# Pairing and exact composition
PiP 4.2.0-alpha exposes `space::PAIRING_MAPPING_VERSION = "2"`. The indexed RNG
word mapping remains version 1. Retain the crate version, complete pairing
configuration, RNG method/version, sweep, and global pair indices for replay.
## Continuous radii and discrete moves
Power-law radii have density proportional to r^(-1-mu) on [c,l); mu = 0 is
log-uniform. UniformDistance samples radii uniformly, not sites or ball volume.
Floating-point inversion can reach an endpoint through rounding.
Radii measure **lattice sites**. Physical geometry spacings do not rescale them.
Site-coordinate isotropy is not physical isotropy when axis spacings differ.
Rank one truncates toward zero. Thus
`P(|displacement|=k) = integral of f(r) over [k,k+1) intersected with [c,l)`.
For a nonempty overlap [a,b), the positive-mu mass is
`(a^(-mu)-b^(-mu))/(c^(-mu)-l^(-mu))`; for mu = 0 it is
`ln(b/a)/ln(l/c)`. Nonzero magnitudes split equally between signs.
The original positive-mu inversion and indexed coordinates are retained when
inverse powers are representable and distinct. Previously degenerate inverse
powers use a finite log-space fallback.
Higher ranks round to nearest integer, with halfway cases away from zero.
When c >= 1, a zero displacement redraws both direction and radius, retaining
the source and pair index and using new draw coordinates. For c < 1, zero
moves are allowed. Very high ranks concentrated near radius one may require
many redraws; there is no constant-time guarantee.
This law integrates the continuous distribution over rounding cells and
conditions on nonzero displacement where applicable. It is **not** a pointwise
the absolute length error is at most sqrt(rank)/2. Symmetry relates sign changes
and axis permutations, not axial and diagonal vectors of different lengths.
## Buffered and on-demand pairs
IndependentUniform samples both endpoints with replacement; self-pairs are valid.
Kernel rules select an origin or uniform source and a raw displacement.
Coordinate buffers satisfy `target = source + displacement`.
PairGenerator::new assumes no boundary policy. sources_flat() is always
available; targets_flat() returns None without geometry. Use with_geometry for
boundary-resolved target indices. source(i) and target(i) borrow raw coordinate
rows and panic for out-of-range indices. source_values(), displacement_values(),
and target_values() borrow dense row-major storage without backend inspection.
Buffers start at zero; generated_sweep() identifies a sampled batch.
A nonzero displacement may still resolve to its source after wrapping, reflection,
or clamping. Rejecting those self-pairs would define a different distribution.
```rust
use physics_in_parallel::prelude::basic::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let geometry = SquareLatticeGeometry::periodic(&[100, 100])?;
let rng = ResolvedRng::new(17, RngMethod::IndexedSplitMix64);
let method = PairingMethod::Mixture { components: vec![
(PairingMethod::Kernel {
kernel: KernelType::NearestNeighbor { dimension: 2 },
sources: SourceMode::RandomUniform,
}, 0.9),
(PairingMethod::IndependentUniform, 0.1),
] };
let sampler = PairSampler::with_geometry(geometry, method, rng)?;
let (source, target) = sampler.pair_at(9, 123)?;
assert!(source < 10_000 && target < 10_000);
Ok(())
}
```
PairSampler stores geometry and validated configuration, with no sweep-sized
buffers or per-pair allocations. pair_at returns flat endpoints; par_pairs is an
indexed Rayon iterator. pair_into writes raw coordinates to caller-owned rows,
including for shape-only construction; wrong row lengths fail before mutation.
Buffered storage holds 3 * rank * pair_count signed coordinates, pair_count
source indices, and optionally pair_count target indices. In rank one on a
64-bit platform, ten million pairs require about 320 MB for shape-only buffers
or 400 MB with resolved targets, excluding small configuration metadata.
On-demand generation has no storage proportional to pair_count.
Buffered and on-demand generation share the same implementation. Output is
bit-identical for the same configuration, sweep, global index, and platform,
independent of worker count or scheduling. Arbitrary CPUs and floating-point
libraries are not promised bitwise equivalence.
Mixtures choose complete child rules using a separate indexed domain. Weights
must be finite and nonnegative with a finite positive total. Zero-weight children
are never chosen, but all children are validated. Nested choices use preorder
node indices in the component coordinate; nesting is limited to 32 levels.
Thresholds use f64 precision. Component order and nesting affect replay.
PairingMethod is now Clone rather than Copy: clone retained configurations.
## Optional periodic bounds
KernelType::power_law_for(geometry,mu,c,l) and uniform_distance_for(geometry,c,l)
use site-unit defaults c = 1 and l = half the shortest axis's site count.
They require periodic geometry and 1 <= c < l <= shortest_axis/2. Small
lattices may have no admissible defaults. These optional inscribed cutoffs do
not restrict ordinary constructors, which still allow longer wrapped jumps.
## Exact composition
```rust
use physics_in_parallel::prelude::basic::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let rng = ResolvedRng::new(17, RngMethod::IndexedSplitMix64);
let mut sites = vec![0_u8; 1000];
fill_with_counts(&mut sites, &[(0, 950), (1, 50)], rng, 7)?;
assert_eq!(sites.iter().filter(|&&v| v == 1).count(), 50);
Ok(())
}
```
fill_with_counts validates checked integer totals, length, and indexed RNG
before mutation, then performs an unbiased Fisher-Yates shuffle without an
extra placement-sized array. Empty counts are valid for an empty destination.
Input order, seed, and step identify replay; thread count does not affect it.
sampling::counts_from_frequencies is a separate largest-remainder helper.
It normalizes finite nonnegative frequencies with positive total weight and
breaks equal remainders by input order. Zero frequencies receive no sites.
It rejects totals above 2^53 and unreliable floating-point apportionments;
explicit integer counts have no 2^53 restriction. Exact composition and
independent site draws are different initial ensembles.
## Named RNG domains
rng::domain("my_crate.module.purpose.v1") is stable FNV-1a-64 over exact UTF-8
bytes, without normalization or case folding. It is not cryptographic or
collision-free. rng::domains::RESERVED publishes PiP's numeric reservations.
Existing identities remain unchanged. Check custom domains against PiP's
registry and each other; this cannot rule out every possible hash collision.