API Reference#
Complete API documentation for phasecurvefit.
Main Functions#
order is the primary entry point. With no orderer it runs default_pipeline, an
MST backbone refined by a SOM; fit_track goes on to fit the autoencoder.
- phasecurvefit.order(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], orderer: AbstractOrderer | None = None, *, metadata: StateMetadata | None = None, init: AbstractResult | None = None, weights: Float[Array, 'n_obs'] | None = None)#
Order tracers with
orderer– the primary ordering entry point.With no
orderer,order(positions, velocities)runsdefault_pipeline(): an MST backbone ordering refined by a SOM (MSTOrderer() | SOMOrderer()), falling back to the MST alone when there are too few tracers for the SOM, and bridging any gap in the stream rather than dropping a side of it. It takes noinit(aValueErrorsays so). Pass anyAbstractOrderer– e.g.LocalFlowOrderer()for the velocity-following walk – to select a different algorithm.Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> q = {"x": jnp.array([0.0, 1.0, 2.0])} >>> p = {"x": jnp.array([1.0, 1.0, 1.0])}
The default is an MST backbone refined by a SOM. Three tracers are too few for the SOM, so here it is the MST alone, oriented along the velocity:
>>> pcf.order(q, p).indices Array([0, 1, 2], dtype=int32) >>> pcf.order(q, p).gamma_range # the walk's would be (0.0, 1.0) (-1.0, 1.0)
Or pass an orderer explicitly, e.g. the velocity-following walk:
>>> res = pcf.order(q, p, pcf.orderers.LocalFlowOrderer(metric_scale=1.0)) >>> res.indices Array([0, 1, 2], dtype=int32)
weightsgives each tracer a weight, e.g. the density at each pixel of a density field. Orderers that can use them do (seeorder()), and the result carries them on totrain_autoencoder():>>> pcf.order(q, p, weights=jnp.array([1.0, 2.0, 1.0])).weights Array([1., 2., 1.], dtype=float32)
- Parameters:
positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])orderer (
AbstractOrderer|None)metadata (
StateMetadata|None)init (
AbstractResult|None)weights (
Float[Array, 'n_obs']|None)
- Return type:
AbstractResult
- phasecurvefit.orderers.default_pipeline(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], *, metadata: StateMetadata | None = None, weights: Float[Array, 'n_obs'] | None = None, n_prototypes: int = 15, **som_kwargs: object)#
Order tracers with the library’s default two-stage pipeline.
Chains an MST backbone ordering with a SOM refinement stage –
MSTOrderer(...) | SOMOrderer(n_prototypes=n_prototypes, **som_kwargs). This is whatorder()runs when it is given noorderer. The MST needs no progenitor or start index and orders a stream tip to tip, including near-closed loops whose velocity field reverses; the SOM’s prototypes then average over many tracers, so the final backbone is far less sensitive to local noise than the MST’s individual graph edges. See The self-organizing map.The MST stage is configured to work on data of any scale and to lose nothing, not to be tuned:
jump_cap=inf(the defaultjump_capis an absolute length, which severs every edge of a sparse or large-scale dataset),velocity_factor=30(an edge between tracers moving in different directions costs up to 60 median kNN edge lengths more, so where a stream crosses itself the tree crosses straight over instead of turning onto the other branch),orient_by_velocity=True(sogammaincreases along the flow rather than in an arbitrary tip-to-tip direction), andon_disconnected="connect"(a gap in the stream splits the neighbour graph; the pieces are joined along their shortest links instead of keeping only the largest). Because the MST used velocities, the SOM does too (seeSOMOrderer). For anything else – a finitejump_cap, other velocity settings, outlier clipping, a differentk– build the chain yourself and pass it toorder().Falls back to the MST alone when fewer tracers were visited than
n_prototypes– the SOM’s own minimum (init_prototypes()needs at least that many points to bin). Rather than raise on the library’s own small examples, the SOM stage simply cannot help there, so it is skipped instead of failing.It runs under
jit,vmapandgrad(see Compile, batch and differentiate with JAX). Underjitandvmapthe fallback test uses the number of tracers, which is the number this MST visits: it joins every piece and clips no edges.- Parameters:
positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Phase-space tracers, as fororder().velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Phase-space tracers, as fororder().metadata (
StateMetadata|None) – Passed through to both stages.weights (
Float[Array, 'n_obs']|None) – Per-tracer weights, passed through to both stages: the SOM fits with them and the MST carries them on its result.n_prototypes (
int) – Passed toSOMOrderer; also the threshold below which the SOM stage is skipped.**som_kwargs (
object) – Any otherSOMOrdererkeyword (metric,sigma_end, …).
- Returns:
An
OrderingResult, from the SOM stage when there was enough data and from the MST otherwise. Both carrygamma_range == (-1.0, 1.0).- Return type:
AbstractResult
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> ang = jnp.linspace(0.0, jnp.pi, 60) >>> pos = {"x": 5.0 * jnp.cos(ang), "y": 5.0 * jnp.sin(ang)} >>> vel = {"x": -jnp.sin(ang), "y": jnp.cos(ang)} >>> result = pcf.orderers.default_pipeline(pos, vel, n_prototypes=12) >>> int(result.n_visited) 60
Too few tracers for the SOM stage falls back to the MST alone rather than raising:
>>> q = {"x": jnp.array([0.0, 1.0, 2.0])} >>> p = {"x": jnp.array([1.0, 1.0, 1.0])} >>> pcf.orderers.default_pipeline(q, p).indices Array([0, 1, 2], dtype=int32)
- phasecurvefit.fit_track(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'], metadata: StateMetadata | None = None, weights: Float[Array, 'N'] | None = None, n_prototypes: int = 15, outlier_mixture: SOMMixture | None = SOMMixture(background_density=None, background_inflate=1.0), training_config: TrainingConfig | None = None)#
Order, refine, and fit a smooth track through phase-space tracers.
Runs
default_pipeline()(the MST backbone refined by a SOM stage), builds aPathAutoencodersized to match, and trains it withtrain_autoencoder()– the same three steps as the quickstart and autoencoder guides, in one call.For control over any individual step (a different orderer, a pre-built model, a decoder swap, …), call the pieces directly instead; this is the convenience path, not a replacement for them.
- Parameters:
positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Phase-space tracers.velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Phase-space tracers.key (
Union[Key[Array, ''],UInt32[Array, '2'],UInt32[Array, '4']]) – Split once for model initialization and once for training.metadata (
StateMetadata|None) – Passed through todefault_pipeline().weights (
Float[Array, 'N']|None) – Per-tracer weights, e.g. the density at each pixel of a density field. Passed todefault_pipeline(), whose result carries them on totrain_autoencoder().n_prototypes (
int) – Passed todefault_pipeline().outlier_mixture (
SOMMixture|None) – ASOMMixturefor the SOM stage ofdefault_pipeline(), which then leaves out of the ordering any tracer the curve-or-background mixture calls background. The encoder learns those tracers as non-members, so the track does not bend out to reach interlopers at the stream’s tips. Defaults toSOMMixture(). A fit that calls most tracers background, as it does when they fill their own bounding box like a mask’s pixels, keeps them all.Nonekeeps every tracer in the ordering. With fewer thann_prototypestracers the SOM stage, and so the rejection, is skipped. It works withweights.training_config (
TrainingConfig|None) – Passed totrain_autoencoder().Noneuses its own defaults.
- Return type:
tuple[AbstractResult,AutoencoderResult,Float[Array, 'n_epochs']]- Returns:
ordering_result (AbstractResult) – What
default_pipeline()produced – useful on its own for diagnosing the ordering stage independently of the fit.autoencoder_result (AutoencoderResult) – The trained result: call it with a
gammavalue to interpolate along the fitted track, or read.modelfor the network itself.losses (Array) – Training losses, for diagnosing convergence.
Examples
>>> import jax >>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> ang = jnp.linspace(0.0, jnp.pi, 60) >>> pos = {"x": 5.0 * jnp.cos(ang), "y": 5.0 * jnp.sin(ang)} >>> vel = {"x": -jnp.sin(ang), "y": jnp.cos(ang)} >>> cfg = pcf.nn.TrainingConfig( ... n_epochs_encoder=5, n_epochs_decoder=5, n_epochs_both=5, show_pbar=False ... ) >>> ordering, fitted, losses = pcf.fit_track( ... pos, vel, key=jax.random.key(0), n_prototypes=12, training_config=cfg ... ) >>> int(ordering.n_visited) 60 >>> fitted.model.normalizer.n_spatial_dims 2
- phasecurvefit.bootstrap_track(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'], n_samples: int = 20, weights: Float[Array, 'N'] | None = None, **fit_options: Any)#
Fit a track and its uncertainty, by refitting bootstrap resamples.
Runs
fit_track()once on all the data, thenn_samplesmore times, each onNtracers drawn from theNwith replacement and with its own training key. Every stage is refitted, so the spread of the members covers the ordering, the outlier clipping, the membership, the training and the noise in the data.A resample repeats some tracers and leaves out others. Repeats are passed as repeated rows, so
weightsstay free for their own meaning.- Parameters:
positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Phase-space tracers.velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Phase-space tracers.key (
Union[Key[Array, ''],UInt32[Array, '2'],UInt32[Array, '4']]) – Split once for the reference fit and once for each member.n_samples (
int) – Number of resamples. Each costs onefit_track().weights (
Float[Array, 'N']|None) – Per-tracer weights, as infit_track(). A resampled tracer keeps its weight. A bootstrap treats each tracer as one independent draw, so it gives an honest uncertainty only when the tracers are independent, for example stars, and not the pixels of an image.**fit_options (
Any) – Any other option offit_track(), such astraining_configoroutlier_mixture, passed to every call.
- Returns:
The full-data fit and the fits to the resamples.
- Return type:
Examples
>>> import jax >>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> ang = jnp.linspace(0.0, jnp.pi, 60) >>> pos = {"x": 5.0 * jnp.cos(ang), "y": 5.0 * jnp.sin(ang)} >>> vel = {"x": -jnp.sin(ang), "y": jnp.cos(ang)} >>> cfg = pcf.nn.TrainingConfig( ... n_epochs_encoder=5, n_epochs_decoder=5, n_epochs_both=5, show_pbar=False ... ) >>> ens = pcf.bootstrap_track( ... pos, ... vel, ... key=jax.random.key(0), ... n_samples=2, ... n_prototypes=12, ... training_config=cfg, ... ) >>> len(ens.members) 2 >>> gamma = jnp.linspace(*ens.reference.track_range, 5) >>> ens.offsets(gamma).shape (2, 5, 2)
- class phasecurvefit.TrackEnsemble(reference: AutoencoderResult, members: tuple[AutoencoderResult, ...])#
Bases:
ReprMixin,ModuleA fit to the data and fits to bootstrap resamples of it.
Made by
bootstrap_track().referenceis the track fitted to all the data, andmembersare the tracks fitted to resamples. The spread of the members about the reference is the track’s uncertainty.Each fit has its own $gamma$, so members are compared with the reference in space: at a point on the reference, a member’s offset is the vector from that point to the member’s nearest point, minus its component along the reference’s tangent.
- Variables:
reference (AutoencoderResult) – The track fitted to all the data.
members (tuple[AutoencoderResult, ...]) – The tracks fitted to the resamples.
- Parameters:
reference (AutoencoderResult)
members (tuple[AutoencoderResult, ...])
:ivar
offsets()andradius()only call each track on $gamma$ and: :ivar read itstrack_range, so code that uses the band should not depend on: :ivar the members beingAutoencoderResult.:- Parameters:
reference (
AutoencoderResult)members (
tuple[AutoencoderResult,...])
-
reference:
AutoencoderResult#
-
members:
tuple[AutoencoderResult,...]#
- offsets(gamma: Float[Array, 'G'], /, *, n_dense: int = 1000)#
Offset of each member from the reference, across the reference.
- Parameters:
gamma (
Float[Array, 'G']) – Points on the reference, as its own $gamma$ (withinreference.track_range).n_dense (
int) – Points at which each member’s track is evaluated, over itstrack_range, to find the one nearest each reference point.
- Returns:
The perpendicular offsets, with shape
(n_members, len(gamma), n_spatial_dims)and the last axis in the order of the position components. With Quantity tracks they are a Quantity in the unit of the first position component. NaN where a member’s nearest point is one of its ends, which means its track stops short of that reference point.- Return type:
Array
- radius(gamma: Float[Array, 'G'], /, level: float = 0.68, *, n_dense: int = 1000)#
Radius of the tube about the reference that holds
levelof the members.At each point it is the
levelquantile of the members’ distances from the reference (the norms ofoffsets()). A member whose track stops short of that point counts as outside the tube, so the radius is NaN where fewer thanlevelof the members reach. Plot the reference with this radius on either side of it.It measures the variance of the fit and not its bias, so where the track bends the true curve can lie outside it more often than
levelimplies; see the explanation page on track uncertainty.With Quantity tracks it is a Quantity, in the unit of the first position component, as
offsets()is.
- phasecurvefit.combine_results(result_fwd, result_bwd, /)#
Combine forward and reverse flow walk results into a single result.
Takes the results from two separate local-flow walks (one forward, one reverse) and combines them into a single coherent ordering. This is useful for tracing complete stellar streams that extend in both directions from a starting point.
The combination strategy assumes both walks started from the same index:
Forward walk: [start_idx, idx1_fwd, idx2_fwd, …]
Backward walk: [start_idx, idx1_bwd, idx2_bwd, …]
Combined: [idx2_bwd, idx1_bwd, start_idx, idx1_fwd, idx2_fwd, …]
Duplicate indices are removed while preserving order, ensuring each point appears only once in the final ordering.
- Parameters:
result_fwd (WalkLocalFlowResult) – Result from a forward walk (direction=’forward’).
result_bwd (WalkLocalFlowResult) – Result from a backward walk (direction=’backward’), typically starting from the same index as the forward walk.
- Returns:
{class}`~typing.NamedTuple` with combined ordering that includes both forward and backward traversals. Indices are ordered from the backward tail through the starting point to the forward tail. The gamma_range is stitched together: if result_bwd has gamma_range [min_bwd, 0] and result_fwd has gamma_range [0, max_fwd], the combined result has gamma_range [min_bwd, max_fwd].
- Return type:
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf
Create phase-space data for a stream extending in both directions:
>>> pos = { ... "x": jnp.array([0.0, 1.0, 2.0, 3.0, 4.0]), ... "y": jnp.array([0.0, 0.1, 0.2, 0.3, 0.4]), ... } >>> vel = { ... "x": jnp.array([1.0, 1.0, 1.0, 1.0, 1.0]), ... "y": jnp.array([0.1, 0.1, 0.1, 0.1, 0.1]), ... }
Run forward and backward walks from the middle:
>>> fwd = pcf.orderers.LocalFlowOrderer(start_idx=2, metric_scale=0.5) >>> bwd = pcf.orderers.LocalFlowOrderer( ... start_idx=2, metric_scale=0.5, direction="backward" ... ) >>> result_fwd = pcf.order(pos, vel, fwd) >>> result_bwd = pcf.order(pos, vel, bwd)
Combine the results:
>>> result = pcf.combine_results(result_fwd, result_bwd) >>> result.indices Array([4, 3, 0, 1, 2], dtype=int32)
This combines the forward walk (2→3→4) and backward walk (2→1→0) into a single ordering (0, 1, 2, 3, 4).
Notes
The combined ordering places the starting point near the center, with the backward walk indices on the left and forward walk indices on the right. This is useful for:
Tracing complete stellar streams from a central progenitor
Exploring both tidal tails of a disrupting stream
Verifying stream connectivity in both directions
Handling bifurcated or complex stream geometries
Orderers#
Pluggable ordering stages, composable with |. See the
Orderers guide.
- class phasecurvefit.orderers.AbstractOrderer#
Bases:
ReprMixin,ModuleBase class for ordering algorithms.
Subclasses carry their own hyperparameters and implement
order().- abstractmethod order(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], *, metadata: StateMetadata | None = None, init: AbstractResult | None = None, weights: Float[Array, 'n_obs'] | None = None)#
Order the tracers and return a result the autoencoder can consume.
weightsare optional per-observation weights, shape(n_obs,), finite and non-negative. An orderer that can use them (SOMOrderer) does; one that cannot (MSTOrderer,LocalFlowOrderer) orders as if they were absent. Every built-in orderer carries them through on the result’sweights, so a later chain stage andtrain_autoencoder()see them too.initis an optional result from a previous ordering stage. An orderer that can refine a prior ordering uses it –LocalFlowOrderertakes its start index from it – and one that cannot should still accept and ignore it, since acceptinginitis what makes an orderer usable anywhere but the head of a chain.An orderer that restricts itself to a subset of
init(e.g. one that works only oninit.indices, the visited observations) must not reintroduce observations the prior stage rejected as outliers – points left unvisited (-1inindices) stay unvisited. There is nothing inChainOrdererthat enforces this; it is a convention every implementation is responsible for keeping.- Parameters:
- Return type:
AbstractResult
- class phasecurvefit.orderers.LocalFlowOrderer(metric_scale: float = 1.0, config: ~phasecurvefit._src.query_config.WalkConfig = <factory>, start_idx: int | None = None, direction: ~typing.Literal['forward', 'backward', 'both'] = 'forward', max_dist: float = inf, terminate_indices: frozenset[int] | None = None, n_max: int | None = None, nan_policy: ~typing.Literal['raise', 'omit'] = 'raise')#
Bases:
AbstractOrdererOrder tracers with the velocity-following local-flow walk.
This is the primary way to run the walk, via the uniform orderer interface:
pcf.order(positions, velocities, pcf.orderers.LocalFlowOrderer()). It is not whatpcf.orderruns with no orderer – that is the MST | SOM default pipeline.order()handlesdirection="both"internally viacombine_results.The walk, with its momentum-weighted metric, is the algorithm of Nibauer et al. (2022); if you use it in published work, please cite that paper (see Citation).
- Parameters:
metric_scale (
float) – Metric-dependent scale parameter.config (
WalkConfig) – Neighbor-query configuration (metric + strategy).Index of the starting observation.
None(the default) takes the start frominitwhen the walk is chained after another orderer, and falls back to0when it is not.The walk has to be told where a curve ends, and picking that index by hand means knowing the answer in advance. An
MSTOrdererfinds the two tips itself – its ordering is the graph diameter, tip to tip – so its first ordered observation is a genuine endpoint:( pcf.orderers.MSTOrderer(k=16, jump_cap=3.0) | pcf.orderers.LocalFlowOrderer() )
An explicit
start_idxalways wins, chained or not.direction (
Literal['forward','backward','both']) –"forward","backward", or"both". Under"both"each half stops where it would turn back toward the start, so it covers only its own side ofstart_idx.max_dist (
float) – Maximum allowed neighbor distance.terminate_indices (
frozenset[int] |None) – Indices that terminate the walk when reached.nan_policy (
Literal['raise','omit']) –What to do with a NaN velocity when the metric reads velocities (the default
AlignedMomentumDistanceMetricdoes). A position-only metric never reads them, so never raises."raise"(default) raisesValueError(underjit, at run time, a JAX runtime error carrying the same message)."omit"treats NaN as a missing measurement (catalogues often lack radial velocities): any step whose metric distance is not finite is scored by position alone, so from a tracer without a velocity the walk takes its nearest unvisited neighbour.A zero velocity is data (a stationary tracer), not missing: under the default metric that step is plain nearest-neighbour. An infinite one is neither, so it raises under either policy.
-
config:
WalkConfig#
- order(positions, velocities, *, metadata=None, init=None, weights=None)#
Run the local-flow walk and return its result.
weightsdo not change the walk; they are validated and carried through on the result.- order(self: LocalFlowOrderer, positions: Mapping[str, jaxtyping.Real[AbstractQuantity, 'N']], velocities: Mapping[str, jaxtyping.Real[AbstractQuantity, 'N']], *, metadata: StateMetadata | None = None, init: phasecurvefit._src.abstract_result.AbstractResult | None = None, weights: jaxtyping.Float[Array, 'n_obs'] | None = None) WalkLocalFlowResult
- Parameters:
positions (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
velocities (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
metadata (StateMetadata | None)
init (AbstractResult | None)
weights (Float[Array, 'n_obs'] | None)
- Return type:
Order Quantity-valued tracers with the local-flow walk.
Delegates to the local-flow walk’s Quantity dispatch. Scalar hyperparameters (
metric_scale,max_dist) that are plain numbers are interpreted in theusyslength unit.A plain
metric_scalebeing labelled a length regardless of the configured metric looks like the same bug as #85’sSOMOrdererone at first glance, but it is not: whatever unit it is wrapped in here is immediately stripped back out by_local_flow_walk’s own Quantity dispatch (viau.ustrip(usys, metric_scale)), and stripping a bare number’s wrapper back out through the sameusysit was wrapped with is a no-op regardless of which dimension was chosen – verified: a bare50.0and bothu.Q(50.0, "kpc")andu.Q(50.0, "Myr")produce identical orderings here.SOMOrdererdiffers because itsmetric_scalewas never stripped at all before reaching its non-quaxplain-array core.- Parameters:
- Return type:
- class phasecurvefit.orderers.MSTOrderer(k: int = 10, jump_cap: float = 3.0, velocity_weight: float = 0.0, velocity_factor: float = 0.0, sever_cos_threshold: float | None = None, orient_by_velocity: bool = False, on_disconnected: Literal['raise', 'warn', 'largest', 'connect'] = 'raise', edge_clip_sigma: float | None = None, edge_clip_max_iters: int = 5, neighbors: AbstractNeighborSearch | None = None, nan_policy: Literal['raise', 'omit'] = 'raise')#
Bases:
AbstractOrdererOrder tracers along the MST longest-path backbone.
- Parameters:
k (
int) – Number of nearest neighbours for the kNN graph.jump_cap (
float) – Edges longer than this (spatially) are severed before building the MST. Should exceed the typical inter-tracer spacing but stay below the loop-opening / arm-separation scale.velocity_weight (
float) – Mechanism 1. If> 0, edge weights become||dq|| + velocity_weight * (1 - cos(v_i, v_j)).0(default) is pure spatial and never reads velocities. Seenan_policyfor missing velocities.velocity_weightis a length, in the units of the positions;velocity_factoris the unit-free form.velocity_factor (
float) – Mechanism 1 without units: the same penalty withvelocity_weight = velocity_factor * L, whereLis the median length of the kNN edges. So it means the same at any scale and in any unit. It adds tovelocity_weightif both are set.0(default) is off. At a crossing the edges between the branches can be much shorter thanL; a penalty that adds a length, not one that multiplies the edge’s own length, is what keeps them out of the tree.sever_cos_threshold (
float|None) –Mechanism 2. If not
None, edges withcos(v_i, v_j)below this are severed (e.g.0.0cuts anti-parallel arms).For mechanisms 1 and 2, a stationary (zero-velocity) tracer has no direction to compare, and any cosine it is given lets it bridge two close, anti-parallel arms. So it joins the graph only as a leaf, by its shortest kNN edge (within
jump_cap) to a tracer that has a direction: a leaf cannot join two components. Many of them close together (~10% of a tight hairpin atk=6) still remove the edges that ran through them and can fragment an arm; raisekthen.orient_by_velocity (
bool) – Mechanism 3. IfTrue, flip the ordering sogammaincreases along the mean velocity.on_disconnected (
Literal['raise','warn','largest','connect']) – Policy when the graph splits into multiple components (a gap in the stream, or ajump_cap/sever_cos_thresholdthat is too tight):"raise"(default),"warn"(order the largest component, warn, leave the rest unvisited),"largest"(same, silently), or"connect"(join the pieces along their shortest links and order everything; the bridge links ignorejump_capand velocity severing, which is what split the graph)."connect"always finds the bridging links with the exact kd-tree (excludequery), whicheverneighborsbackend is set.edge_clip_sigma (
float|None) – Optional outlier rejection by MST edge length. If notNone, robustly sigma-clip the backbone’s spatial edge lengths in log space: cut edges longer thanmedian * exp(edge_clip_sigma * 1.4826 * MAD(log L))(never shorter than twice the median), split off the small components this isolates, and repeat (seeedge_clip_max_iters). Interlopers the MST threads in along one long edge fall away and are left unvisited (indices == -1); the rest of the stream is kept and reconnected (bridged again underon_disconnected="connect"if a rejected interloper was what joined two pieces; otherwise the largest is kept), so a sparse but continuous tail is not rejected.None(default) disables clipping. Loweredge_clip_sigmaclips more aggressively.edge_clip_max_iters (
int) – Maximum sigma-clip iterations (default 5). Ignored whenedge_clip_sigmaisNone.neighbors (
AbstractNeighborSearch|None) – The exact kNN backend (phasecurvefit.neighbors).None(default) picks per call:SciPy()when the inputs are concrete (fastest on CPU, no compilation) andBucketKDTree()when they are traced by jit/vmap/grad. Or pin one:BucketKDTree()(JAX-native, traceable; compiles once per size bucket),BruteForce(),JaxKD()(optional dependency), orSciPy(workers=-1)(host-only: it raises inside jit/vmap/grad, even on arrays a jitted function captures). With equidistant neighbours SciPy andBucketKDTreemay pick differently, so the default’s eager and traced orderings can differ on tied (e.g. grid) data; pin a backend if that matters.nan_policy (
Literal['raise','omit']) –What to do with a NaN velocity when a mechanism reads velocities (
velocity_weight > 0,velocity_factor > 0,sever_cos_thresholdororient_by_velocity). The pure-spatial default never reads them, so never raises."raise"(default) raisesValueError(underjit, ajax.errors.JaxRuntimeErrorwhose message omits the counts and the first offending index, which are not known at trace time)."omit"treats NaN as a missing measurement (catalogues often lack radial velocities): for mechanisms 1 and 2 it joins the graph as a leaf, like a stationary tracer, and mechanism 3 skips it. That is an opt-in, not a safe default: the leaf goes to the spatially nearest tracer with a direction, which on two close arms can be the other arm.A zero velocity is data (a stationary tracer), not missing. An infinite one is neither, so it raises under either policy.
Examples
Order a simple 2D stream using the MST backbone:
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf
>>> positions = { ... "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]), ... } >>> velocities = {"x": jnp.ones(5), "y": jnp.full(5, 0.5)}
>>> orderer = pcf.orderers.MSTOrderer(k=10, jump_cap=3.0) >>> result = pcf.order(positions, velocities, orderer) >>> result.indices Array([4, 3, 2, 1, 0], dtype=int32)
For near-closed loops where the velocity field reverses, use
velocity_weightto penalize edges between opposite-moving arms:>>> # Synthetic near-closed loop (two arms moving in opposite directions) >>> theta = jnp.linspace(0, 2 * jnp.pi, 100) >>> positions = {"x": jnp.cos(theta), "y": jnp.sin(theta)} >>> # Velocity tangent to the circle, but reversing at the crossing >>> velocities = {"x": -jnp.sin(theta), "y": jnp.cos(theta)}
Use
velocity_weightto down-weight edges between opposite-moving regions:>>> orderer = pcf.orderers.MSTOrderer(k=10, jump_cap=2.0, velocity_weight=1.0) >>> result = pcf.order(positions, velocities, orderer) >>> result.n_visited > 0 # Most points ordered Array(True, dtype=bool)
Alternatively, use
sever_cos_thresholdto explicitly cut edges where velocities are anti-parallel:>>> orderer = pcf.orderers.MSTOrderer(k=10, jump_cap=2.0, sever_cos_threshold=0.0) >>> result = pcf.order(positions, velocities, orderer)
The result includes a
backbonepolyline (the MST longest path) that__call__uses for smooth interpolation:>>> result.backbone is not None True >>> result.backbone["x"].shape (100,)
Orient the ordering to increase along the mean velocity using
orient_by_velocity:>>> orderer = pcf.orderers.MSTOrderer(k=10, jump_cap=2.0, orient_by_velocity=True) >>> result = pcf.order(positions, velocities, orderer)
Reject an interloper by MST edge length with
edge_clip_sigma. Here a lone point sits far off an otherwise clean line; clipping leaves it unvisited:>>> xs = jnp.concat([jnp.linspace(0.0, 9.0, 40), jnp.array([30.0])]) >>> ys = jnp.concat([jnp.zeros(40), jnp.array([30.0])]) >>> pos = {"x": xs, "y": ys} >>> vel = {"x": jnp.ones(41), "y": jnp.zeros(41)} >>> clipper = pcf.orderers.MSTOrderer(k=10, jump_cap=50.0, edge_clip_sigma=3.0) >>> result = pcf.order(pos, vel, clipper) >>> int(result.n_skipped) # the lone interloper is rejected 1
-
neighbors:
AbstractNeighborSearch|None= None#
- order(positions, velocities, *, metadata=None, init=None, weights=None)#
Order tracers along the MST backbone.
weightsdo not change the tree, which is built from geometry alone; they are validated and carried through on the result.Three stages. (a) The kNN runs in the
neighborsbackend (by default SciPy when the inputs are concrete,BucketKDTreewhen traced). (b) The graph algorithms (MST, components, diameter, edge-clip, bridging) and (c) the arc-length projection and ordering run in pure JAX forBucketKDTree,BruteForceandJaxKD, soorder()traces underjax.jit/vmap/gradwith no host callback. WithSciPyevery stage runs eagerly in NumPy/SciPy, and a traced call raisesTypeError.on_disconnected="raise"raisesValueErrorwhen called eagerly; under tracing it is a runtime check (equinox.error_if) whose message says “multiple components” instead of the count."warn"warns in both cases (throughjax.debug.callbackwhen traced). Velocity checks (nan_policy) behave the same way.- order(self: MSTOrderer, positions: Mapping[str, jaxtyping.Real[AbstractQuantity, 'N']], velocities: Mapping[str, jaxtyping.Real[AbstractQuantity, 'N']], *, metadata: StateMetadata | None = None, init: phasecurvefit._src.abstract_result.AbstractResult | None = None, weights: jaxtyping.Float[Array, 'n_obs'] | None = None) OrderingResult
- Parameters:
positions (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
velocities (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
metadata (StateMetadata | None)
init (AbstractResult | None)
weights (Float[Array, 'n_obs'] | None)
- Return type:
Order Quantity-valued tracers with the MST backbone.
See
_order_with_backbone_and_chordfor the strip/run/reattach body shared withSOMOrderer’s dispatch below.- Parameters:
- Return type:
- class phasecurvefit.orderers.SOMOrderer(n_prototypes: int = 25, metric: AbstractDistanceMetric | None = None, metric_scale: float | Float[Array, ''] | None = None, n_epochs: int = 10, sigma_start: float | None = None, sigma_end: float = 0.7, densify_factor: int = 5, orient_by_velocity: bool = False, outlier_mixture: SOMMixture | None = None, nan_policy: Literal['raise', 'omit'] = 'raise')#
Bases:
AbstractOrdererOrder tracers by projection onto a trained 1-D Self-Organizing Map.
- Parameters:
n_prototypes (
int) – Number of SOM prototypes,K. More prototypes track finer structure at the cost of following noise; the paper finds results insensitive to the exact value above roughly 10 per distinct segment of the curve.metric (
AbstractDistanceMetric|None) –Phase-space distance metric for the best-matching-unit search and the backbone assignment.
None(the default) followsinit: after a stage that used velocity it isFullPhaseSpaceDistanceMetric, and otherwiseSpatialDistanceMetric.Ordering on position alone after a stage that used velocity undoes that stage’s work: at a self-crossing the two branches are spatially coincident and only their velocities differ, so a position-only SOM re-conflates exactly what the earlier stage separated.
metricmust be symmetric in the two points it compares.AlignedMomentumDistanceMetricis not: it scores “forward along the direction of travel”, which is what a greedy walk step needs and not what nearest-prototype means. Passing it collapses the lattice toward the curve’s head.metric_scale (
float|Float[Array, '']|None) –Scale handed to
metric.None(the default) derives it assigma_phys / (2 |v|)when following a velocity-awareinit, and is0.0otherwise. The derived value makes the velocity term separate anti-parallel branches by about the distance the lattice can already resolve.Set it explicitly to override. It is a time, converting velocity differences into position units, so its right value depends on your unit system. Too large and “nearest prototype” becomes “nearest in velocity”, which on a winding curve conflates points a whole turn apart. A non-zero value with
SpatialDistanceMetric, which ignores it, is rejected at construction.n_epochs (
int) – Number of batch-Kohonen epochs.sigma_start (
float|None) – Neighbourhood width in lattice units at the first and last epoch, annealed geometrically. Wheninitis supplied,sigma_start=Noneusessigma_endinstead: a wide start would smooth away the very ordering the prior stage just computed. Standalone,sigma_start=Noneusesmax(n_prototypes / 4, sigma_end), i.e.n_prototypes / 4floored atsigma_endso the anneal is never inverted on a very small lattice.sigma_end (
float) – Neighbourhood width in lattice units at the first and last epoch, annealed geometrically. Wheninitis supplied,sigma_start=Noneusessigma_endinstead: a wide start would smooth away the very ordering the prior stage just computed. Standalone,sigma_start=Noneusesmax(n_prototypes / 4, sigma_end), i.e.n_prototypes / 4floored atsigma_endso the anneal is never inverted on a very small lattice.densify_factor (
int) – Backbone samples per prototype segment.orient_by_velocity (
bool) –If
True, flip the result so the chord increases along the mean velocity, mirroringMSTOrderer’s option of the same name. The SOM has no progenitor anchor – the paper fixes the lattice’s first point to the origin (§2.2.2 step 1) and this implementation does not – so a standalone ordering’s direction is otherwise arbitrary: it comes from the sign of the initializer’s principal-axis eigenvector, which is stable but meaningless.Note this overrides an inherited direction rather than deferring to it: chained after a stage that already fixed one, setting this can silently reverse that stage’s choice. Default
False, matchingMSTOrderer.outlier_mixture (
SOMMixture|None) – ASOMMixtureto reject outliers, orNone(default) for none. Without it the SOM has no outlier rejection, and field contamination drags the backbone off the curve while the ordering still looks good. With it, each tracer’s position is modelled as drawn either from the curve or from a flat background, and each tracer counts in the prototype update by its posterior membership. A tracer whose final membership is below 0.5 gets-1inOrderingResult.indicesandnaninOrderingResult.chord, the same contract as a point a prior stage never visited. It combines withweights: a weight multiplies a tracer’s terms and never changes its membership. Seephasecurvefit.som.fit()for the algorithm.nan_policy (
Literal['raise','omit']) –What to do with a NaN velocity when this stage reads velocities, i.e. with a velocity-aware
metricororient_by_velocity. A position-only stage never reads them, so never raises."raise"(default) raisesValueError(underjit, at run time, a JAX runtime error carrying the same message)."omit"treats NaN as a missing measurement (catalogues often lack radial velocities): it is left out of the prototype velocity averages, a tracer whosemetricdistances are not all finite is matched by position alone, and it is skipped when orienting. More missing velocities move the ordering toward the position-only one.A zero velocity is data (a stationary tracer), not missing. An infinite one is neither, so it raises under either policy.
Notes
order()is JAX-traceable underjit,vmapandgrad, both standalone and chained after another stage. Chained, the SOM keeps allNobservations at a fixed shape and masks out the ones the prior stage left unvisited: they get zero weight in the fit and stay-1inOrderingResult.indices. The equi-frequency binning that seeds the lattice counts only the visited ones, in the prior stage’s order. The disagreement warning needs concrete values, so it is skipped underjitandvmap.Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf
>>> ang = jnp.linspace(0.0, jnp.pi, 60) >>> pos = {"x": 5.0 * jnp.cos(ang), "y": 5.0 * jnp.sin(ang)} >>> vel = {"x": -jnp.sin(ang), "y": jnp.cos(ang)}
>>> result = pcf.order(pos, vel, pcf.orderers.SOMOrderer(n_prototypes=10)) >>> int(result.n_visited) 60
The result carries both a smooth backbone and the arc-length chord:
>>> result.backbone["x"].shape (46,) >>> result.chord.shape (60,)
As a refinement stage after another orderer:
>>> chain = pcf.orderers.MSTOrderer(k=8, jump_cap=3.0) | pcf.orderers.SOMOrderer( ... n_prototypes=10 ... ) >>> int(pcf.order(pos, vel, chain).n_visited) 60
-
metric:
AbstractDistanceMetric|None= None#
-
outlier_mixture:
SOMMixture|None= None#
- order(positions, velocities, *, metadata=None, init=None, weights=None)#
Train a SOM and order the tracers by their chord parameter.
weightsweigh each tracer in the batch-Kohonen update (omega_ninfit()), so the prototypes follow the weighted density, and combine withoutlier_mixture.- order(self: SOMOrderer, positions: Mapping[str, jaxtyping.Real[AbstractQuantity, 'N']], velocities: Mapping[str, jaxtyping.Real[AbstractQuantity, 'N']], *, metadata: StateMetadata | None = None, init: phasecurvefit._src.abstract_result.AbstractResult | None = None, weights: jaxtyping.Float[Array, 'n_obs'] | None = None) OrderingResult
- Parameters:
positions (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
velocities (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
metadata (StateMetadata | None)
init (AbstractResult | None)
weights (Float[Array, 'N'] | None)
- Return type:
Order Quantity-valued tracers with the SOM.
See
_order_with_backbone_and_chordfor the strip/run/reattach body shared withMSTOrderer’s dispatch above.metric_scale, unlikepositions/velocities, is not stripped by that shared body: it is a field onself, not a call argument, and the SOM core is plain-array math with noquaxawareness, so a Quantity left on it reachesmetric_scale * d_vel(e.g. insideFullPhaseSpaceDistanceMetric’s(metric_scale * d_vel) ** 2) still unit-ful, whiled_velis already a bare number – raising deep inside the metric rather than here.- Parameters:
- Return type:
- class phasecurvefit.orderers.RidgeOrderer(bandwidth: float | Float[Array, ''] | None = None, k: int = 8, core: float = 0.2, trim: float = 0.5)#
Bases:
AbstractOrdererOrder samples along the ridge of their weighted density.
- Parameters:
bandwidth (
float|Float[Array, '']|None) – Width of the Gaussian kernel for the density estimate, in position units: roughly the half-width of the stream. Too small and the ridge follows noise or pixel structure; too large and it cuts bends.None(default) estimates it from the data. It starts at a tenth of the data’s extent, finds the backbone, sets the bandwidth to the weighted RMS distance of the samples from the backbone, and repeats until that changes by less than 2%. The estimate runs on a random subsample of at most 2000 samples, and is never below their median nearest-neighbour spacing.k (
int) – Neighbours each sample links to in the graph the ridge path runs on.core (
float) – Density, as a fraction of its peak, above which a sample can be an end.trim (
float) – The backbone is cut where the density along it falls below this fraction of its median.
Notes
The ends are found to within about
bandwidth: the longest path through the core starts at its far corner, off the ridge, and a uniform image’s round caps hold more density than a blurred line’s ends, sotrimstops a little past them. A highercorenarrows the core around the ridge, but too high a value splits it at any gap in the stream, and then the backbone covers only one side of the gap.Past 10 000 samples the backbone is found on a random subsample of 10 000 with positive weight (fixed seed), and every sample is then projected onto it. Pixels much finer than the bandwidth add nothing to the density, and the full set would pair every pixel with tens of thousands of others.
Examples
An image of a blurred arc: each pixel is a sample weighted by its density.
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> g = jnp.linspace(-1.5, 1.5, 61) >>> X, Y = jnp.meshgrid(g, g) >>> R = jnp.hypot(X, Y) >>> image = jnp.exp(-((R - 1.0) ** 2) / (2 * 0.1**2)) * (Y > 0) >>> keep = image.ravel() > 0.05 >>> pos = {"x": X.ravel()[keep], "y": Y.ravel()[keep]} >>> vel = {"x": jnp.zeros_like(pos["x"]), "y": jnp.zeros_like(pos["y"])} >>> result = pcf.order( ... pos, ... vel, ... pcf.orderers.RidgeOrderer(), ... weights=image.ravel()[keep], ... ) >>> radius = jnp.hypot(result.backbone["x"], result.backbone["y"]) >>> bool(jnp.median(jnp.abs(radius - 1.0)) < 0.03) True
- order(positions, velocities, *, metadata=None, init=None, weights=None)#
Order samples along the ridge of their weighted density.
- order(self: RidgeOrderer, positions: Mapping[str, jaxtyping.Real[AbstractQuantity, 'N']], velocities: Mapping[str, jaxtyping.Real[AbstractQuantity, 'N']], *, metadata: StateMetadata | None = None, init: phasecurvefit._src.abstract_result.AbstractResult | None = None, weights: jaxtyping.Float[Array, 'n_obs'] | None = None) OrderingResult
- Parameters:
positions (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
velocities (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
metadata (StateMetadata | None)
init (AbstractResult | None)
weights (Float[Array, 'N'] | None)
- Return type:
Order Quantity-valued samples along the ridge of their density.
bandwidthis a length. A Quantity is stripped intousys’s length unit, the unit the positions are stripped into; a bare number is taken to be in that unit already.- Parameters:
- Return type:
- class phasecurvefit.orderers.ChainOrderer(*stages: AbstractOrderer)#
Bases:
AbstractOrdererRun several orderers in sequence, threading results forward.
- Parameters:
*stages (
AbstractOrderer) – The orderers to run, in order. Nested chains are flattened, soa | b | cyields one three-stage chain rather than a nest.
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf
>>> pos = {"x": jnp.linspace(0.0, 3.0, 4), "y": jnp.zeros(4)} >>> vel = {"x": jnp.ones(4), "y": jnp.zeros(4)}
>>> chain = pcf.orderers.ChainOrderer( ... pcf.orderers.LocalFlowOrderer(), pcf.orderers.LocalFlowOrderer() ... ) >>> chain.order(pos, vel).indices Array([0, 1, 2, 3], dtype=int32)
The
|operator builds the same thing, and flattens:>>> chain = pcf.orderers.LocalFlowOrderer() | pcf.orderers.LocalFlowOrderer() >>> len(chain.stages) 2
-
stages:
tuple[AbstractOrderer,...]#
- order(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], *, metadata: StateMetadata | None = None, init: AbstractResult | None = None, weights: Float[Array, 'n_obs'] | None = None)#
Run each stage in turn, feeding its result to the next as
init.weightsgo to every stage.- Parameters:
- Return type:
AbstractResult
- class phasecurvefit.orderers.OrderingResult(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], indices: Int[Array, 'N'], *, gamma_range: tuple[float, float] = (0.0, 1.0), velocity_aware: bool = False, backbone: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']] | None = None, backbone_size: Int[Array, ''] | None = None, chord: Float[Array, 'N'] | None = None, weights: Float[Array, 'N'] | None = None)#
Bases:
AbstractResultUnified result of an ordering algorithm.
- Variables:
positions (dict[str, Array]) – Original (not reordered) position components, 1D arrays of shape
(n_obs,).velocities (dict[str, Array]) – Original velocity components, same shape as
positions.indices (Int[Array, " n_obs"]) –
Observation indices in visit order, padded with
-1for unvisited observations. The position in the array is the step in the ordering and the value is the original observation index:indices = [3, 7, 1, 5, -1, -1] # ^ 1st is observation 3 # ^ 2nd is observation 7, and so on # ^ two observations were not visited
Use ordering for the visited indices alone.
gamma_range (tuple[float, float]) – Static valid range of the ordering parameter for
__call__.backbone (dict[str, Array] | None) – Optional ordered polyline (tip-to-tip) that
__call__interpolates along.Nonefor walk-style results, which interpolate along the ordered visited observations instead.backbone_size (Int[Array, ""] | None) – Number of valid leading vertices in
backbonewhen it has been padded to a static shape (e.g. byMSTOrderer, whose backbone length is data-dependent and so unknown at trace time underjit/vmap).None(default) means every vertex inbackboneis valid.chord (Float[Array, " n_obs"] | None) –
Arc length along the curve this result represents, per observation, in input order – not reordered. Unvisited observations carry
nan.This is the physical along-track coordinate: the distance travelled from the curve’s start, in position units. Unlike the ordering, it is continuous and it reflects how the observations are actually spaced, so it is the natural affine parameter for a downstream fit.
Nonewhen the orderer does not provide one, in which case consumers fall back to index-uniform spacing.weights (Float[Array, " n_obs"] | None) – Per-observation weights, in input order, as passed to
order().None(default) means every observation counts equally. Orderers carry them through unchanged so thattrain_autoencoder()picks them up from the result. A density field enters as one observation per pixel, weighted by the density there.velocity_aware (bool) – Inherited from
AbstractResult. For an orderer, it reflects the metric it was configured with – seeAbstractDistanceMetric.uses_velocity– not any scale parameter: a zero scale makes a phase-space metric numerically position-only, but the orderer is still configured to use velocity. Orderers that order on position alone leave itFalse.
- Parameters:
positions (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
velocities (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
indices (Int[Array, 'N'])
velocity_aware (bool)
backbone (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']] | None)
backbone_size (Int[Array, ''] | None)
chord (Float[Array, 'N'] | None)
weights (Float[Array, 'N'] | None)
Notes
Accessors, all derived from
indices:visited: boolean mask over observations, in input order
n_visited, n_skipped, all_visited: counts and a summary flag
ordering: visited indices in order (
indiceswithout the-1)skipped_indices: indices of observations that were not visited
ordered: positions and velocities reordered along the ordering
Calling the result,
result(gamma), interpolates a position along the ordering for any $gamma$ ingamma_range: alongbackbonewhen there is one, otherwise between the visited observations in order.Examples
Create an
OrderingResultfrom ordering observations:>>> import jax.numpy as jnp >>> import phasecurvefit as pcf
>>> # Define phase-space data >>> positions = { ... "x": jnp.array([0.0, 1.0, 2.0, 3.0]), ... "y": jnp.array([0.0, 0.5, 1.0, 1.5]), ... } >>> velocities = {"x": jnp.ones(4), "y": jnp.full(4, 0.5)} >>> indices = jnp.array([0, 1, 2, 3]) # All observations visited
>>> # Create a result object >>> result = pcf.orderers.OrderingResult( ... positions=positions, ... velocities=velocities, ... indices=indices, ... gamma_range=(0.0, 1.0), ... )
Access ordering properties:
>>> result.ordering # Ordered indices Array([0, 1, 2, 3], dtype=int32) >>> result.n_visited # Number of observations included Array(4, dtype=int32) >>> result.n_skipped # Number of observations skipped Array(0, dtype=int32) >>> result.all_visited # Were all observations included? Array(True, dtype=bool)
Get ordered data:
>>> ordered_pos, ordered_vel = result.ordered >>> ordered_pos["x"] Array([0., 1., 2., 3.], dtype=float32)
Interpolate positions along the ordering using
gamma:>>> # gamma=0 returns the first position, gamma=1 the last >>> result(jnp.array(0.0)) {'x': Array(0., dtype=float32), 'y': Array(0., dtype=float32)} >>> result(jnp.array(0.5)) {'x': Array(1.5, dtype=float32), 'y': Array(0.75, dtype=float32)} >>> result(jnp.array(1.0)) {'x': Array(3., dtype=float32), 'y': Array(1.5, dtype=float32)}
With a
backbone(e.g., fromMSTOrderer),__call__interpolates along the smooth polyline instead:>>> backbone = {"x": jnp.array([0.0, 1.5, 3.0]), "y": jnp.array([0.0, 0.75, 1.5])} >>> result_with_backbone = pcf.orderers.OrderingResult( ... positions=positions, ... velocities=velocities, ... indices=indices, ... gamma_range=(0.0, 1.0), ... backbone=backbone, ... ) >>> result_with_backbone(jnp.array(0.5)) {'x': Array(1.5, dtype=float32), 'y': Array(0.75, dtype=float32)}
Interpolation works under
jit,vmapandgrad:>>> import jax >>> jax.jit(lambda g: result(g))(0.25)["x"] Array(0.75, dtype=float32) >>> jax.vmap(result)(jnp.linspace(0, 1, 5))["x"].shape (5,) >>> jax.grad(lambda g: result(g)["x"])(0.5) Array(3., dtype=float32, weak_type=True)
- Parameters:
positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])indices (
Int[Array, 'N'])velocity_aware (
bool)backbone (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]] |None)backbone_size (
Int[Array, '']|None)chord (
Float[Array, 'N']|None)weights (
Float[Array, 'N']|None)
-
indices:
Int[Array, 'N']#
-
backbone:
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]] |None= None#
- property visited: Bool[Array, 'N']#
Boolean array indicating which observations were visited.
- property n_visited: Int[Array, '']#
Number of observations that were visited (not skipped).
- property n_skipped: Int[Array, '']#
Number of observations that were not visited (skipped).
- property all_visited: Bool[Array, '']#
Whether all observations were visited (no skips).
- property skipped_indices: Int[Array, 'n_skipped']#
Indices of skipped observations (marked as -1 in indices).
- property ordering: Int[Array, 'n_visited']#
Indices of visited observations in the order they were visited.
- property ordered: tuple[Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']]]#
Positions and velocities ordered by the walk (visited only).
- __call__(gamma: Array, /, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None = None)#
Interpolate spatial positions from ordering parameter $gamma$.
Uses linear interpolation between consecutive control points. The control points are the
backbonepolyline vertices when a backbone is present, otherwise the ordered visited observations.gammamust lie withingamma_range; values outside it raiseValueError(underjit, a JAX runtime error at run time). It is normalized to[0, 1]before interpolation.
- velocity_aware: bool = False#
Walk Configuration#
- class phasecurvefit.WalkConfig(metric: ~phasecurvefit._src.metrics.AbstractDistanceMetric = <factory>, strategy: ~phasecurvefit._src.strategies.AbstractQueryStrategy = <factory>)#
Bases:
ReprMixin,ModuleConfiguration for neighbor queries in the local-flow walk.
Composes a distance metric with a query strategy. This is the primary way to configure how the algorithm selects the next point.
- Parameters:
metric (AbstractDistanceMetric) – Distance metric for computing modified distances between points. Default:
AlignedMomentumDistanceMetric().strategy (AbstractQueryStrategy) – Strategy for finding candidate neighbors. Default:
BruteForce().
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf
Default configuration (brute-force with aligned-momentum metric):
>>> config = pcf.WalkConfig() >>> 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])} >>> result = pcf.order(pos, vel, pcf.orderers.LocalFlowOrderer(config=config))
KD-tree strategy with aligned momentum metric:
>>> from phasecurvefit.metrics import AlignedMomentumDistanceMetric >>> config = pcf.WalkConfig( ... metric=AlignedMomentumDistanceMetric(), ... strategy=pcf.strats.KDTree(k=50), ... )
-
metric:
AbstractDistanceMetric#
-
strategy:
AbstractQueryStrategy#
- class phasecurvefit.StateMetadata(**kwargs: object)#
Bases:
ReprMixin,ValueMetadata container for the local-flow walk’s state.
This holds optional context like unit systems that need to be passed through the algorithm state without participating in computation.
StateMetadata is registered as a JAX PyTree LEAF (not a node), which means JAX treats it as an atomic, non-flattened object. This prevents JAX from: - Attempting to flatten the metadata dict - Trying to convert the unit system object to an array - Losing the metadata during tree operations like scan
Examples
>>> metadata = StateMetadata(usys="SI") >>> metadata["usys"] 'SI' >>> "usys" in metadata True
- Parameters:
kwargs (
object)
- keys()#
Return the metadata keys.
Required for
dict(metadata)and**metadatato work. Without it neither raises a missing-method error:dictfalls back to the iterable-of-pairs protocol, iterates the keys, and tries to unpack each one as a 2-element pair. A key of any length but two raises an opaque “dictionary update sequence element #0 has length 4”, and a two-character key silently unpacks into its own characters –StateMetadata(ab=1)became{"a": "b"}.
- aval()#
Return a placeholder abstract value so JAX tracing is satisfied.
- Return type:
ShapedArray
Result Accessor#
Helper function to extract ordered data from results.
- phasecurvefit.order_w(res: WalkLocalFlowResult, /)#
Get xs and vs in the ordered sequence from a WalkLocalFlowResult.
Filters out unvisited indices (marked as -1) and returns only the visited observations in the order they were traversed.
- Parameters:
res (
WalkLocalFlowResult) – The result from the local-flow walk.- Return type:
- Returns:
xs (dict[str, Array]) – Position arrays reordered according to the algorithm’s output, with unvisited observations removed.
vs (dict[str, Array]) – Velocity arrays reordered according to the algorithm’s output, with unvisited observations removed.
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> pos = {"x": jnp.array([3.0, 1.0, 2.0])} >>> vel = {"x": jnp.array([1.0, 1.0, 1.0])} >>> lfo = pcf.orderers.LocalFlowOrderer(start_idx=1, metric_scale=0.0) >>> result = pcf.order(pos, vel, lfo) >>> ordered_pos, ordered_vel = pcf.order_w(result)
Distance Metrics#
Pluggable distance metrics for controlling how the algorithm selects the next point. See the Metrics Guide for usage examples.
- class phasecurvefit.metrics.AbstractDistanceMetric#
Bases:
ReprMixin,ModuleAbstract base class for distance metrics in phase-space walks.
A distance metric computes modified distances between a current point and all candidate next points, incorporating both spatial and velocity information. Different metrics can implement different weighting schemes or use different phase-space representations.
Subclasses declare
uses_velocity: whether the metric reads velocity at all. It is a property of the metric type, not of any scale parameter – a scale of zero makes a phase-space metric numerically position-only, but the metric still is one. An orderer reports that as its result’svelocity_aware, so a later stage knows whether velocity informed the ordering it is refining.Examples
>>> import phasecurvefit as pcf >>> metric = pcf.metrics.AlignedMomentumDistanceMetric() >>> # Use with the local-flow walk via the metric parameter
-
uses_velocity:
ClassVar[bool] = True# the signature takes velocities, so a metric that ignores them is the special case and should say so. Defaulting the other way would silently drop a custom velocity-aware metric back to position-only in a chain.
- Type:
Whether this metric reads velocity at all. Defaults to
True
-
uses_velocity:
- final class phasecurvefit.metrics.AlignedMomentumDistanceMetric#
Bases:
AbstractDistanceMetricDefault momentum-based distance metric.
Computes modified distance as:
$$ d = d_0 + lambda (1 - costheta) $$
where $d_0$ is the Euclidean distance in position space, $theta$ is the angle between the current velocity and the direction to the candidate point, and $lambda$ controls the relative importance of momentum alignment.
When $lambda = 0$, reduces to pure nearest-neighbor search in position space. As $lambda$ increases, points aligned with the current velocity direction are increasingly favored.
This is the original phase-flow walk metric from Nibauer et al. (2022).
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> metric = pcf.metrics.AlignedMomentumDistanceMetric() >>> 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])} >>> current_pos = {k: v[0] for k, v in pos.items()} >>> current_vel = {k: v[0] for k, v in vel.items()} >>> distances = metric(current_pos, current_vel, pos, vel, metric_scale=1.0) >>> distances.shape (3,)
-
uses_velocity:
ClassVar[bool] = True# the signature takes velocities, so a metric that ignores them is the special case and should say so. Defaulting the other way would silently drop a custom velocity-aware metric back to position-only in a chain.
- Type:
Whether this metric reads velocity at all. Defaults to
True
-
uses_velocity:
- final class phasecurvefit.metrics.SpatialDistanceMetric#
Bases:
AbstractDistanceMetricPosition-only distance metric.
Computes pure Euclidean distance in position space, ignoring velocity information entirely. This reduces to standard nearest-neighbor search.
$$ d = d_0 $$
where $d_0$ is the Euclidean distance between positions. The metric_scale parameter is ignored.
This metric is useful when: - Velocity information is unreliable or unavailable - Pure spatial proximity is the desired ordering criterion - Comparing against baseline nearest-neighbor approaches
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> metric = pcf.metrics.SpatialDistanceMetric() >>> 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])} >>> current_pos = {k: v[0] for k, v in pos.items()} >>> current_vel = {k: v[0] for k, v in vel.items()} >>> distances = metric(current_pos, current_vel, pos, vel, metric_scale=0.0) >>> distances.shape (3,)
-
uses_velocity:
ClassVar[bool] = False# the signature takes velocities, so a metric that ignores them is the special case and should say so. Defaulting the other way would silently drop a custom velocity-aware metric back to position-only in a chain.
- Type:
Whether this metric reads velocity at all. Defaults to
True
- is_symmetric: ClassVar[bool] = True#
a distance is normally symmetric, so asymmetry is the special case and should say so. Consumers that compare a point to a set – nearest-prototype in the SOM – are only meaningful under a symmetric metric.
- Type:
Whether
d(a, b) == d(b, a). Defaults toTrue
-
uses_velocity:
- final class phasecurvefit.metrics.FullPhaseSpaceDistanceMetric#
Bases:
AbstractDistanceMetricFull 6D phase-space distance metric.
Computes the Euclidean distance in the full 6-dimensional phase space by combining position and velocity differences. The parameter metric_scale (with time units) converts velocity differences to position units.
$$ d = sqrt{d_0^2 + (tau cdot d_v)^2} $$
where $d_0$ is the Euclidean distance in position space, $d_v$ is the Euclidean distance in velocity space, and $tau$ is the time parameter (metric_scale) that converts velocity to position units.
This metric treats position and velocity symmetrically in phase space, without directional bias from momentum alignment. The metric_scale parameter determines the relative weighting of velocity differences.
Physically, if we think of phase space as having position coordinates measured in kpc and velocity coordinates measured in kpc/Myr, then metric_scale with units of Myr converts velocity differences to kpc, allowing us to compute a true Euclidean distance in a uniformly scaled phase space.
This metric is useful when:
Position and velocity information are equally important
You want true 6D proximity without momentum direction bias
The natural time scale of the system is known
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> metric = pcf.metrics.FullPhaseSpaceDistanceMetric() >>> 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.5, 2.0]), "y": jnp.array([0.5, 1.0, 1.5])} >>> current_pos = {k: v[0] for k, v in pos.items()} >>> current_vel = {k: v[0] for k, v in vel.items()} >>> # metric_scale=1.0 means 1 unit of velocity diff = 1 unit of position diff >>> distances = metric(current_pos, current_vel, pos, vel, metric_scale=1.0) >>> distances.shape (3,)
-
uses_velocity:
ClassVar[bool] = True# the signature takes velocities, so a metric that ignores them is the special case and should say so. Defaulting the other way would silently drop a custom velocity-aware metric back to position-only in a chain.
- Type:
Whether this metric reads velocity at all. Defaults to
True
- is_symmetric: ClassVar[bool] = True#
a distance is normally symmetric, so asymmetry is the special case and should say so. Consumers that compare a point to a set – nearest-prototype in the SOM – are only meaningful under a symmetric metric.
- Type:
Whether
d(a, b) == d(b, a). Defaults toTrue
Query Strategies#
Neighbour-query strategies for the walk, set via WalkConfig(strategy=...).
- class phasecurvefit.strats.AbstractQueryStrategy#
Bases:
ReprMixin,ABCAbstract base class for neighbor query strategies.
Strategies are minimally stateful. Configure via __init__ (e.g., KD-tree k). The walk calls init(positions) once to build a strategy state, then query_at(state, idx, …) at each step. Subclasses must implement query, which answers for an arbitrary position; the default query_at looks up the data point at
idxand delegates to it. Override query_at only to use precomputed per-point state, as KDTree does.- abstractmethod init(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, metadata: object)#
Build and return strategy state from positions.
For brute-force, return an empty state (e.g., None).
- abstractmethod query(state: object, /, current_pos: Mapping[str, Real[Array, ''] | Real[ndarray, ''] | number | int | float | Real[TypedNdArray, '']], current_vel: Mapping[str, Real[Array, ''] | Real[ndarray, ''] | number | int | float | Real[TypedNdArray, '']], positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], metric_fn: AbstractDistanceMetric, metric_scale: Float[Array, ''] | Float[ndarray, ''] | number | float | Float[TypedNdArray, ''])#
Query for neighbors given current state.
- Parameters:
state (object) – Strategy state returned by init()
current_pos (dict) – Position of current point
current_vel (dict) – Velocity of current point
positions (dict) – All positions in dataset
velocities (dict) – All velocities in dataset
metric_fn (callable) – Distance metric function
metric_scale (float) – Metric-dependent scale parameter
- Returns:
Result containing distances and optionally candidate indices
- Return type:
- query_at(state: object, current_idx: Int[Array, ''], /, positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], metric_fn: AbstractDistanceMetric, metric_scale: Float[Array, ''] | Float[ndarray, ''] | number | float | Float[TypedNdArray, ''])#
Query for neighbors of the data point at
current_idx.The walk only ever queries at data points, so it calls this rather than query. The default looks the point up and delegates to query; a strategy can override it to use precomputed per-point state (as KDTree does with its neighbor table).
- Parameters:
state (
object)current_idx (
Int[Array, ''])positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])metric_fn (
AbstractDistanceMetric)metric_scale (
Union[Float[Array, ''],Float[ndarray, ''],number,float,Float[TypedNdArray, '']])
- Return type:
- class phasecurvefit.strats.BruteForce#
Bases:
AbstractQueryStrategyBrute-force strategy: compute distance to all points.
This is the default strategy. It computes distances to all unvisited points and selects the nearest one. Most efficient for small datasets or when most points are still unvisited.
- init(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, metadata: object)#
No persistent state for brute-force; return None.
- query(state: object, /, current_pos: Mapping[str, Real[Array, ''] | Real[ndarray, ''] | number | int | float | Real[TypedNdArray, '']], current_vel: Mapping[str, Real[Array, ''] | Real[ndarray, ''] | number | int | float | Real[TypedNdArray, '']], positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], metric_fn: AbstractDistanceMetric, metric_scale: Float[Array, ''] | Float[ndarray, ''] | number | float | Float[TypedNdArray, ''])#
Compute distances to all points using the metric.
- Parameters:
state (
object)current_pos (
Mapping[str,Union[Real[Array, ''],Real[ndarray, ''],number,int,float,Real[TypedNdArray, '']]])current_vel (
Mapping[str,Union[Real[Array, ''],Real[ndarray, ''],number,int,float,Real[TypedNdArray, '']]])positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])metric_fn (
AbstractDistanceMetric)metric_scale (
Union[Float[Array, ''],Float[ndarray, ''],number,float,Float[TypedNdArray, '']])
- Return type:
- query_at(state: object, current_idx: Int[Array, ''], /, positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], metric_fn: AbstractDistanceMetric, metric_scale: Float[Array, ''] | Float[ndarray, ''] | number | float | Float[TypedNdArray, ''])#
Query for neighbors of the data point at
current_idx.The walk only ever queries at data points, so it calls this rather than query. The default looks the point up and delegates to query; a strategy can override it to use precomputed per-point state (as KDTree does with its neighbor table).
- Parameters:
state (
object)current_idx (
Int[Array, ''])positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])metric_fn (
AbstractDistanceMetric)metric_scale (
Union[Float[Array, ''],Float[ndarray, ''],number,float,Float[TypedNdArray, '']])
- Return type:
- class phasecurvefit.strats.KDTree(k: int = 50)#
Bases:
AbstractQueryStrategyKD-tree strategy: restrict each step to the k nearest spatial neighbors.
init builds a KD-tree and queries the
knearest spatial neighbors of every point once, giving an(n, k + 1)neighbor table. Each walk step then looks up the current point’s row and evaluates the metric on those candidates only, so a step’s own work is O(k) rather than O(n). Building the table is one batched KD-tree query over all points; on CPU that one-off cost dominates for small datasets, so this is faster than BruteForce only from a few thousand points up (withk=50).Because only spatial neighbors are candidates, the walk can pick a different point than BruteForce would: one that is nearer under the metric but not among the
knearest in space is never considered.Requires jaxkd optional dependency.
- Parameters:
k (
int)
- init(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, metadata: object)#
Build the KD-tree and every point’s neighbor table.
- query(kd_state: dict[str, Any], /, current_pos: Mapping[str, Real[Array, ''] | Real[ndarray, ''] | number | int | float | Real[TypedNdArray, '']], current_vel: Mapping[str, Real[Array, ''] | Real[ndarray, ''] | number | int | float | Real[TypedNdArray, '']], positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], metric_fn: AbstractDistanceMetric, metric_scale: Float[Array, ''] | Float[ndarray, ''] | number | float | Float[TypedNdArray, ''])#
Query the KD-tree at an arbitrary position; metric on candidates only.
- Parameters:
current_pos (
Mapping[str,Union[Real[Array, ''],Real[ndarray, ''],number,int,float,Real[TypedNdArray, '']]])current_vel (
Mapping[str,Union[Real[Array, ''],Real[ndarray, ''],number,int,float,Real[TypedNdArray, '']]])positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])metric_fn (
AbstractDistanceMetric)metric_scale (
Union[Float[Array, ''],Float[ndarray, ''],number,float,Float[TypedNdArray, '']])
- Return type:
- query_at(kd_state: dict[str, Any], current_idx: Int[Array, ''], /, positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], metric_fn: AbstractDistanceMetric, metric_scale: Float[Array, ''] | Float[ndarray, ''] | number | float | Float[TypedNdArray, ''])#
Look up the data point’s precomputed neighbors; O(k) per step.
- Parameters:
current_idx (
Int[Array, ''])positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])metric_fn (
AbstractDistanceMetric)metric_scale (
Union[Float[Array, ''],Float[ndarray, ''],number,float,Float[TypedNdArray, '']])
- Return type:
- class phasecurvefit.strats.QueryResult(distances, indices=None)#
Bases:
NamedTupleResult of a neighbor query.
- Variables:
distances (Array) – Metric distances. If
indicesis None, to every point (shape(n,)); otherwise to each candidate, aligned withindices(distances[i]is the distance to pointindices[i]).indices (Array or None) – Candidate indices, or None if every point is a candidate. For KDTree these are the
k + 1nearest spatial points, which include the current point itself; the walk excludes it as already visited.
- Parameters:
- count(value, /)#
Return number of occurrences of value.
- index(value, start=0, stop=9223372036854775807, /)#
Return first index of value.
Raises ValueError if the value is not present.
Phase-Space Utilities#
Low-level functions for phase-space operations. Available in the phasecurvefit.w submodule.
- phasecurvefit.w.euclidean_distance(q_a, q_b, /)#
Compute Euclidean distance between two position points in Cartesian space.
This function operates on scalar components only (single points). Use jax.vmap to compute distances for arrays of points.
- Parameters:
q_a (ScalarComponents) – Position dictionaries with scalar Cartesian components (keys: “x”, “y”, “z”).
q_b (ScalarComponents) – Position dictionaries with scalar Cartesian components (keys: “x”, “y”, “z”).
- Returns:
The Euclidean distance.
- Return type:
FLikeSz0
Examples
>>> import jax.numpy as jnp >>> q_a = {"x": jnp.array(0.0), "y": jnp.array(0.0)} >>> q_b = {"x": jnp.array(3.0), "y": jnp.array(4.0)} >>> float(euclidean_distance(q_a, q_b)) 5.0
- phasecurvefit.w.euclidean_distance(q_a: Mapping[str, jaxtyping.Real[AbstractQuantity, '']], q_b: Mapping[str, jaxtyping.Real[AbstractQuantity, '']], /) jaxtyping.Real[AbstractQuantity, '']
Compute the distance between Quantity-valued positions, in their unit.
Examples
>>> import jax.numpy as jnp >>> import unxt as u >>> q_a = {"x": u.Q(0.0, "m"), "y": u.Q(0.0, "m")} >>> q_b = {"x": u.Q(3.0, "m"), "y": u.Q(4.0, "m")} >>> euclidean_distance(q_a, q_b) Quantity(Array(5., dtype=float32, weak_type=True), unit='m')
- phasecurvefit.w.unit_direction(q_a, q_b, /)#
Compute unit direction vector from position a to b in Cartesian space.
This function operates on scalar components only (single points). Use jax.vmap to compute directions for arrays of points.
- Parameters:
q_a (ScalarComponents) – Position dictionaries with scalar Cartesian components (keys: “x”, “y”, “z”).
q_b (ScalarComponents) – Position dictionaries with scalar Cartesian components (keys: “x”, “y”, “z”).
- Returns:
Dictionary of unit direction Cartesian components.
- Return type:
ScalarComponents
Examples
>>> import jax.numpy as jnp >>> q_a = {"x": jnp.array(0.0), "y": jnp.array(0.0)} >>> q_b = {"x": jnp.array(3.0), "y": jnp.array(4.0)} >>> udir = unit_direction(q_a, q_b) >>> float(udir["x"]), float(udir["y"]) (0.6..., 0.8...)
- phasecurvefit.w.unit_direction(q_a: Mapping[str, jaxtyping.Real[AbstractQuantity, '']], q_b: Mapping[str, jaxtyping.Real[AbstractQuantity, '']], /) Mapping[str, jaxtyping.Real[AbstractQuantity, '']]
Compute the unit direction from
q_atoq_b(dimensionless).Examples
>>> import jax.numpy as jnp >>> import unxt as u >>> q_a = {"x": u.Q(0.0, "m"), "y": u.Q(0.0, "m")} >>> q_b = {"x": u.Q(3.0, "m"), "y": u.Q(4.0, "m")} >>> unit_direction(q_a, q_b) {'x': Quantity(Array(0.6, dtype=float32, weak_type=True), unit=''), 'y': Quantity(Array(0.8, dtype=float32, weak_type=True), unit='')}
- phasecurvefit.w.unit_velocity(velocity, /)#
Compute the unit velocity vector in Cartesian space.
This function operates on scalar components only (single velocity vector). Use jax.vmap to compute unit velocities for arrays of velocities.
- Parameters:
velocity (ScalarComponents) – Velocity dictionary with scalar Cartesian components (keys: “x”, “y”, “z”).
- Returns:
Dictionary of unit velocity Cartesian components.
- Return type:
ScalarComponents
Examples
>>> import jax.numpy as jnp >>> vel = {"x": jnp.array(3.0), "y": jnp.array(4.0)} >>> uvel = unit_velocity(vel) >>> float(uvel["x"]), float(uvel["y"]) (0.6..., 0.8...)
- phasecurvefit.w.unit_velocity(velocity: Mapping[str, jaxtyping.Real[AbstractQuantity, '']], /) Mapping[str, jaxtyping.Real[AbstractQuantity, '']]
Compute the unit velocity vector (dimensionless).
Examples
>>> import jax.numpy as jnp >>> import unxt as u >>> vel = {"x": u.Q(3.0, "m/s"), "y": u.Q(4.0, "m/s")} >>> unit_velocity(vel) {'x': Quantity(Array(0.6, dtype=float32, ...), unit=''), 'y': Quantity(Array(0.8, dtype=float32, ...), unit='')}
- phasecurvefit.w.velocity_norm(velocity, /)#
Compute the norm of a velocity vector in Cartesian space.
This function operates on scalar components only (single velocity vector). Use jax.vmap to compute norms for arrays of velocities.
- Parameters:
velocity (ScalarComponents) – Velocity dictionary with scalar Cartesian components (keys: “x”, “y”, “z”).
- Returns:
The Euclidean norm of the velocity.
- Return type:
FLikeSz0
Examples
>>> import jax.numpy as jnp >>> vel = {"x": jnp.array(3.0), "y": jnp.array(4.0)} >>> float(velocity_norm(vel)) 5.0
- phasecurvefit.w.velocity_norm(velocity: Mapping[str, jaxtyping.Real[AbstractQuantity, '']], /) jaxtyping.Real[AbstractQuantity, '']
Compute the norm of a Quantity-valued velocity, in its unit.
Examples
>>> import jax.numpy as jnp >>> import unxt as u >>> vel = {"x": u.Q(3.0, "m/s"), "y": u.Q(4.0, "m/s")} >>> result = velocity_norm(vel) >>> result.to("m/s").value Array(5., dtype=float32, weak_type=True)
- phasecurvefit.w.cosine_similarity(vec_a, vec_b, /)#
Compute cosine similarity between two vectors in Cartesian space.
The cosine similarity is defined as the dot product of the vectors. For unit vectors, this equals the cosine of the angle between them.
This function operates on scalar components only (single vectors). Use jax.vmap to compute similarities for arrays of vectors.
- Parameters:
vec_a (ScalarComponents) – Vector dictionaries with scalar Cartesian components (keys: “x”, “y”, “z”).
vec_b (ScalarComponents) – Vector dictionaries with scalar Cartesian components (keys: “x”, “y”, “z”).
- Returns:
The cosine similarity (dot product).
- Return type:
FLikeSz0
Examples
>>> import jax.numpy as jnp >>> # Parallel vectors >>> a = {"x": jnp.array(1.0), "y": jnp.array(0.0)} >>> b = {"x": jnp.array(1.0), "y": jnp.array(0.0)} >>> float(cosine_similarity(a, b)) 1.0
>>> # Orthogonal vectors >>> a = {"x": jnp.array(1.0), "y": jnp.array(0.0)} >>> b = {"x": jnp.array(0.0), "y": jnp.array(1.0)} >>> float(cosine_similarity(a, b)) 0.0
- phasecurvefit.w.cosine_similarity(vel_a: Mapping[str, jaxtyping.Real[AbstractQuantity, '']], vel_b: Mapping[str, jaxtyping.Real[AbstractQuantity, '']], /) jaxtyping.Real[AbstractQuantity, '']
Compute the cosine similarity of two Quantity-valued vectors.
Examples
>>> import jax.numpy as jnp >>> import unxt as u >>> vel_a = {"x": u.Q(1.0, "m/s"), "y": u.Q(0.0, "m/s")} >>> vel_b = {"x": u.Q(0.0, "m/s"), "y": u.Q(1.0, "m/s")} >>> cosine_similarity(vel_a, vel_b) Quantity(Array(0., dtype=float32, ...), unit='')
- phasecurvefit.w.get_w_at(q: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], p: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], idx: int | Int[Array, ''] | Int[Array, 'N'], /)#
Extract a phase-space point at the given index.
This function uses standard phase-space notation where: - q = position (generalized Cartesian coordinates: “x”, “y”, “z”) - p = momentum/velocity (generalized Cartesian momenta: “x”, “y”, “z”) - w = (q, p) = full phase-space point
This extracts a single point (scalar components) from arrays. For extracting multiple points, use jax.vmap or array indexing directly.
- Parameters:
q (VectorComponents) – Position dictionary with 1D array Cartesian values of shape (N,).
p (VectorComponents) – Velocity/momentum dictionary with 1D array Cartesian values of shape (N,).
idx (int | Array) – Index or indices to extract. Can be: - int: Extract a single point (returns scalar arrays) - 0-d Array: Extract a single point (returns scalar arrays) - 1-d Array: Extract multiple points (returns 1D arrays)
- Returns:
The (position, velocity) tuple at the given index/indices.
- Return type:
Examples
>>> import jax.numpy as jnp >>> pos = {"x": jnp.array([1.0, 2.0, 3.0]), "y": jnp.array([4.0, 5.0, 6.0])} >>> vel = {"x": jnp.array([0.1, 0.2, 0.3]), "y": jnp.array([0.4, 0.5, 0.6])}
Extract a single point:
>>> q, p = get_w_at(pos, vel, 1) >>> float(q["x"]), float(p["y"]) (2.0, 0.5)
Extract multiple points:
>>> q, p = get_w_at(pos, vel, jnp.array([0, 2])) >>> list(q["x"]) [Array(1., dtype=float32), Array(3., dtype=float32)]
Types#
- class phasecurvefit.WalkLocalFlowResult(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], indices: Int[Array, 'N'], *, gamma_range: tuple[float, float] = (0.0, 1.0), velocity_aware: bool = False, backbone: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']] | None = None, backbone_size: Int[Array, ''] | None = None, chord: Float[Array, 'N'] | None = None, weights: Float[Array, 'N'] | None = None)#
Bases:
OrderingResultResult of the local-flow walk (LocalFlowOrderer).
An OrderingResult with no extra fields; see it for the attributes, the layout of
indices, the accessors and interpolation. The subclass exists as a type marker, so code can tell a walk’s result from other orderers’:combine_results dispatches on it: only two walk results (a forward and a backward walk, as
direction="both"produces) can be merged.isinstance(result, WalkLocalFlowResult)distinguishes a walk from, e.g., the default MST | SOM pipeline, which returns a plain OrderingResult.
What is specific to the walk:
It follows the local flow of the velocity field from a start tracer, one step at a time, and can stop before visiting every tracer (e.g. when no unvisited tracer is within
max_dist). Skipped tracers leave-1slots at the end ofindices; see skipped_indices and n_skipped.It has no
backbone, soresult(gamma)interpolates linearly between the visited tracers in walk order, overgamma_range == (0.0, 1.0).
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> t = jnp.linspace(0, 2 * jnp.pi, 20) >>> pos = {"x": jnp.linspace(0, 10, 20), "y": jnp.sin(t)} >>> vel = {"x": jnp.ones(20), "y": jnp.cos(t)}
>>> walk = pcf.order(pos, vel, pcf.orderers.LocalFlowOrderer()) >>> isinstance(walk, pcf.WalkLocalFlowResult) True >>> walk.gamma_range (0.0, 1.0) >>> walk.n_visited, walk.n_skipped (Array(20, dtype=int32), Array(0, dtype=int32)) >>> walk(0.5)["x"] Array(5., dtype=float32)
The default pipeline is not a walk:
>>> isinstance(pcf.order(pos, vel), pcf.WalkLocalFlowResult) False
- Parameters:
positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])indices (
Int[Array, 'N'])velocity_aware (
bool)backbone (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]] |None)backbone_size (
Int[Array, '']|None)chord (
Float[Array, 'N']|None)weights (
Float[Array, 'N']|None)
- property all_visited: Bool[Array, '']#
Whether all observations were visited (no skips).
- backbone: VectorComponents | None = None#
- backbone_size: ISz0 | None = None#
- chord: FSzN | None = None#
- gamma_range: tuple[float, float] = (0.0, 1.0)#
- property n_skipped: Int[Array, '']#
Number of observations that were not visited (skipped).
- property n_visited: Int[Array, '']#
Number of observations that were visited (not skipped).
- property ordered: tuple[Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']]]#
Positions and velocities ordered by the walk (visited only).
- property ordering: Int[Array, 'n_visited']#
Indices of visited observations in the order they were visited.
- property skipped_indices: Int[Array, 'n_skipped']#
Indices of skipped observations (marked as -1 in indices).
- velocity_aware: bool = False#
- property visited: Bool[Array, 'N']#
Boolean array indicating which observations were visited.
- weights: FSzN | None = None#
- positions: VectorComponents#
- velocities: VectorComponents#
- indices: ISzN#
- phasecurvefit.ScalarComponents : TypeAlias = dict[str, RLikeSz0]#
Type alias for dictionaries mapping component names to scalar JAX arrays.
Used for single phase-space points. Keys are coordinate/component names (e.g., “x”, “y”, “z”), values are 0-dimensional JAX arrays.
Example:
import jax.numpy as jnp position = { "x": jnp.array(1.0), "y": jnp.array(2.0), }
- phasecurvefit.VectorComponents : TypeAlias = dict[str, RLikeSzN]#
Type alias for dictionaries mapping component names to 1D JAX arrays.
Used for arrays of phase-space points. Keys are coordinate/component names (e.g., “x”, “y”, “z”), values are 1-dimensional JAX arrays of shape (N,).
Example:
import jax.numpy as jnp position = { "x": jnp.array([0.0, 1.0, 2.0]), "y": jnp.array([0.0, 1.0, 2.0]), }
Autoencoder Module#
Neural network for interpolating skipped tracers. See Autoencoder Guide for details.
Classes#
- class phasecurvefit.nn.PathAutoencoder(encoder: OrderingNet, decoder: AbstractTrackNet, normalizer: AbstractNormalizer, width: WidthNet | None = None)#
Bases:
AbstractAutoencoderAutoencoder combining OrderingNet and TrackNet.
This autoencoder is trained to assign $gamma$ values to stream tracers that were skipped by the phase-flow walk algorithm. It consists of two parts:
Interpolation Network: Maps phase-space coordinates $(x, v) to (gamma, p)$ where $gamma in [0, 1]$ is the ordering parameter and $p in [0, 1]$ is the membership probability.
Param-Net (Decoder): Maps $gamma to x$, reconstructing the position from the ordering parameter.
- Parameters:
encoder (
OrderingNet)decoder (
AbstractTrackNet)normalizer (
AbstractNormalizer)
-
encoder:
OrderingNet#
-
decoder:
AbstractTrackNet#
-
normalizer:
AbstractNormalizer#
-
width:
WidthNet|None= None# Foreground half-width $sigma(gamma)$ (e.g. a stream’s), or None.
Present only when the autoencoder was trained with mixture-model membership (see MixtureMembershipConfig). It is kept on the model because it is needed at inference to turn the encoder’s prior membership $pi$ into a calibrated posterior; see posterior_membership.
- classmethod make(normalizer: AbstractNormalizer, *, gamma_range: tuple[float, float], ordering_width_size: int = 100, ordering_depth: int = 2, track_width_size: int = 128, track_depth: int = 3, decoder: AbstractTrackNet | None = None, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'])#
- Parameters:
normalizer (
AbstractNormalizer)ordering_width_size (
int)ordering_depth (
int)track_width_size (
int)track_depth (
int)decoder (
AbstractTrackNet|None)key (
Union[Key[Array, ''],UInt32[Array, '2'],UInt32[Array, '4']])
- Return type:
- decode(gamma: Float[Array, 'N'], /, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None = None)#
Decode $gamma$ to reconstructed position.
- Parameters:
gamma (Array) – Ordering parameter, typically in the range defined by gamma_range, shape (N,). Some decoders may support extrapolation beyond this range.
key (PRNGKeyArray, optional) – JAX random key for stochastic decoding (if applicable).
- Returns:
position – Reconstructed dict of positions.
- Return type:
VectorComponents
- encode(qs: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], ps: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None = None)#
Encode phase-space coordinates to ($gamma$, $p$).
- Parameters:
qs (VectorComponents) – Spatial / velocity coordinates of shape (N, n_dims).
ps (VectorComponents) – Spatial / velocity coordinates of shape (N, n_dims).
key (PRNGKeyArray, optional) – JAX random key for stochastic encoding (if applicable).
- Return type:
tuple[Float[Array, 'N'],Float[Array, 'N']]- Returns:
gamma (Array) – Ordering parameter in [0, 1], shape (N,).
prob (Array) – Membership probability in [0, 1], shape (N,).
- class phasecurvefit.nn.OrderingNet(in_size: int = 6, width_size: int = 100, depth: int = 2, *, gamma_range: tuple[float, float] = (0.0, 1.0), key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'])#
Bases:
ReprMixin,ModuleInterpolation network:$(x, v) ;mapsto; (gamma, p),$.
This network takes N-D phase-space coordinates and outputs:
$gamma in [0, 1]$: The ordering parameter along the stream
$p in [0, 1]$: The membership probability (1 = likely stream member)
The architecture follows Appendix B.3 of Nibauer et al. (2022).
Uses scan-over-layers for improved compilation speed. See: https://docs.kidger.site/equinox/tricks/#improve-compilation-speed-with-scan-over-layers
- Parameters:
in_size (int) – Number of spatial + kinematic dimensions (6 for 3D: x, y, z, vx, vy, vz).
width_size (int) – The size of each hidden layer.
depth (int, optional) –
The number of hidden layers, not include the input layer or output heads. For example, depth=2 results in an network with layers:
[Linear(in_size, width_size), Linear(width_size, width_size), Linear(width_size, out_size), (output_heads)]key (PRNGKeyArray) – JAX random key for initialization.
- class phasecurvefit.nn.TrackNet(out_size: int = 3, width_size: int = 100, depth: int = 3, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'])#
Bases:
AbstractTrackNetParam-Net (decoder): maps $gamma to$ position (x, y, z).
This network reconstructs the stream track position from the ordering parameter $gamma$. It serves as the second half of the autoencoder.
The architecture follows Appendix B.1 of Nibauer et al. (2022).
Uses scan-over-layers for improved compilation speed. See: https://docs.kidger.site/equinox/tricks/#improve-compilation-speed-with-scan-over-layers
- Parameters:
key (PRNGKeyArray) – JAX random key for initialization.
out_size (int) – Number of spatial dimensions (2 for 2D, 3 for 3D) for the track speed.
hidden_size (int, optional) – Size of hidden layers. Default: 100.
n_hidden (int, optional) – Number of hidden layers. Default: 3.
width_size (
int)depth (
int)
- class phasecurvefit.nn.TrainingConfig(*, optimizer: ~optax._src.base.GradientTransformation = (<function chain.<locals>.init_fn>, <function chain.<locals>.update_fn>), batch_size: int = 100, show_pbar: bool = True, member_threshold: float = 0.5, n_epochs_encoder: int = 800, lambda_prob: float = 1.0, n_epochs_decoder: int = 100, n_epochs_both: int = 200, lambda_q: float = 1.0, lambda_p: tuple[float, float] = (1.0, 5.0), weight_by_density: bool | ~collections.abc.Mapping[str, object] = False, freeze_encoder_final_training: bool | None = None, membership: ~phasecurvefit._src.nn.membership.MixtureMembershipConfig | None = None, track_ends: ~typing.Literal['half_max', 'mask'] = 'half_max')#
Bases:
objectConfiguration for three-phase autoencoder training.
- Parameters:
-
optimizer:
GradientTransformation= (<function chain.<locals>.init_fn>, <function chain.<locals>.update_fn>)# Optax optimizer for training.
-
lambda_p:
tuple[float,float] = (1.0, 5.0)# Weight range
(start, stop)for Phase 3 (joint) velocity alignment.
-
weight_by_density:
bool|Mapping[str,object] = False# Whether to inverse density weight the samples. USE WITH CARE.
-
freeze_encoder_final_training:
bool|None= None# Whether to freeze the encoder during phase 3 training.
None(the default) freezes it whenmembershipis set and trains it otherwise; see EncoderDecoderTrainingConfig.freeze_encoder.
-
membership:
MixtureMembershipConfig|None= None# Opt in to mixture-model membership (outlier rejection).
None(the default) preserves the existing behaviour exactly. Supply a MixtureMembershipConfig to model the field as a stream + background mixture (Hogg, Bovy & Lang 2010, §3) so that membership is a calibrated posterior driven by the distance from the fitted track.Applies to phase 3 (joint encoder+decoder training), which is where the decoder – and therefore the residual – exists.
-
track_ends:
Literal['half_max','mask'] = 'half_max'# How the trained result’s
track_rangefinds the ends of the curve."half_max"(default) cuts where the weighted number of samples per unit length falls to half its value just inside, which is the true end of a curve blurred by any symmetric kernel."mask"reads each end from the cap of a mask made by thickening a curve: the farthest any sample reaches along the track, minus the mask’s half-width there. Use it for segmentation maps and other images with a definite edge, not for point clouds.
- encoderonly_config()#
Construct the OrderingNet config.
- Return type:
- decoderonly_config()#
Construct the TrackNet config.
- Return type:
TrackTrainingConfig
- autoencoder_config()#
Construct the Autoencoder config.
- Return type:
EncoderDecoderTrainingConfig
- class phasecurvefit.nn.AbstractTrackNet#
Bases:
ReprMixin,ModuleInterface for a trainable decoder mapping $gamma to$ position.
A track net is the second half of the autoencoder: it reconstructs the spatial track position from the scalar ordering parameter $gamma$.
Subclasses must:
expose
out_size(the number of spatial dimensions), andimplement
__call__(gamma, /, key=None) -> positionof shape(out_size,), differentiable ingamma(Phase-2 training takes ajvpof the decoder w.r.t. $gamma$ for the velocity/tangent loss).
Concrete variants (all interchangeable via
PathAutoencoder.make(decoder=...)):TrackNet— a plain MLP on $gamma$ (default).FourierTrackNet— Fourier features on $gamma$, for sharp / self-intersecting tracks a plain MLP over-smooths.
-
out_size:
AbstractVar[int]#
- class phasecurvefit.nn.FourierTrackNet(out_size: int = 3, n_frequencies: int = 8, width_size: int = 128, depth: int = 3, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'])#
Bases:
AbstractTrackNetDecoder with Fourier features on $gamma$ before the MLP.
Maps $gamma$ to
[gamma, sin(pi k gamma), cos(pi k gamma)]fork = 1 .. n_frequenciesand feeds those1 + 2*n_frequenciesfeatures to an MLP. The Fourier features give the network the high-frequency capacity to represent sharp or self-intersecting tracks (e.g. multi-petal curves) that a plainTrackNettends to over-smooth.sin/cos(pi k gamma)complete one period over a unit-width $gamma$-range, son_frequenciescontrols how sharp a curve the decoder can render.- Parameters:
out_size (int) – Number of spatial dimensions.
n_frequencies (int) – Number of Fourier modes
k. Higher captures sharper structure.width_size (int) – MLP hidden-layer size and number of hidden layers.
depth (int) – MLP hidden-layer size and number of hidden layers.
key (PRNGKeyArray) – JAX random key for initialization.
Examples
Create a Fourier decoder for 2D tracks:
>>> import jax.random as jr >>> import jax.numpy as jnp >>> import phasecurvefit as pcf
>>> # Create a decoder mapping gamma to 2D positions >>> decoder = pcf.nn.FourierTrackNet( ... out_size=2, n_frequencies=8, width_size=128, depth=3, key=jr.key(0) ... ) >>> decoder.out_size 2
Decode a single position from the ordering parameter:
>>> # Evaluate decoder at gamma=0.5 (middle of track) >>> gamma_val = jnp.array(0.5) >>> position = decoder(gamma_val) >>> position.shape (2,)
The Fourier embedding converts
gammato higher-dimensional features before the MLP, allowing sharp / multi-petal structure:>>> # Inspect the Fourier features >>> features = decoder.features(jnp.array(0.3)) >>> features.shape # (1 + 2 * 8,) (17,)
Compute the tangent vector (velocity) for the tangent/momentum loss:
>>> import jax >>> gamma = jnp.array(0.5) >>> position, tangent = jax.jvp(decoder, (gamma,), (jnp.array(1.0),)) >>> tangent.shape # Tangent vector in position space (2,)
Use with
PathAutoencoder.make()to build a complete autoencoder with Fourier decoding instead of the default plain MLP:>>> positions = {"x": jnp.linspace(0, 1, 20), "y": jnp.linspace(0, 1, 20)} >>> velocities = {"x": jnp.ones(20), "y": jnp.ones(20)} >>> normalizer = pcf.nn.StandardScalerNormalizer(positions, velocities)
>>> # Create decoder with specific parameters for sharp tracks >>> decoder_sharp = pcf.nn.FourierTrackNet( ... out_size=2, n_frequencies=16, width_size=256, depth=4, key=jr.key(1) ... ) >>> autoencoder = pcf.nn.PathAutoencoder.make( ... normalizer, gamma_range=(0.0, 1.0), decoder=decoder_sharp, key=jr.key(2) ... ) >>> isinstance(autoencoder.decoder, pcf.nn.FourierTrackNet) True
- features(gamma: Real[Array, ''], /)#
Fourier-feature embedding of the scalar ordering parameter.
- Parameters:
gamma (
Real[Array, ''])- Return type:
n_frequencies}']
- class phasecurvefit.nn.AbstractAutoencoder(encoder: Module, decoder: Module, normalizer: AbstractNormalizer)#
Bases:
ReprMixin,Module- Parameters:
encoder (
Module)decoder (
Module)normalizer (
AbstractNormalizer)
-
normalizer:
AbstractNormalizer#
- encode(qs: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], ps: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None = None)#
Encode phase-space coordinates to ($gamma$, $p$).
- Parameters:
qs (VectorComponents) – Spatial / velocity coordinates of shape (N, n_dims).
ps (VectorComponents) – Spatial / velocity coordinates of shape (N, n_dims).
key (PRNGKeyArray, optional) – JAX random key for stochastic encoding (if applicable).
- Return type:
tuple[Float[Array, 'N'],Float[Array, 'N']]- Returns:
gamma (Array) – Ordering parameter in [0, 1], shape (N,).
prob (Array) – Membership probability in [0, 1], shape (N,).
- decode(gamma: Float[Array, 'N'], /, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None = None)#
Decode $gamma$ to reconstructed position.
- Parameters:
gamma (Array) – Ordering parameter, typically in the range defined by gamma_range, shape (N,). Some decoders may support extrapolation beyond this range.
key (PRNGKeyArray, optional) – JAX random key for stochastic decoding (if applicable).
- Returns:
position – Reconstructed dict of positions.
- Return type:
VectorComponents
- class phasecurvefit.nn.AbstractExternalDecoder#
Bases:
ReprMixin,ModuleAbstract base class for external decoders.
- abstractmethod update(model: EncoderExternalDecoder, all_ws: Float[Array, 'N TwoF'], *, weights: Float[Array, 'N'] | None = None)#
Update decoder parameters.
This method should return a new instance of the decoder with updated parameters based on the provided keyword arguments.
- Parameters:
model (EncoderExternalDecoder) – The encoder-external decoder model instance.
all_ws (Float[Array, " N TwoF"]) – Normalized phase-space coordinates of the training tracers.
weights (Float[Array, " N"] | None) – Optional per-tracer weights, in the same order as
all_ws.
- Returns:
A new instance of the decoder with updated parameters.
- Return type:
- class phasecurvefit.nn.EncoderExternalDecoder(encoder: OrderingNet, decoder: AbstractExternalDecoder, normalizer: AbstractNormalizer)#
Bases:
AbstractAutoencoderAutoencoder with trained encoder and user-provided decoder function.
This class provides a flexible alternative to PathAutoencoder where the decoder is a user-provided function rather than a trained neural network. The most common use case is with a running-mean decoder that performs non-parametric interpolation in $gamma$-space.
The encoder (OrderingNet) is trained to predict $gamma$ and membership probability $p$ from phase-space coordinates. The decoder function maps $gamma$ values back to positions.
- Variables:
encoder (OrderingNet) – Neural network mapping $(x, v) to (gamma, p)$.
decoder (Callable[[Array], Array]) – Function mapping $gamma to x$. Should be vmappable and JIT-compatible.
normalizer (AbstractNormalizer) – Data normalizer for preprocessing phase-space coordinates.
- Parameters:
encoder (OrderingNet)
decoder (AbstractExternalDecoder)
normalizer (AbstractNormalizer)
See also
PathAutoencoderFull autoencoder with trainable decoder network.
RunningMeanDecoder.makeCreate a running-mean decoder.
Examples
>>> import jax.numpy as jnp >>> import jax.random as jr >>> import phasecurvefit as pcf >>> # Create sample data >>> key = jr.key(0) >>> positions = {"x": jnp.array([0.0, 1.0, 2.0]), "y": jnp.array([0.0, 0.0, 0.0])} >>> velocities = {"x": jnp.array([1.0, 1.0, 1.0]), "y": jnp.array([0.0, 0.0, 0.0])} >>> ordering = jnp.array([0, 1, 2]) >>> # Create normalizer and encoder >>> normalizer = pcf.nn.StandardScalerNormalizer(positions, velocities) >>> encoder = pcf.nn.OrderingNet(in_size=4, width_size=32, depth=2, key=jr.key(1)) >>> decoder = pcf.nn.RunningMeanDecoder(window_size=0.05) >>> # Create model >>> model = pcf.nn.EncoderExternalDecoder( ... encoder=encoder, decoder=decoder, normalizer=normalizer ... )
- Parameters:
encoder (
OrderingNet)decoder (
AbstractExternalDecoder)normalizer (
AbstractNormalizer)
-
encoder:
OrderingNet#
-
decoder:
AbstractExternalDecoder#
-
normalizer:
AbstractNormalizer#
- decode(gamma: Float[Array, 'N'], /, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None = None)#
Decode $gamma$ to reconstructed position.
- Parameters:
gamma (Array) – Ordering parameter, typically in the range defined by gamma_range, shape (N,). Some decoders may support extrapolation beyond this range.
key (PRNGKeyArray, optional) – JAX random key for stochastic decoding (if applicable).
- Returns:
position – Reconstructed dict of positions.
- Return type:
VectorComponents
- encode(qs: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], ps: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None = None)#
Encode phase-space coordinates to ($gamma$, $p$).
- Parameters:
qs (VectorComponents) – Spatial / velocity coordinates of shape (N, n_dims).
ps (VectorComponents) – Spatial / velocity coordinates of shape (N, n_dims).
key (PRNGKeyArray, optional) – JAX random key for stochastic encoding (if applicable).
- Return type:
tuple[Float[Array, 'N'],Float[Array, 'N']]- Returns:
gamma (Array) – Ordering parameter in [0, 1], shape (N,).
prob (Array) – Membership probability in [0, 1], shape (N,).
- class phasecurvefit.nn.RunningMeanDecoder(window_size: float, gamma_train: Float[Array, 'N'] | None = None, positions_train: Float[Array, 'N D'] | None = None, member_train: Bool[Array, 'N'] | None = None, weights_train: Float[Array, 'N'] | None = None, empty_window: Literal['nan', 'nearest'] = 'nan')#
Bases:
AbstractExternalDecoderRunning-mean decoder for non-parametric position reconstruction.
This decoder stores the training data and reconstructs positions from gamma values using a windowed running mean.
- Variables:
gamma_train (Array) – Precomputed gamma values for all training samples.
positions_train (Array) – Training positions (normalized).
window_size (float) – Window size in gamma-space.
empty_window ({"nan", "nearest"}) – What to return when no member star lies within
window_size / 2of the query gamma."nan"(default) returns NaN in every coordinate, so plots show a gap and downstream code can detect the missing value."nearest"returns the mean position of the member star(s) whose gamma is closest to the query. If there are no members at all, NaN is returned in either mode.weights_train (Array | None) – Per-sample weights in the running mean.
None(default) weighs every member equally.
- Parameters:
- classmethod make(encoder: OrderingNet, normalizer: AbstractNormalizer, positions: Mapping[str, Array] | Float[Array, 'N D'], velocities: Mapping[str, Array] | Float[Array, 'N D'], /, *, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None = None, window_size: float = 0.05, member_threshold: float = 0.5, empty_window: Literal['nan', 'nearest'] = 'nan', weights: Float[Array, 'N'] | None = None)#
Create a running-mean decoder for non-parametric position reconstruction.
This classmethod constructs a decoder that reconstructs positions from $gamma$ values using a windowed running mean in $gamma$-space. For each query $gamma$, the decoder:
Predicts $gamma$ values for all training samples using the encoder
Finds member samples whose $gamma$ is within [$gamma$ - window_size/2, $gamma$ + window_size/2]
Returns the mean position of those samples
If the window contains no member samples, the result is controlled by
empty_window: NaN (default) or the mean of the nearest member(s) in $gamma$.This provides a simple, non-parametric alternative to training a neural network decoder. It works well when the stream is smooth and well-sampled.
- Parameters:
encoder (OrderingNet) – Trained encoder network that predicts $gamma$ from phase-space.
normalizer (AbstractNormalizer) – Normalizer used to preprocess the phase-space data.
positions (Mapping[str, Array] or Array, shape (N, D)) – Training positions. If Mapping, will be transformed by normalizer. If Array, assumed to be already normalized.
velocities (Mapping[str, Array] or Array, shape (N, D)) – Training velocities. Same format as positions.
key (PRNGKeyArray, optional) – Random key for any stochastic operations (not used here, but included for consistency).
window_size (float, default=0.05) – Window size in $gamma$-space for computing running mean. Smaller values give more localized (less smooth) reconstruction.
member_threshold (float, default=0.5) – Membership probability threshold for including samples in the running mean.
empty_window ({"nan", "nearest"}, default="nan") – Behaviour when no member sample falls in the window.
"nan"returns NaN (so plots show gaps and downstream code can detect them);"nearest"returns the mean position of the member(s) closest in $gamma$.weights (Array, shape (N,), optional) – Per-sample weights, e.g. the density at each pixel of a density field. The running mean becomes a weighted mean.
None(default) weighs every member equally.
- Returns:
decoder – Decoder module mapping $gamma$ to positions. The returned decoder is JIT-compatible and vmappable.
- Return type:
Notes
The running mean is computed using a uniform (rectangular) kernel:
\[\hat{x}(\gamma) = \frac{\sum_i x_i \cdot \mathbb{1}_{|\gamma_i - \gamma| < w/2}} {\sum_i \mathbb{1}_{|\gamma_i - \gamma| < w/2}}\]where $w$ is the window size and the sums run over member samples. When the denominator is zero (an empty window), see
empty_window.The decoder stores the encoder and training data, so it can be used independently after creation.
Examples
>>> import jax >>> import jax.numpy as jnp >>> import jax.random as jr >>> import phasecurvefit as pcf
Create sample stream data
>>> key = jr.key(0) >>> N = 100 >>> t = jnp.linspace(0, 2 * jnp.pi, N) >>> positions = {"x": jnp.cos(t), "y": jnp.sin(t)} >>> velocities = {"x": -jnp.sin(t), "y": jnp.cos(t)}
Create and train encoder
>>> key, key1, key2 = jr.split(key, 3) >>> normalizer = pcf.nn.StandardScalerNormalizer(positions, velocities) >>> encoder = pcf.nn.OrderingNet( ... in_size=4, width_size=32, depth=2, gamma_range=(0.0, 1.0), key=key1 ... )
>>> # Prepare training data: concatenate normalized positions and velocities >>> qs_norm, ps_norm = normalizer.transform(positions, velocities) >>> all_ws = jnp.concatenate([qs_norm, ps_norm], axis=1) >>> # For this synthetic example, the ordering is just 0, 1, 2, ..., N-1 >>> ordering_indices = jnp.arange(N)
>>> # Train the encoder on the ordered stream data >>> config = pcf.nn.OrderingTrainingConfig(n_epochs=10, show_pbar=False) >>> trained_encoder, _, _ = pcf.nn.train_ordering_net( ... encoder, all_ws, ordering_indices, config, key=key2 ... )
>>> # Create decoder using trained encoder >>> decoder = pcf.nn.RunningMeanDecoder.make( ... trained_encoder, normalizer, positions, velocities, window_size=0.05 ... ) >>> # Reconstruct positions for gamma values within the training range. >>> # The decoder can only interpolate gamma values that are within the >>> # range of gamma predictions from the encoder on its training data. >>> gamma_test = jnp.array([0.4, 0.5, 0.6]) >>> reconstructed = jax.vmap(decoder)(gamma_test) >>> reconstructed.shape (3, 2)
- update(model: EncoderExternalDecoder, all_ws: Float[Array, 'N TwoF'], *, weights: Float[Array, 'N'] | None = None)#
Update decoder parameters.
This method returns a new instance of the decoder with updated parameters based on the provided keyword arguments.
- Parameters:
model (EncoderExternalDecoder) – The encoder-external decoder model instance.
all_ws (Float[Array, " N TwoF"]) – Normalized phase-space coordinates of the training tracers.
weights (Float[Array, " N"] | None) – Optional per-tracer weights for the running mean; see make.
- Returns:
new_decoder – New instance of RunningMeanDecoder with updated parameters.
- Return type:
- class phasecurvefit.nn.AutoencoderResult(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], indices: Int[Array, 'N'], gamma: Float[Array, 'N'], membership_prob: Float[Array, 'N'], model: AbstractAutoencoder, *, gamma_range: tuple[float, float] = (0.0, 1.0), velocity_aware: bool = False, track_range: tuple[float, float] | None = None)#
Bases:
AbstractResultResult of autoencoder training and prediction with interpolation.
Extends AbstractResult with training outputs (gamma, membership_prob) and provides spatial interpolation via the trained decoder network.
- Variables:
positions (VectorComponents) – Original position data (dict with 1D arrays).
velocities (VectorComponents) – Original velocity data (dict with 1D arrays).
indices (ISzN) – Indices sorted by gamma value.
gamma_range (tuple[float, float]) – Valid range for the ordering parameter: calling the result accepts any $gamma$ in it, including every tracer’s own.
track_range (tuple[float, float] | None) – The range of $gamma$ the track covers, for drawing it:
result(jnp.linspace(*result.track_range, n)). Each end is where the weighted number of member tracers per unit length along the track falls below half its value just inside, so faint tracers past the end of a stream – the blurred tail of a density field – don’t carry the track past the end, while a stream that narrows or fades keeps its ends. Withingamma_range.Nonefor a result built by hand; training sets it.gamma (FSzN) – Ordering parameters for all tracers.
membership_prob (Array) – Membership probabilities for all tracers.
model (AbstractAutoencoder) – Trained autoencoder model with decoder for spatial interpolation.
- Parameters:
positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])indices (
Int[Array, 'N'])gamma (
Float[Array, 'N'])membership_prob (
Float[Array, 'N'])model (
AbstractAutoencoder)velocity_aware (
bool)
-
indices:
Int[Array, 'N']#
-
gamma:
Float[Array, 'N']#
-
membership_prob:
Float[Array, 'N']#
-
model:
AbstractAutoencoder#
- velocity_aware: bool = False#
- class phasecurvefit.nn.OrderingTrainingConfig(*, optimizer: ~optax._src.base.GradientTransformation = (<function chain.<locals>.init_fn>, <function chain.<locals>.update_fn>), n_epochs: int = 800, batch_size: int = 100, lambda_prob: float = 1.0, arclength_alpha: float = 0.8, show_pbar: bool = True)#
Bases:
objectConfiguration for interpolation network training.
- Parameters:
-
optimizer:
GradientTransformation= (<function chain.<locals>.init_fn>, <function chain.<locals>.update_fn>)#
-
arclength_alpha:
float= 0.8# Blend factor for arclength-like targets.
If 0.0, the training targets use uniform spacing in $gamma$. If 1.0, the targets are proportional to cumulative arclength along the ordered tracers: the orderer’s
chordwhen train_ordering_net is given one, otherwise the sum of straight-line steps between consecutive ordered positions in all_ws. Values in (0, 1) linearly blend the two targets; values outside [0, 1] are clipped. The default, 0.8, leans towards arclength.
- class phasecurvefit.nn.AbstractNormalizer(qs: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], ps: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], **kwargs: object)#
Bases:
ReprMixinAbstract base class for normalizers used in autoencoders.
- Parameters:
- abstractmethod transform(qs: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], ps: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])#
Transform the data using the fitted normalizer.
- abstractmethod inverse_transform(qs: Float[Array, 'N D'], ps: Float[Array, 'N D'])#
Inverse transform the data back to original space.
- class phasecurvefit.nn.StandardScalerNormalizer(qs, ps, /, **_)#
Bases:
AbstractNormalizerStandardize phase-space data to zero mean and unit variance.
This normalizer computes per-component statistics from the provided position and velocity dictionaries, then uses them to scale data during transform() and restore it during inverse_transform().
- Parameters:
qs (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Mapping of position components to arrays with shape(N,).ps (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Mapping of velocity components to arrays with shape(N,).**kwargs – Ignored extra arguments for compatibility with other normalizers.
_ (object)
Examples
Basic usage with dict-based phase-space data
>>> import jax.numpy as jnp >>> qs = {"x": jnp.array([0.0, 1.0, 2.0]), "y": jnp.array([0.5, 1.5, 2.5])} >>> ps = {"vx": jnp.array([1.0, 1.0, 2.0]), "vy": jnp.array([0.0, 1.0, 1.0])} >>> normalizer = StandardScalerNormalizer(qs, ps) >>> q_std, p_std = normalizer.transform(qs, ps) >>> q_orig, p_orig = normalizer.inverse_transform(q_std, p_std)
Using the spatial dimension count
>>> normalizer = StandardScalerNormalizer(qs, ps) >>> normalizer.n_spatial_dims 2
- Parameters:
- transform(qs, ps)#
Standardize the input data: zero mean and unit variance.
- inverse_transform(qs: Float[Array, 'N D'], ps: Float[Array, 'N D'])#
Inverse the standardization to return to original data space.
Training Functions#
- phasecurvefit.nn.train_autoencoder(model, all_ws, ordering_indices, /, *, config=None, chord=None, weights=None, key)#
Train the PathAutoencoder in three phases.
This function orchestrates the complete three-phase training procedure:
Phase 1 (OrderingNet/Encoder): Trains the encoder to predict $gamma$ (ordering parameter) and $p$ (membership probability) from phase-space coordinates. Uses the ordering from the walk algorithm as supervision.
Phase 2 (TrackNet/Decoder): Trains the decoder, with the encoder frozen, to reproduce a running mean of member positions as a function of $gamma$. Uses the trained encoder to filter stream members based on the membership probability threshold.
Phase 3 (joint): Trains encoder and decoder together on spatial reconstruction plus velocity alignment, with the velocity weight ramped over
config.lambda_p. Skipped whenconfig.n_epochs_both == 0.Each phase optimizes a different objective, so the concatenated
lossesare not comparable across phase boundaries. The returned model holds the weights from the final epoch of the last phase that ran; no best-epoch checkpoint is kept.- Parameters:
model (EncoderExternalDecoder) – Untrained or partially trained autoencoder model.
all_ws (Array, shape (N, 2*n_dims)) – All phase-space coordinates (positions + velocities).
ordering_indices (Array, shape (N,)) – Ordering indices from walk algorithm. Valid indices (>= 0) indicate ordered tracers; -1 indicates skipped/unordered tracers.
chord (Array or Quantity, shape (N,) | None, keyword-only) – The orderer’s arc-length parameter (
OrderingResult.chord), passed through to the encoder’s arclength target. TheOrderingResultoverload supplies this automatically.weights (Array, shape (N,) | None, keyword-only) – Per-tracer weights, in input order, e.g. the density at each pixel of a density field; the
OrderingResultoverload takes them from the result’sweights. All three phases use them: the encoder’s $gamma$ targets spread tracers by cumulative weight and its loss is weighted (see train_ordering_net), the decoder is trained on a weighted running mean with a weighted loss, and the joint loss is weighted. A tracer of weight 2 then counts like two coincident tracers of weight 1.None(default) weighs every tracer equally.config (OrderingTrainingConfig, optional) – Complete training configuration for all three phases. If None (default), uses default configuration.
key (PRNGKeyArray) – Random key for training (split internally for each phase).
model – The autoencoder model to train. Its encoder will be updated.
all_ws – All phase-space coordinates (positions + velocities) in normalized form.
ordering_indices – Ordering indices from walk algorithm. Valid indices (>= 0) indicate ordered tracers; -1 indicates skipped/unordered tracers.
config – Training configuration for the encoder. If None, uses default config.
chord – The orderer’s arc-length parameter (
OrderingResult.chord), passed through to the encoder’s arclength target. TheOrderingResultoverload supplies this automatically.weights – Per-tracer weights, in input order. They weight the encoder’s training (see train_ordering_net) and the running-mean decoder. The
OrderingResultoverload takes them from the result’sweights.decoder_kwargs (Mapping, optional) – Keyword arguments passed to decoder function creation. For running-mean decoder, can include ‘window_size’. If None, uses defaults.
key – Random key for training.
- Return type:
tuple[AutoencoderResult,dict[str,PyTree],n_epochs}']]- Returns:
result (AutoencoderResult) – Result containing the fully trained autoencoder and ordering data.
opt_states (dict[str, optax.OptState]) – Dictionary with ‘encoder’, ‘decoder’ and ‘both’ optimizer states.
losses (Array, shape (n_epochs_encoder + n_epochs_decoder + n_epochs_both,)) – Per-epoch training losses of the three phases, concatenated in order.
.. py (function:: train_autoencoder(model: phasecurvefit._src.nn.abstractautoencoder.AbstractAutoencoder, walk_results: phasecurvefit._src.orderers.result.OrderingResult, /, *, config: phasecurvefit._src.nn.autoencoder.TrainingConfig | None = None, weights: jaxtyping.Float[Array, ‘N’] | None = None, key: Union[jaxtyping.Key[Array, ‘’], jaxtyping.UInt32[Array, ‘2’], jaxtyping.UInt32[Array, ‘4’]]) -> tuple[phasecurvefit._src.nn.result.AutoencoderResult, dict[str, jaxtyping.PyTree], jaxtyping.Float[Array, ‘{config.n_epochs}’]]) – :noindex:
.. py (function:: train_autoencoder(model: phasecurvefit._src.nn.externalautoencoder.EncoderExternalDecoder, all_ws: jaxtyping.Float[Array, ‘N TwoF’], ordering_indices: jaxtyping.Int[Array, ‘N’], /, *, config: phasecurvefit._src.nn.order_net.OrderingTrainingConfig | phasecurvefit._src.nn.autoencoder.TrainingConfig | None = None, chord: jaxtyping.Float[Array, ‘N’] | None = None, weights: jaxtyping.Float[Array, ‘N’] | None = None, key: Union[jaxtyping.Key[Array, ‘’], jaxtyping.UInt32[Array, ‘2’], jaxtyping.UInt32[Array, ‘4’]]) -> tuple[phasecurvefit._src.nn.result.AutoencoderResult, dict[str, jaxtyping.PyTree], jaxtyping.Float[Array, ‘{config.n_epochs}’]]) – :noindex:
Train the EncoderExternalDecoder encoder and create running-mean decoder.
This function provides a simplified training workflow
1. Train the encoder (OrderingNet) using supervised learning from ordering indices
2. Create a running-mean decoder using the trained encoder and training data
Unlike train_autoencoder for PathAutoencoder, this does not train a decoder
network. Instead, it uses the provided (or default) decoder function.
- Returns:
result (AutoencoderResult) – Result containing the trained autoencoder and ordering data.
opt_state (dict[str, PyTree]) – Optimizer state from encoder training (wrapped in dict for consistency).
losses (Array, shape (n_epochs,)) – Training losses from encoder training.
Examples
>>> import jax.numpy as jnp >>> import jax.random as jr >>> import phasecurvefit as pcf
>>> key = jr.key(0) >>> N = 50 >>> positions = {"x": jnp.arange(N, dtype=float), "y": jnp.zeros(N)} >>> velocities = {"x": jnp.ones(N), "y": jnp.zeros(N)} >>> ordering = jnp.arange(N)
>>> model = pcf.nn.EncoderExternalDecoder( ... pcf.nn.OrderingNet(in_size=4, width_size=32, depth=2, key=jr.key(1)), ... pcf.nn.RunningMeanDecoder(window_size=0.05), ... pcf.nn.StandardScalerNormalizer(positions, velocities), ... )
Train (with minimal epochs for demonstration)
>>> qs_norm, ps_norm = model.normalizer.transform(positions, velocities) >>> ws_norm = jnp.concat([qs_norm, ps_norm], axis=1) >>> config = pcf.nn.OrderingTrainingConfig( ... n_epochs=10, batch_size=16, show_pbar=False ... ) >>> result, opt_state, losses = pcf.nn.train_autoencoder( ... model, ws_norm, ordering, config=config, key=jr.key(2) ... ) >>> losses.shape (10,)
- phasecurvefit.nn.fill_ordering_gaps(model: AbstractAutoencoder, result: AbstractResult, /, prob_threshold: float = 0.5)#
Use trained autoencoder to fill gaps in phase-flow walk ordering.
This function predicts $gamma$ values for all tracers (including those skipped by phase-flow walk) and returns a complete ordering.
- Parameters:
model (PathAutoencoder) – Trained autoencoder model.
result (AbstractResult) – Result from an orderer.
prob_threshold (float, optional) – Minimum membership probability to include. Default: 0.5.
- Returns:
result – Complete ordering including previously skipped tracers.
- Return type:
Examples
>>> import jax >>> import jax.numpy as jnp >>> import phasecurvefit as pcf
>>> pos = {"x": jnp.linspace(0, 5, 20), "y": jnp.zeros(20)} >>> vel = {"x": jnp.ones(20), "y": jnp.zeros(20)} >>> result = pcf.order(pos, vel) >>> keys = jax.random.split(jax.random.key(0), 2) >>> normalizer = pcf.nn.StandardScalerNormalizer(pos, vel) >>> model = pcf.nn.PathAutoencoder.make( ... normalizer, gamma_range=result.gamma_range, key=keys[0] ... ) >>> cfg = pcf.nn.TrainingConfig(show_pbar=False) >>> result, *_ = pcf.nn.train_autoencoder(model, result, config=cfg, key=keys[1])
- phasecurvefit.nn.train_ordering_net(model: OrderingNet, all_ws: Float[Array, 'N TwoF'], ordering_indices: Int[Array, 'N'], /, config: OrderingTrainingConfig | None = None, *, chord: Float[Array, 'N'] | None = None, weights: Float[Array, 'N'] | None = None, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'])#
Train the interpolation network on ordered stream tracers.
This implementation uses lax.scan for efficient batching and supports Orbax checkpointing. The training follows the pattern from the original autoencoder for maximum performance.
- Parameters:
model (OrderingNet) – The interpolation network to train.
all_ws (Array, shape (N, 2*n_dims)) – Phase-space coordinates from the walk algorithm.
chord (Array or Quantity, shape (N,) | None, keyword-only) – The orderer’s arc-length parameter per observation, in input order (
OrderingResult.chord). When given it supplies the arclength target thatarclength_alphablends toward; whenNonethat target is approximated by summing straight-line steps between consecutive ordered observations, which is noisier and lives in normalized space. A Quantity chord is stripped in its own unit; only ratios of it are used.weights (Array, shape (N,) | None, keyword-only) – Per-tracer weights, in input order, e.g. the density at each pixel of a density field. They weight each tracer’s terms in the loss, and the uniform-spacing part of the $gamma$ target spreads tracers by cumulative weight rather than by count, so a tracer of weight 2 is treated like two coincident tracers of weight 1.
None(default) weighs every tracer equally.ordering_indices (Array, shape (N,)) – Indices representing the ordering of tracers. Unvisited tracers have indices of -1.
config (OrderingTrainingConfig | None) – Training configuration. If None, uses default config. Its arclength_alpha (default 0.8) blends the targets towards cumulative arclength along the ordered tracers, which reduces local compression of $gamma$ and improves rolling-mean decoders; set it to 0.0 for uniform spacing in $gamma$.
key (PRNGKeyArray) – Random key for shuffling and random sampling.
- Return type:
tuple[OrderingNet,Union[Array,ndarray,bool,number,Iterable[ArrayTree],Mapping[Any, ArrayTree]],Float[Array, 'E']]- Returns:
trained_net (OrderingNet) – The trained interpolation network.
opt_state (optax.OptState) – The optimizer state after training.
losses (Array, shape (n_epochs,)) – Training loss per epoch.
- phasecurvefit.nn.encoder_loss(gamma_true: Float[Array, 'N'], gamma_pred: Float[Array, 'N'], prob_pred_ordered: Float[Array, 'N'], prob_pred_random: Float[Array, 'N'], mask: Bool[Array, 'N'], *, lambda_prob: float = 1.0, weights: Float[Array, 'N'] | None = None)#
Compute loss for interpolation network training.
- Parameters:
gamma_true (Array, shape (N,)) – True $gamma$ values for ordered stream tracers.
gamma_pred (Array, shape (N,)) – Predicted $gamma$ values from the interpolation network.
prob_pred_ordered (Array, shape (N,)) – Predicted membership probabilities for ordered stream tracers. Should be pushed toward 1.
prob_pred_random (Array, shape (M,)) – Predicted membership probabilities for random phase-space samples. Should be pushed toward 0.
mask (Array, shape (N,)) – Binary mask where True = real data, False = padding. Only masked positions contribute to the loss.
lambda_prob (float, optional) – Weight for probability penalties. Default: 1.0.
weights (Array, shape (N,), optional) – Per-tracer weights on the $gamma$ term, normalized to mean 1 over the training set.
None(default) weighs every tracer equally. The membership terms are not weighted: a weight says how much a tracer counts in the track, not how sure we are that it belongs, and a weighted membership term would let faint tracers (the tails of a density field) fall below the membership threshold and drop out.
- Returns:
loss – Scalar loss value.
- Return type:
Array
Membership & Outlier Rejection#
Mixture-model membership, after Hogg, Bovy & Lang (2010), §3. See Outlier rejection with a mixture model.
- class phasecurvefit.nn.MixtureMembershipConfig(*, sigma_init: float = 0.1, sigma_min: float = 0.001, sigma_ceiling: tuple[float, float] = (0.5, 0.1), warmup_frac: float = 0.3, background_density: float | None = None, background_inflate: float = 1.0, width_size: int = 32, depth: int = 2, lambda_velocity: float = 1.0)#
Bases:
objectConfiguration for mixture-model membership (outlier rejection).
Pass an instance of this to phasecurvefit.nn.TrainingConfig.membership to swap the classifier-style membership loss for the generative mixture model of Hogg, Bovy & Lang (2010), §3.
Leaving
membership=None(the default) preserves the existing behaviour exactly.- Variables:
sigma_init (float) – Stream half-width the WidthNet is initialised to predict. Set it to your best guess at the stream width, in the normalised coordinates the networks see (StandardScalerNormalizer makes this roughly “in units of the field’s standard deviation”).
sigma_min (float) – Hard floor on the width, guarding the collapse-onto-a-single-star degeneracy that afflicts every mixture likelihood.
sigma_ceiling (tuple[float, float]) –
(start, stop)for the annealing ceiling on the width, applied geometrically across epochs; see sigma_ceiling.startshould be a few times the expected width,stopof order the width. This is one of the two knobs that matter: with no ceiling, a free width will inflate to swallow nearby outliers rather than reject them.warmup_frac (float) – Fraction of training spent ramping the membership term in; see membership_rampup. This is the other knob that matters: with no warm-up, the model can collapse to “everything is background” before the track has fitted, and never recover. Set to 0 only if you are supplying an already-good track.
background_density (float | None) – $rho_{mathrm{bg}}$. If None (default), computed from the extent of the training positions via uniform_background_density.
background_inflate (float) – Passed to uniform_background_density when
background_densityis None. Increase if the observed stars do not fill the survey footprint.depth (width_size,) – Architecture of the WidthNet.
lambda_velocity (float) – Weight on the velocity-alignment term, which is reweighted by the posterior responsibility so that outliers cannot drag the track’s tangent. Set to 0 to disable the velocity term entirely.
- Parameters:
Examples
>>> import phasecurvefit as pcf
Enable outlier rejection with a stream you expect to be ~0.1 wide:
>>> membership = pcf.nn.MixtureMembershipConfig( ... sigma_init=0.1, sigma_ceiling=(0.5, 0.1) ... ) >>> cfg = pcf.nn.TrainingConfig(membership=membership, show_pbar=False) >>> cfg.membership.sigma_init 0.1
The default is None, i.e. the legacy classifier membership:
>>> pcf.nn.TrainingConfig().membership is None True
- Parameters:
- make_width_net(*, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'])#
Build the WidthNet this config describes.
- Parameters:
key (
Union[Key[Array, ''],UInt32[Array, '2'],UInt32[Array, '4']])- Return type:
- class phasecurvefit.nn.WidthNet(width_size: int = 32, depth: int = 2, *, sigma_init: float = 0.1, sigma_min: float = 0.001, sigma_max: float | None = None, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'])#
Bases:
ReprMixin,ModuleWidth $sigma$ of the foreground component along the ordering parameter.
The foreground density need not have a uniform width. A stream, for example, is typically narrow near the progenitor and fans out towards the tidal tails; the same is true of many curved distributions. A single scalar $sigma$ forces one compromise, which is both a worse fit and – more importantly – a worse outlier detector, because the compromise width is too generous wherever the stream is genuinely thin.
This is a small MLP $gamma mapsto log sigma_{mathrm{raw}}(gamma)$, exponentiated to guarantee positivity and then capped from above by an annealing ceiling (see sigma_ceiling):
\[\sigma(\gamma, t) = \min\!\big( \sigma_{\mathrm{raw}}(\gamma),\; \sigma_{\mathrm{ceil}}(t) \big)\]The floor is enforced by construction (
expis positive) plussigma_min, which keeps the Gaussian from collapsing onto individual stars – the classic degenerate maximum of any mixture likelihood, where one component shrinks to zero width around a single point and the likelihood diverges.- Parameters:
width_size (int) – Hidden-layer size and number of hidden layers of the MLP.
depth (int) – Hidden-layer size and number of hidden layers of the MLP.
sigma_init (float) – Width the network is initialised to predict, everywhere. Choose something comparable to the expected stream width; it only sets the starting point.
sigma_min (float) – Hard floor on the returned width. Guards the collapse-onto-a-star degeneracy. Should be well below the true stream width (e.g. the typical positional uncertainty).
sigma_max (float | None) – Cap on the returned width when the call gives no
ceiling. Training sets it to the last value of sigma_ceiling, so that a trained model reports the width training ended with.None(default) means no cap.key (PRNGKeyArray) – JAX random key for initialisation.
Examples
>>> import jax.numpy as jnp >>> import jax.random as jr >>> import phasecurvefit as pcf
>>> width = pcf.nn.WidthNet(sigma_init=0.2, key=jr.key(0))
At initialisation the predicted width is close to
sigma_initeverywhere:>>> sigma = width(jnp.array(0.3)) >>> bool(0.1 < sigma < 0.4) True
It is a scalar-in, scalar-out function, so
vmapit over a batch:>>> import jax >>> gammas = jnp.linspace(-1.0, 1.0, 5) >>> jax.vmap(width)(gammas).shape (5,)
Widths are strictly positive, always:
>>> bool(jnp.all(jax.vmap(width)(gammas) > 0)) True
- phasecurvefit.nn.posterior_membership(model: PathAutoencoder, ws: Float[Array, 'N TwoF'], /, *, background_density: float | None = None, key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None = None)#
Posterior probability that each point belongs to the foreground component.
The foreground is whatever the model fits a track through – a stream is the running example. This is the number you want when deciding which points are members. It is not the encoder’s raw
proboutput: that is only the prior $pi_n$, formed from the star’s phase-space coordinates before the model has looked at how far the star actually landed from the fitted track. This function folds in the residual, giving the posterior of Hogg, Bovy & Lang (2010), §3:\[\hat{q}_n = \frac{\pi_n \, \mathcal{N}(r_n; 0, \sigma^2(\gamma_n))} {\pi_n \, \mathcal{N}(r_n; 0, \sigma^2(\gamma_n)) + (1 - \pi_n) \, \rho_{\mathrm{bg}}}\]Here $sigma(gamma_n)$ is the fitted width, capped at the ceiling training ended with (the
stopofsigma_ceiling), so the posterior uses the same width as the last epoch of training.Requires a model trained with MixtureMembershipConfig (so that
model.widthexists).- Parameters:
model (PathAutoencoder) – A model trained with mixture membership.
ws (Array, shape (N, 2D)) – Phase-space coordinates, in the same normalised frame used for training.
background_density (float | None) – $rho_{mathrm{bg}}$. If None, recomputed from the extent of
ws. Pass the same value used at training time if you are scoring a different field from the one you trained on – otherwise the posterior is calibrated against the wrong background.key (PRNGKeyArray | None) – Optional key for the (deterministic) networks.
- Returns:
responsibility – Posterior membership in [0, 1]. Threshold at 0.5 for a hard cut, or keep it as a weight – Hogg et al. recommend the latter.
- Return type:
Array, shape (N,)
- Raises:
ValueError – If the model was not trained with mixture membership.
- phasecurvefit.nn.mixture_membership_loss(qs_meas: Float[Array, 'N D'], qs_pred: Float[Array, 'N D'], prob: Float[Array, 'N'], sigma: Float[Array, 'N'], mask: Bool[Array, 'N'], /, *, log_bg_density: float, rampup: Float[Array, ''] | float = 1.0, weights: Float[Array, 'N'] | None = None)#
Negative log-likelihood of the stream/background mixture.
Implements the “mixture” model of Hogg, Bovy & Lang (2010), §3, with the bad-data fraction amortised into a per-star, network-predicted $pi_n$:
\[-\log \mathcal{L} = -\frac{1}{N} \sum_n \omega_n \log\!\left[ \pi_n \, \mathcal{N}\!\left(q_n; x_{\theta}(\gamma_n), \sigma_n^2 \mathbb{I}\right) + (1 - \pi_n) \, \rho_{\mathrm{bg}} \right]\]Minimising this simultaneously fits the track ($x_{theta}$), the width ($sigma$), and the membership ($pi$) – and the last of these is now driven by the residual, which is the entire point.
Evaluated with jax.nn.logsumexp semantics (via jnp.logaddexp) so that a star which is implausible under both components – very far from the track and in a low-density corner – does not underflow to
-inf.- Parameters:
qs_meas (Array, shape (N, D)) – Observed positions.
qs_pred (Array, shape (N, D)) – Decoded track positions, $x_{theta}(gamma_n)$.
prob (Array, shape (N,)) – Encoder membership output $pi_n$, in [0, 1].
sigma (Array, shape (N,)) – Stream half-width at each star’s $gamma$. Must be positive.
mask (Array, shape (N,)) – True for real, usable stars; False for padding or ignorable rows. Only masked-in stars contribute.
log_bg_density (float) – $log rho_{mathrm{bg}}$; see uniform_background_density.
rampup (Array, shape () | float, optional) – Membership ramp $w in [0, 1]$ from membership_rampup. The effective membership is $pi^{mathrm{eff}} = 1 - w (1 - pi)$, so
w=0gives a pure reconstruction NLL andw=1the full mixture. Defaults to 1 (no warm-up); see membership_rampup for why you almost certainly want to ramp.weights (Array, shape (N,), optional) – Per-star weights $omega_n$, normalized to mean 1 over the training set. A star of weight $omega_n$ counts like $omega_n$ coincident stars, so it scales that star’s term in the loss. It does not change the star’s responsibility, which depends only on where the star is.
None(default) weighs every star equally.
- Return type:
tuple[Float[Array, ''],Float[Array, 'N']]- Returns:
loss (Array, shape ()) – Mean negative log-likelihood over the masked-in stars.
responsibility (Array, shape (N,)) – Posterior membership $hat{q}_n$ for every star (including masked-out ones, whose values are meaningless). Returned because the caller almost always wants it – to weight the velocity-alignment term, and to report membership – and recomputing it would duplicate the whole forward pass.
Computed from the effective membership, so during warm-up it is (correctly) close to 1 everywhere.
Examples
>>> import jax.numpy as jnp >>> from phasecurvefit.nn import mixture_membership_loss
Two stars on the track and one far off it. With a confident prior, the on-track stars get responsibility ~1 and the outlier ~0:
>>> qs_meas = jnp.array([[0.0, 0.0], [1.0, 0.0], [0.0, 9.0]]) >>> qs_pred = jnp.array([[0.0, 0.0], [1.0, 0.0], [0.0, 0.0]]) >>> prob = jnp.array([0.9, 0.9, 0.9]) >>> sigma = jnp.array([0.1, 0.1, 0.1]) >>> mask = jnp.ones(3, dtype=bool) >>> loss, resp = mixture_membership_loss( ... qs_meas, qs_pred, prob, sigma, mask, log_bg_density=float(jnp.log(0.01)) ... ) >>> bool(resp[0] > 0.99), bool(resp[1] > 0.99), bool(resp[2] < 0.01) (True, True, True)
The loss is finite even for the wildly-discrepant star:
>>> bool(jnp.isfinite(loss)) True
- phasecurvefit.nn.membership_responsibility(prob: Float[Array, 'N'], r2: Float[Array, 'N'], sigma: Float[Array, 'N'], /, *, log_bg_density: Float[Array, ''] | float, n_dims: int)#
Posterior probability that each star is a stream member.
This is the E-step of the mixture model: given the current track, width, and prior membership $pi_n$, the posterior membership of star $n$ is
\[\hat{q}_n = \frac{\pi_n \, \mathcal{N}(r_n; 0, \sigma_n^2)} {\pi_n \, \mathcal{N}(r_n; 0, \sigma_n^2) + (1 - \pi_n)\, \rho_{\mathrm{bg}}}\]which is Hogg, Bovy & Lang (2010)’s $q_i$ after marginalisation – the quantity they recommend reporting instead of a hard cut.
Note the distinction from
prob: $pi_n$ is what the encoder believes from the star’s phase-space coordinates alone, before seeing how far it actually landed from the track. $hat{q}_n$ folds in the residual. The responsibility is the number you want when identifying members;probis only its prior.- Parameters:
prob (Array, shape (N,)) – Encoder membership output $pi_n$, in [0, 1].
r2 (Array, shape (N,)) – Squared residual $lVert q_n - x_{theta}(gamma_n) rVert^2$.
sigma (Array, shape (N,)) – Stream half-width at each star’s $gamma$.
log_bg_density (float) – $log rho_{mathrm{bg}}$.
n_dims (int) – Spatial dimensionality $D$.
- Returns:
responsibility – Posterior membership in [0, 1].
- Return type:
Array, shape (N,)
Examples
>>> import jax.numpy as jnp >>> from phasecurvefit.nn import membership_responsibility
A star sitting exactly on the track, with a flat prior, is confidently a member; one far away is confidently not:
>>> prob = jnp.array([0.5, 0.5]) >>> r2 = jnp.array([0.0, 100.0]) # on the track / far off it >>> sigma = jnp.array([0.1, 0.1]) >>> q = membership_responsibility( ... prob, r2, sigma, log_bg_density=float(jnp.log(0.01)), n_dims=2 ... ) >>> bool(q[0] > 0.99), bool(q[1] < 0.01) (True, True)
- phasecurvefit.nn.sigma_ceiling(epoch_idx: Int[Array, ''] | int, num_epochs: int, /, *, start: float, stop: float)#
Annealing ceiling on the stream width, geometric from start to stop.
The mixture likelihood has a well-known failure mode: rather than lowering the membership of a few nearby outliers, it can simply widen the stream component until they are explained. The likelihood genuinely prefers this, so no amount of training fixes it – it is not a convergence problem.
Annealing removes the option. Early on the ceiling is generous, which is what we want: the decoded track is still garbage, so every star is far from it, and an aggressive width would reject the entire stream. As the track sharpens, the ceiling is squeezed and stars that stay far from the track are progressively forced to explain themselves as background.
The schedule is geometric (linear in $log sigma$), which is the natural choice for a scale parameter.
- Parameters:
epoch_idx (Array, shape () | int) – Current epoch, in
[0, num_epochs). May be a tracer.num_epochs (int) – Total number of epochs. Must be static.
start (float) – Ceiling at the first and last epoch.
startshould be comfortably larger than the expected stream width (a few times is fine);stopshould be of order the stream width.stop (float) – Ceiling at the first and last epoch.
startshould be comfortably larger than the expected stream width (a few times is fine);stopshould be of order the stream width.
- Returns:
ceiling – The width ceiling for this epoch.
- Return type:
Array, shape ()
Examples
>>> import jax.numpy as jnp >>> from phasecurvefit.nn import sigma_ceiling
The ceiling starts at
startand ends atstop:>>> float(sigma_ceiling(0, 5, start=1.0, stop=0.1)) 1.0 >>> round(float(sigma_ceiling(4, 5, start=1.0, stop=0.1)), 6) 0.1
…and is geometric in between, so the midpoint is the geometric mean:
>>> round(float(sigma_ceiling(2, 5, start=1.0, stop=0.01)), 6) 0.1
A single-epoch run just uses
start:>>> float(sigma_ceiling(0, 1, start=1.0, stop=0.1)) 1.0
- phasecurvefit.nn.membership_rampup(epoch_idx: Int[Array, ''] | int, num_epochs: int, /, *, warmup_frac: float)#
Ramp the membership term in from zero: 0 during warm-up, 1 afterwards.
Why this is not optional#
The mixture likelihood has a second degenerate optimum, and it is worse than the width-inflation one because it is self-reinforcing.
At initialisation the decoded track is meaningless, so every star has a huge residual. The likelihood’s cheapest move is to declare the whole dataset background: push $pi_n to 0$ for all $n$. But once $pi_n = 0$ the stream component carries no weight, so no gradient reaches the decoder – the track is free to drift anywhere, residuals grow further, and $pi$ is pinned at zero forever. Training collapses to “there is no stream”. We have measured this: with outliers at 20 stream-widths, an un-ramped mixture drove the median inlier residual to ~8 (stream width 0.15) and rejected all 400 genuine members.
The cure is the standard EM initialisation: fit the track first, with membership effectively pinned at 1, and only then let the model start disowning stars. Concretely we use
\[\pi^{\mathrm{eff}}_n = 1 - w(t)\,(1 - \pi_n)\]so that at $w = 0$ the loss degenerates to the plain Gaussian reconstruction NLL (the background term vanishes), and at $w = 1$ it is the full mixture. Gradients still flow into $pi$ during warm-up (through the $w pi_n$ term), they simply cannot yet act on the reconstruction.
Together with sigma_ceiling this brackets the problem from both sides: the ramp stops membership collapsing before the track exists, and the ceiling stops the width inflating once it does.
- type epoch_idx:
Int[Array, '']|int- param epoch_idx:
Current epoch, in
[0, num_epochs). May be a tracer.- type epoch_idx:
Array, shape () | int
- type num_epochs:
- param num_epochs:
Total number of epochs. Must be static.
- type num_epochs:
int
- type warmup_frac:
- param warmup_frac:
Fraction of training spent ramping, in
[0, 1).wrises linearly from 0 to 1 across the firstwarmup_frac * (num_epochs - 1)epochs and stays at 1 thereafter.0disables the ramp (full mixture from epoch zero) – don’t, unless you have a good reason.- type warmup_frac:
float
- returns:
w – Ramp value in [0, 1].
- rtype:
Array, shape ()
Examples
>>> from phasecurvefit.nn import membership_rampup
With a 50% warm-up the mixture is fully on by the halfway point:
>>> float(membership_rampup(0, 10, warmup_frac=0.5)) 0.0 >>> float(membership_rampup(5, 10, warmup_frac=0.5)) 1.0 >>> float(membership_rampup(9, 10, warmup_frac=0.5)) 1.0
…and rises linearly in between:
>>> round(float(membership_rampup(2, 10, warmup_frac=0.5)), 3) 0.444
warmup_frac=0means no warm-up at all:>>> float(membership_rampup(0, 10, warmup_frac=0.0)) 1.0
- phasecurvefit.nn.uniform_background_density(qs: Float[Array, 'N D'], /, *, inflate: float = 1.0)#
Flat background density $rho_{mathrm{bg}}$ from the field’s extent.
The mixture model needs a density for the “not a stream member” component. Hogg, Bovy & Lang (2010) §3 use a broad Gaussian $(Y_b, V_b)$ and marginalise over it; when the field is a bounded footprint – as it is here – the natural analogue is a uniform density over that footprint,
\[\rho_{\mathrm{bg}} = \frac{1}{\prod_d \left(\max_d q - \min_d q\right)} .\]This is not a free knob to tune: it is the reciprocal of the field volume, and it is what makes membership a calibrated posterior rather than an arbitrary cut. It is, however, the quantity that sets where the stream/background crossover sits, so it is worth being deliberate about the footprint you hand it.
- Parameters:
qs (Array, shape (N, D)) – Positions defining the field.
inflate (float, optional) – Multiply the extent of each axis by this factor before taking the volume. Use
> 1if the observed points do not fill the true survey footprint. Default 1.
- Returns:
rho_bg – Background density, in units of (length)^-D. Returned as a 0-d array so that it stays trace-transparent under
jit(e.g. inside posterior_membership); usefloat(...)if you need a Python scalar.- Return type:
Array, scalar
Examples
>>> import jax.numpy as jnp >>> from phasecurvefit.nn import uniform_background_density
A unit square has unit background density:
>>> qs = jnp.array([[0.0, 0.0], [1.0, 1.0]]) >>> float(uniform_background_density(qs)) 1.0
A 2x2 square has a quarter the density:
>>> qs = jnp.array([[0.0, 0.0], [2.0, 2.0]]) >>> float(uniform_background_density(qs)) 0.25
SOM Module#
Self-Organizing Map ordering, after Starkman et al. (2023). See The self-organizing map.
SOMOrderer is listed under Orderers.
- class phasecurvefit.som.SOM1D(prototype_positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], prototype_velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], metric: AbstractDistanceMetric, metric_scale: float | Float[Array, ''] = 0.0, n_epochs: int = 10, sigma_start: float | None = None, sigma_end: float = 0.7, densify_factor: int = 5)#
Bases:
ReprMixin,ModuleA trained or untrained 1-D Self-Organizing Map.
A thin, composable object over the functional core: it carries the prototypes and the hyperparameters, and its methods forward to
fit(),densify()andchord(). The functions remain the primary interface – an ensemble mapsvmapover those, not this class.Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> from phasecurvefit import som
>>> pos = {"x": jnp.linspace(0.0, 9.0, 60), "y": jnp.zeros(60)} >>> vel = {"x": jnp.ones(60), "y": jnp.zeros(60)}
>>> model = som.SOM1D.make( ... pos, vel, n_prototypes=8, metric=pcf.metrics.SpatialDistanceMetric() ... ) >>> model.n_prototypes 8 >>> trained = model.fit(pos, vel) >>> trained.chord(pos, vel).shape (60,)
- Parameters:
prototype_positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])prototype_velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])metric (
AbstractDistanceMetric)metric_scale (
float|Float[Array, ''])n_epochs (
int)sigma_end (
float)densify_factor (
int)
-
prototype_positions:
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]#
-
prototype_velocities:
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]#
-
metric:
AbstractDistanceMetric#
- classmethod make(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, n_prototypes: int, ordering: Int[Array, 'N'] | None = None, metric: AbstractDistanceMetric | None = None, **kwargs: object)#
Build an untrained SOM with prototypes initialized from the data.
- Parameters:
- Return type:
- fit(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /)#
Train on the data, returning a new SOM with updated prototypes.
- backbone()#
Return the densified, arc-length-uniform backbone polyline.
- phasecurvefit.som.init_prototypes(positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, n_prototypes: int, ordering: Int[Array, 'N'] | None = None)#
Initialize prototypes by equi-frequency binning.
This is the paper’s default initialization: place a prototype at the average location of every
n-th point along an ordering.- Parameters:
positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Phase-space components, 1-D arrays of shape(N,).velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Phase-space components, 1-D arrays of shape(N,).n_prototypes (
int) – Number of prototypes,K. Must be at least 2 and at most the number of points being binned.ordering (
Int[Array, 'N']|None) – Indices in order, as from a previous stage. WhenNone, bin along the first principal axis of the positions – the N-D replacement for the paper’s “bin in an observational longitude”. Requires that the curve not double back along that axis: past about one turn the initial lattice is tangled and training cannot repair it. Curves that wind further must pass anorderingfrom a prior stage.
- Returns:
Prototype positions and velocities, each of shape
(K,).- Return type:
Examples
>>> import jax.numpy as jnp >>> from phasecurvefit import som
>>> pos = {"x": jnp.linspace(0.0, 9.0, 10), "y": jnp.zeros(10)} >>> vel = {"x": jnp.ones(10), "y": jnp.zeros(10)} >>> pq, pp = som.init_prototypes(pos, vel, n_prototypes=5) >>> pq["x"].shape (5,)
- phasecurvefit.som.fit(proto_positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], proto_velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, metric: AbstractDistanceMetric, metric_scale: float | Float[Array, ''] = 0.0, n_epochs: int = 10, sigma_start: float | None = None, sigma_end: float = 0.7, weights: Float[Array, 'N'] | None = None, outlier_mixture: SOMMixture | None = None, mask: Bool[Array, 'N'] | None = None)#
Train a 1-D SOM by batch Kohonen updates.
Each epoch assigns every datum to its best-matching unit, then replaces every prototype by the neighbourhood-weighted mean of all the data:
\[p_k \leftarrow \frac{\sum_n h_{c(n),k}\, \omega_n r_n\, w_n} {\sum_n h_{c(n),k}\, \omega_n r_n}, \qquad h_{ij} = \exp\!\left(-\frac{(i-j)^2}{2\sigma^2}\right)\]The neighbourhood is equation (A8) of the paper on the paper’s linear lattice. The update replaces the paper’s online form (A9)/(A10): there is no learning rate. This batch form is the fixed point of the conventional online Kohonen update, whose increment is proportional to
w - p^(k)(The self-organizing map notes how that differs from (A9) as printed).omega_nisweights, defaulting to1for every datum.r_nis the datum’s membership of the curve underoutlier_mixture, and1without it. The paper has neither term, so with the defaults the sum above is exactly the un-weighted one. A non-finite velocity component is left out of both sums for that component, so a missing velocity cannot poison every prototype through the neighbourhood.sigmaanneals geometrically fromsigma_starttosigma_end, so the global ordering forms first and local detail is refined afterwards.sigma_endis reached on the last epoch, son_epochs=1runs its one epoch atsigma_startand never narrows; passsigma_start=sigma_endto train a single epoch at the final width.Setting
outlier_mixturemodels each datum’s position as drawn either from the curve or from a flat background (SOMMixture). Each epoch computes every datum’s membershipr_nfrom the current prototypes, fits the mixing fraction and the curve’s width by their closed-form M-steps, and then updates the prototypes as above. Early on the lattice is a rough copy of the curve, so the memberships are computed with the curve widened by a tenth ofsigma_ttimes the mean prototype spacing, wheresigma_tanneals geometrically frommax(sigma_start, K / 4)tosigma_endover the epochs. The widening is zero at the last epoch. It anneals from at leastK / 4even whensigma_startis narrow, as it is chained after another orderer, where the lattice starts from bin means that cut inside the curve’s bends. A weight multiplies every sum, the M-steps included, so a datum of weightwcounts likewcoincident copies; it never entersr_n. A fit whose mixing fraction ends below 0.5 keeps every datum, withresponsibility1: it called most of the data background, which is what happens when the data fill their own bounding box.- Parameters:
proto_positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Initial prototypes, shape(K,)per component.proto_velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Initial prototypes, shape(K,)per component.positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – The data, shape(N,)per component.velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – The data, shape(N,)per component.metric (
AbstractDistanceMetric) – Any symmetricAbstractDistanceMetric; seeSOMOrdererfor which, and why.metric_scale (
float|Float[Array, '']) – Scale parameter handed tometric; seeSOMOrderer.n_epochs (
int) – Number of batch updates. Static.sigma_start (
float|None) – Initial neighbourhood width in lattice units.Noneusesmax(K / 4, sigma_end), i.e.K / 4floored atsigma_endso the anneal is never inverted on a very small lattice.sigma_end (
float) – Final neighbourhood width in lattice units.weights (
Float[Array, 'N']|None) – Per-datum weightomega_nin the update above, shape(N,).None(default) weighs every datum equally. A datum weighted0contributes to no prototype’s update without changing any array’s shape.outlier_mixture (
SOMMixture|None) – ASOMMixtureto reject outliers, orNone(default) for none.mask (
Bool[Array, 'N']|None) – Which data take part, shape(N,).None(default) means all of them. AFalsedatum is treated as absent: its weight is0in every sum, the mixture’s included, and it isFalseinkeptwithresponsibility0. Unlike dropping it, this keeps every shape static, so a mask known only at run time still traces. A masked datum must still hold finite positions, since a weight of0times a non-finite value is not0, and it still counts towards the bounding box of the defaultbackground_density.
- Returns:
Trained prototype positions and velocities, each datum’s
responsibility, and the booleankeptmaskresponsibility >= 0.5.- Return type:
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> from phasecurvefit import som
>>> pos = {"x": jnp.linspace(0.0, 9.0, 50), "y": jnp.zeros(50)} >>> vel = {"x": jnp.ones(50), "y": jnp.zeros(50)} >>> pq, pp = som.init_prototypes(pos, vel, n_prototypes=6) >>> result = som.fit( ... pq, pp, pos, vel, metric=pcf.metrics.SpatialDistanceMetric(), n_epochs=20 ... ) >>> bool(jnp.all(jnp.diff(result.prototype_positions["x"]) > 0)) True >>> bool(jnp.all(result.kept)) True
With one wild outlier, the mixture finds it:
>>> pos_c = dict(pos) >>> pos_c["y"] = pos_c["y"].at[25].set(50.0) >>> pq, pp = som.init_prototypes(pos_c, vel, n_prototypes=6) >>> result = som.fit( ... pq, ... pp, ... pos_c, ... vel, ... metric=pcf.metrics.SpatialDistanceMetric(), ... n_epochs=20, ... outlier_mixture=som.SOMMixture(), ... ) >>> bool(result.kept[25]) False >>> int(result.kept.sum()) 49
- phasecurvefit.som.densify(proto_positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], proto_velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, factor: int = 5)#
Turn prototypes into a smooth, arc-length-uniform backbone polyline.
Densifying to a C1 curve is what removes the paper’s 2-D “convexity” case. On a piecewise-linear polyline every point whose nearest polyline point is a vertex receives the same arc length – a tie the paper broke with an
arctan2angle sweep that does not generalize past 2-D. On a smooth curve those wedges have angular extent of order (curvature x spacing) and vanish as the sampling densifies, so no angle machinery is needed at all.- Parameters:
proto_positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Prototypes, shape(K,)per component.proto_velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]]) – Prototypes, shape(K,)per component.factor (
int) – Samples per prototype segment; the result hasfactor * (K - 1) + 1vertices.factor=1still evaluates the spline, but at one sample per segment, which reproduces the prototypes to float32 rounding – so it smooths nothing. It does not skip the arc-length resampling, so the result is a polyline whose vertices are redistributed to equal spacing rather than the prototypes themselves – on unevenly spaced prototypes it cuts corners, and a corner prototype can end up off the emitted polyline entirely. Raising it buys down the interior geometric error but not the error in the first and last segments: the duplicated end stencil gives the phantom knot a near-zero spacing, so the parameterization stalls at the tips and those two segments keep a fixed error floor. The tips are wherechord()extrapolates past the ends, so that floor bounds end-cap accuracy.
- Returns:
Backbone positions and velocities.
- Return type:
Examples
>>> import jax.numpy as jnp >>> from phasecurvefit import som
>>> pq = {"x": jnp.linspace(0.0, 3.0, 4), "y": jnp.zeros(4)} >>> pp = {"x": jnp.ones(4), "y": jnp.zeros(4)} >>> bq, bp = som.densify(pq, pp, factor=5) >>> bq["x"].shape (16,)
- phasecurvefit.som.chord(backbone_positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], backbone_velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /, *, metric: AbstractDistanceMetric, metric_scale: float | Float[Array, ''] = 0.0)#
Project data onto the backbone and return the arc-length chord parameter.
This is the N-dimensional generalization of the paper’s Section 2.2.2. Each datum is assigned to its nearest backbone vertex under
metric, and then refined to sub-vertex resolution in position space, where projection onto a segment is actually defined.Whether that assignment is velocity-aware depends on
metricandmetric_scale. At the defaultmetric_scale=0.0the phase-space metric reduces to pure position distance, so anti-parallel arms of a near-closed loop can capture each other; The self-organizing map gives the contamination rates andSOMOrderercovers choosing a scale.The split is forced: a metric such as
AlignedMomentumDistanceMetricis not induced by an inner product, so “project onto a line segment” has no meaning under it. The metric therefore chooses which segment; Euclidean position geometry chooses where within it. The returned chord is consequently a genuine physical arc length along the track, computed as true cumulative arc length over the backbone – which need not be arc-length-uniform (densify()produces one that is, but this function does not assume it).- Returns:
Arc length per observation, in input order. Values outside
[0, L]are data beyond the tips (see_segment_projection).- Return type:
Float[Array, ” N”]
- Parameters:
backbone_positions (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
backbone_velocities (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
positions (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
velocities (Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']])
metric (AbstractDistanceMetric)
metric_scale (float | Float[Array, ''])
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> from phasecurvefit import som
>>> bq = {"x": jnp.linspace(0.0, 10.0, 11), "y": jnp.zeros(11)} >>> bp = {"x": jnp.ones(11), "y": jnp.zeros(11)} >>> pos = {"x": jnp.array([0.0, 5.0, 10.0]), "y": jnp.zeros(3)} >>> vel = {"x": jnp.ones(3), "y": jnp.zeros(3)} >>> lam = som.chord(bq, bp, pos, vel, metric=pcf.metrics.SpatialDistanceMetric()) >>> jnp.round(lam, 3) Array([ 0., 5., 10.], dtype=float32)
- Parameters:
backbone_positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])backbone_velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])metric (
AbstractDistanceMetric)metric_scale (
float|Float[Array, ''])
- Return type:
Float[Array, ’N’]
- phasecurvefit.som.bootstrap_weights(key: Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'], n_obs: int, /)#
Multinomial counts for one bootstrap resample, as
weightsforfit().Draws
n_obsindices with replacement and returns how often each datum was drawn. Handed tofitasweightsthis is a bootstrap resample: a datum drawn twice counts twice in the neighbourhood-weighted mean, and one never drawn counts not at all. Roughly1/eof the data is left out of any member, which is where an ensemble’s spread comes from.This exists because
vmapalone does not give you an ensemble. Batch Kohonen replaces each prototype outright with a mean of the data, so a prototype survives only through which datum it wins; members that agree on their assignments stay merged for every later epoch, and perturbing a shared initialization converges to bit-identical members. The diversity has to come from the data.Counts rather than gathered indices, because counts keep every array at shape
(N,): an ensemble is avmapover an(M, N)weight matrix with the data passed once, notMcopies of the data.- Parameters:
key (
Union[Key[Array, ''],UInt32[Array, '2'],UInt32[Array, '4']]) – Ajax.random.key(). Split it per ensemble member.n_obs (
int) – Number of observations,N. Static.
- Returns:
Counts summing to
n_obs.- Return type:
Array, shape (N,)
Examples
>>> import jax >>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> from phasecurvefit import som
>>> pos = {"x": jnp.linspace(0.0, 9.0, 50), "y": jnp.zeros(50)} >>> vel = {"x": jnp.ones(50), "y": jnp.zeros(50)} >>> w = som.bootstrap_weights(jax.random.key(0), 50) >>> w.shape, float(w.sum()) ((50,), 50.0)
An ensemble maps over the weights, not over copies of the data:
>>> keys = jax.random.split(jax.random.key(0), 4) >>> ws = jax.vmap(lambda k: som.bootstrap_weights(k, 50))(keys) >>> pq, pp = som.init_prototypes(pos, vel, n_prototypes=6) >>> metric = pcf.metrics.SpatialDistanceMetric() >>> fq = jax.vmap(lambda w: som.fit(pq, pp, pos, vel, metric=metric, weights=w))( ... ws ... ).prototype_positions >>> fq["x"].shape (4, 6)
- phasecurvefit.som.bmu_distance(metric: AbstractDistanceMetric, metric_scale: float | Float[Array, ''], positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], proto_positions: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], proto_velocities: Mapping[str, Real[Array, 'N'] | Real[ndarray, 'N'] | Real[TypedNdArray, 'N']], /)#
Each datum’s phase-space distance to its own best-matching prototype.
The quantization error fit minimizes but never returns: a large value means a datum sits far from every prototype, whether because it is an outlier or because the lattice is too coarse to reach it.
Examples
>>> import jax.numpy as jnp >>> import phasecurvefit as pcf >>> from phasecurvefit import som
>>> pos = {"x": jnp.linspace(0.0, 9.0, 50), "y": jnp.zeros(50)} >>> vel = {"x": jnp.ones(50), "y": jnp.zeros(50)} >>> pq, pp = som.init_prototypes(pos, vel, n_prototypes=6) >>> result = som.fit( ... pq, pp, pos, vel, metric=pcf.metrics.SpatialDistanceMetric(), n_epochs=20 ... ) >>> d = som.bmu_distance( ... pcf.metrics.SpatialDistanceMetric(), ... 0.0, ... pos, ... vel, ... result.prototype_positions, ... result.prototype_velocities, ... ) >>> d.shape (50,) >>> bool(jnp.all(d >= 0)) True
- Parameters:
metric (
AbstractDistanceMetric)metric_scale (
float|Float[Array, ''])positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])proto_positions (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])proto_velocities (
Mapping[str,Union[Real[Array, 'N'],Real[ndarray, 'N'],Real[TypedNdArray, 'N']]])
- Return type:
Float[Array, 'N']
- class phasecurvefit.som.FitResult(prototype_positions, prototype_velocities, kept, responsibility)#
Bases:
NamedTupleTrained prototypes, and each datum’s membership of the curve.
- Variables:
prototype_velocities (prototype_positions,) – Trained prototypes, shape
(K,)per component.kept (Bool[Array, " N"]) –
Truefor data the outlier mixture counts as members of the curve (responsibility >= 0.5). All-Truewhenoutlier_mixturewasNone.responsibility (Float[Array, " N"]) – Posterior probability that each datum came from the curve rather than the background, under the final prototypes. All ones when
outlier_mixturewasNone.
- Parameters:
-
kept:
Bool[Array, 'N']# Alias for field number 2
-
responsibility:
Float[Array, 'N']# Alias for field number 3
- count(value, /)#
Return number of occurrences of value.
- index(value, start=0, stop=9223372036854775807, /)#
Return first index of value.
Raises ValueError if the value is not present.
- class phasecurvefit.som.SOMMixture(*, background_density: float | None = None, background_inflate: float = 1.0)#
Bases:
objectMixture-model outlier rejection for
fit()andSOMOrderer.Each datum’s position comes either from the curve or from a flat background,
\[\mathcal{L}_n = \pi\, f(q_n) + (1 - \pi)\, \rho_{\mathrm{bg}} ,\]where \(f\) is a Gaussian tube of width \(s\) about the polyline through the prototype positions, open at its two ends. Every epoch computes the posterior membership \(r_n\) of each datum (the E-step), fits \(\pi\) and \(s\) by their closed-form M-steps, and counts each datum by \(\omega_n r_n\) in the prototype update. A weight \(\omega_n\) multiplies every sum and never enters \(r_n\). The self-organizing map explains the model.
The background needs room outside the curve. Samples that fill their own bounding box, as the pixels of a mask or an image do, are explained better by the background than by the curve, and EM ends with most of them called background. A fit whose member fraction \(\pi\) ends below 0.5 has fitted the box rather than the curve, so it keeps every datum, as without the mixture.
- Variables:
background_density (float | None) – \(\rho_{\mathrm{bg}}\), in inverse position units to the power
D.None(default) uses the reciprocal volume of the positions’ bounding box (uniform_background_density()).background_inflate (float) – Scales each axis of that bounding box when
background_densityisNone. Raise it when the data do not fill the field.
- Parameters:
Examples
>>> from phasecurvefit import som >>> som.SOMMixture().background_density is None True
Neighbour Backends#
Exact k-nearest-neighbour backends for
MSTOrderer (neighbors=).
Choosing a backend. SciPy is eager-only: it raises TypeError
inside jit, vmap or grad, including on arrays a jitted function captures
rather than takes as arguments. Under those transforms use
BucketKDTree (or BruteForce/JaxKD). MSTOrderer’s default
(neighbors=None) makes that choice per call: SciPy for concrete inputs,
BucketKDTree when traced.
BucketKDTree and BruteForce wrap
jaxknn’s knn and brute_knn. The
kd-tree buys traceability, not CPU speed. Compiled under jit, it is
slower than eager SciPy, and it compiles once per input shape. Measured on
an Apple M2 Pro (10 cores, under load, so treat these as rough):
n |
|
kNN (k=10): jit kd-tree / SciPy |
|
|---|---|---|---|
~2,000 |
~8–9 s |
~3× slower |
~2× slower |
10,000–100,000 |
~11–13 s |
~6.5–8.5× slower |
~1.6–2.8× slower (20,000–100,000) |
1,000,000 |
~27 s |
~6× slower |
not measured |
SciPy queries with every core (workers=-1); the kd-tree query is only
partly parallel on CPU. GPU was not measured.
- class phasecurvefit.neighbors.AbstractNeighborSearch#
Bases:
ReprMixin,ModuleAn exact k-nearest-neighbour backend.
knn(points, k)returns, for every point, its k nearest other points (self excluded by index).knn(points, k, queries=q)returns the k nearest points to each query. Both give(indices, distances): Euclidean distances, rows sorted ascending; a missing neighbour (fewer than k candidates) is indexlen(points)with distanceinf. Equidistant neighbours:BucketKDTreeandBruteForcetake the lower index (identically eager and under jit; forBucketKDTreewith indices below 2**24, beyond which its overflow tiers may order such ties differently, distances unaffected);JaxKDandSciPyfollow their library’s order.
- class phasecurvefit.neighbors.BucketKDTree(leaf_size: int = 16, frontier: int = 16)#
Bases:
AbstractNeighborSearchJAX-native exact kd-tree (
jaxknn.knn). Traceable under jit/vmap/grad.MSTOrderer’s default when its inputs are traced.SciPyis eager-only, so under jit/vmap/grad this (orBruteForce/JaxKD) is the choice; eagerly,SciPyis faster and compiles nothing, which is why the default uses it there.Eager calls pad
nto a size bucket ({2**j, 1.5 * 2**j}) with far rows, so differing stream lengths share compiled code (each new bucket compiles once: seconds, ~9 s at n = 100k, k = 8); underjitthe caller’s shapes are used as-is.Tuning, which matters only where
SciPycannot run (traced calls):Large
k(>= 32): setfrontierneark; atk = 32,frontier=32measured 3-15% faster than the default 16.High dimension (
d >= 6): every query overflows the default frontier, and the tree is ~30-50x slower thanSciPy;leaf_size=32measured ~1.45x faster. Eagerly, preferSciPy.
- class phasecurvefit.neighbors.BruteForce(chunk: int = 1024)#
Bases:
AbstractNeighborSearchExact brute force (
jaxknn.brute_knn),chunkqueries at a time.Traceable.
- Parameters:
chunk (
int)
- class phasecurvefit.neighbors.JaxKD#
Bases:
AbstractNeighborSearchThe optional
jaxkdpackage.Traceable, but pathological on data with scattered interlopers (minutes at n=100k).
- class phasecurvefit.neighbors.SciPy(workers: int = -1)#
Bases:
AbstractNeighborSearchscipy’s
cKDTree: fastest on CPU, but host-only (raises on traced inputs).workersis scipy’s thread count: -1 (default) uses every core.- Parameters:
workers (
int)