use super::super::{
kernel::{BuiltinKernel, KernelType, try_create_builtin_kernel},
representation::SquareLatticeGeometry,
};
use super::{PairGenerationError as E, PairingMethod, SourceMode};
use crate::math::{TensorError, tensor::rank_n::layout::RowMajorLayout};
use crate::rng::{IndexedRng, ResolvedRng, domains as d};
use rayon::prelude::*;
#[derive(Clone, Debug)]
pub struct PairSampler {
pub(super) layout: RowMajorLayout,
pub(super) geometry: Option<SquareLatticeGeometry>,
method: PairingMethod,
prepared: PreparedMethod,
key: IndexedRng,
}
impl PairSampler {
pub fn new(shape: &[usize], method: PairingMethod, rng: ResolvedRng) -> Result<Self, E> {
let key = IndexedRng::new(rng).map_err(E::Rng)?;
let layout = RowMajorLayout::try_new(shape).map_err(|error| match error {
TensorError::InvalidShape { shape } if shape.is_empty() => E::EmptyShape,
TensorError::InvalidShape { shape } => E::ZeroAxis {
axis: shape.iter().position(|n| *n == 0).expect("zero axis"),
},
_ => E::SiteCountOverflow,
})?;
let prepared = prepare(&method, shape, 0, &mut 0)?;
Ok(Self {
layout,
geometry: None,
method,
prepared,
key,
})
}
pub fn with_geometry(
geometry: SquareLatticeGeometry,
method: PairingMethod,
rng: ResolvedRng,
) -> Result<Self, E> {
let mut sampler = Self::new(geometry.shape(), method, rng)?;
sampler.geometry = Some(geometry);
Ok(sampler)
}
pub fn shape(&self) -> &[usize] {
self.layout.shape()
}
pub fn rank(&self) -> usize {
self.shape().len()
}
pub fn method(&self) -> &PairingMethod {
&self.method
}
pub fn resolved_rng(&self) -> ResolvedRng {
self.key.resolved_rng()
}
pub fn pair_at(&self, sweep: u64, index: u64) -> Result<(usize, usize), E> {
let geometry = self.geometry.as_ref().ok_or(E::MissingGeometry)?;
let pair = self.sample(sweep, index);
let target = self
.layout
.strides()
.iter()
.zip(self.shape())
.enumerate()
.map(|(axis, (&stride, &extent))| {
geometry
.boundary()
.normalize(self.raw_target(&pair, axis), extent)
* stride
})
.sum();
Ok((pair.source, target))
}
pub fn par_pairs(
&self,
sweep: u64,
count: usize,
) -> Result<impl IndexedParallelIterator<Item = (usize, usize)> + '_, E> {
if self.geometry.is_none() {
return Err(E::MissingGeometry);
}
Ok((0..count)
.into_par_iter()
.with_min_len(crate::threading::parallel_chunk_len(count).unwrap_or(1))
.map(move |i| {
self.pair_at(sweep, i as u64)
.expect("geometry was validated")
}))
}
pub fn pair_into(
&self,
sweep: u64,
index: u64,
source: &mut [isize],
displacement: &mut [isize],
target: &mut [isize],
) -> Result<(), E> {
for actual in [source.len(), displacement.len(), target.len()] {
if actual != self.rank() {
return Err(E::OutputRankMismatch {
expected: self.rank(),
actual,
});
}
}
self.fill_unchecked(sweep, index, source, displacement, target);
Ok(())
}
pub(super) fn fill_unchecked(
&self,
sweep: u64,
index: u64,
source: &mut [isize],
displacement: &mut [isize],
target: &mut [isize],
) -> usize {
let pair = self.sample(sweep, index);
for axis in 0..self.rank() {
source[axis] = self.coordinate(pair.source, axis);
target[axis] = self.raw_target(&pair, axis);
displacement[axis] = target[axis] - source[axis];
}
pair.source
}
fn coordinate(&self, site: usize, axis: usize) -> isize {
((site / self.layout.strides()[axis]) % self.shape()[axis]) as isize
}
fn raw_target(&self, pair: &SampledPair, axis: usize) -> isize {
match &pair.jump {
Jump::Independent { target } => self.coordinate(*target, axis),
_ => self.coordinate(pair.source, axis) + pair.jump.component(axis, self.rank()),
}
}
fn sample(&self, sweep: u64, item: u64) -> SampledPair {
let mut method = &self.prepared;
while let PreparedMethod::Mixture { node, components } = method {
let unit = self.key.unit_f64(sweep, d::PAIRING_MIXTURE, item, *node, 0);
let selected = components
.partition_point(|(upper, _)| *upper <= unit)
.min(components.len() - 1);
method = &components[selected].1;
}
match method {
PreparedMethod::Independent => SampledPair {
source: self
.key
.uniform_index(
sweep,
d::INDEPENDENT_SOURCE_SITE,
item,
0,
self.layout.size(),
)
.unwrap(),
jump: Jump::Independent {
target: self
.key
.uniform_index(
sweep,
d::INDEPENDENT_TARGET_SITE,
item,
0,
self.layout.size(),
)
.unwrap(),
},
},
PreparedMethod::Kernel {
kernel,
sources,
kind,
} => {
let source = match sources {
SourceMode::Origin => 0,
SourceMode::RandomUniform => self
.key
.uniform_index(sweep, d::SOURCE_COORDINATE, item, 0, self.layout.size())
.unwrap(),
};
let jump = match kind {
KernelType::NearestNeighbor { dimension } => {
let code = self
.key
.uniform_index(sweep, d::HAAR_COMPONENT, item, 0, 2 * dimension)
.unwrap();
Jump::Nearest {
axis: code / 2,
sign: if code.is_multiple_of(2) { 1 } else { -1 },
}
}
KernelType::PowerLaw { c, .. } | KernelType::UniformDistance { c, .. } => {
let mut attempt = 0;
loop {
let length = kernel.sample_unit(self.key.unit_f64(
sweep,
d::KERNEL_SAMPLE,
item,
0,
attempt,
));
let direction =
Direction::sample(self.key, sweep, item, self.rank(), attempt);
let jump = Jump::Radial { length, direction };
if self.rank() == 1
|| *c < 1.0
|| (0..self.rank())
.any(|axis| jump.component(axis, self.rank()) != 0)
{
break jump;
}
attempt += 1;
}
}
};
SampledPair { source, jump }
}
PreparedMethod::Mixture { .. } => unreachable!("mixtures resolved above"),
}
}
}
#[derive(Clone, Debug)]
enum PreparedMethod {
Independent,
Kernel {
kernel: BuiltinKernel,
sources: SourceMode,
kind: KernelType,
},
Mixture {
node: u64,
components: Vec<(f64, PreparedMethod)>,
},
}
fn prepare(
method: &PairingMethod,
shape: &[usize],
depth: usize,
next_node: &mut u64,
) -> Result<PreparedMethod, E> {
if depth > 32 {
return Err(E::MixtureTooDeep);
}
match method {
PairingMethod::IndependentUniform => Ok(PreparedMethod::Independent),
PairingMethod::Kernel { kernel, sources } => {
let builtin = try_create_builtin_kernel(*kernel).map_err(E::Kernel)?;
let radius = match kernel {
KernelType::NearestNeighbor { dimension } => {
if *dimension != shape.len() {
return Err(E::KernelRankMismatch {
kernel_dimension: *dimension,
rank: shape.len(),
});
}
1.0
}
KernelType::PowerLaw { l, .. } | KernelType::UniformDistance { l, .. } => *l,
};
let radius = if matches!(kernel, KernelType::NearestNeighbor { .. }) {
radius
} else {
radius
.max(builtin.sample_unit(1.0 - f64::EPSILON / 2.0))
.next_up()
};
let source_max = if *sources == SourceMode::Origin {
0
} else {
*shape.iter().max().unwrap() - 1
};
if (radius.ceil() as u128)
.checked_add(source_max as u128)
.is_none_or(|end| end > isize::MAX as u128)
{
return Err(E::CoordinateOverflow);
}
Ok(PreparedMethod::Kernel {
kernel: builtin,
sources: *sources,
kind: *kernel,
})
}
PairingMethod::Mixture { components } => {
let total: f64 = components.iter().map(|(_, w)| *w).sum();
if components.is_empty()
|| !total.is_finite()
|| total <= 0.0
|| components.iter().any(|(_, w)| !w.is_finite() || *w < 0.0)
{
return Err(E::InvalidMixture);
}
let node = *next_node;
*next_node += 1;
let mut cumulative = 0.0;
let mut prepared = Vec::new();
for (method, weight) in components {
let child = prepare(method, shape, depth + 1, next_node)?;
if *weight > 0.0 {
cumulative += weight / total;
prepared.push((cumulative, child));
}
}
prepared.last_mut().expect("positive total").0 = 1.0;
Ok(PreparedMethod::Mixture {
node,
components: prepared,
})
}
}
}
struct SampledPair {
source: usize,
jump: Jump,
}
enum Jump {
Independent { target: usize },
Nearest { axis: usize, sign: isize },
Radial { length: f64, direction: Direction },
}
impl Jump {
fn component(&self, axis: usize, rank: usize) -> isize {
match self {
Self::Nearest {
axis: selected,
sign,
} => {
if axis == *selected {
*sign
} else {
0
}
}
Self::Radial { length, direction } => {
let value = direction.component(axis) * length;
if rank == 1 {
value as isize
} else {
value.round() as isize
}
}
Self::Independent { .. } => unreachable!("independent target is already a site"),
}
}
}
enum Direction {
Sign(f64),
Plane(f64, f64),
Sphere(f64, f64, f64),
Gaussian {
key: IndexedRng,
sweep: u64,
item: u64,
attempt: u64,
norm: f64,
},
}
impl Direction {
fn sample(key: IndexedRng, sweep: u64, item: u64, rank: usize, attempt: u64) -> Self {
match rank {
1 => Self::Sign(
if key
.uniform_index(sweep, d::HAAR_COMPONENT, item, 0, 2)
.unwrap()
== 0
{
-1.0
} else {
1.0
},
),
2 => {
let angle = std::f64::consts::TAU
* key.unit_f64(sweep, d::HAAR_COMPONENT, item, 0, attempt);
let (sin, cos) = angle.sin_cos();
Self::Plane(cos, sin)
}
3 => {
let z = 2.0 * key.unit_f64(sweep, d::HAAR_COMPONENT, item, 0, attempt) - 1.0;
let phi = std::f64::consts::TAU
* key.unit_f64(sweep, d::HAAR_COMPONENT, item, 1, attempt);
let (sin, cos) = phi.sin_cos();
let radius = (1.0 - z * z).sqrt();
Self::Sphere(radius * cos, radius * sin, z)
}
_ => {
let norm = (0..rank)
.map(|axis| {
let value = normal(key, sweep, item, axis as u64, attempt);
value * value
})
.sum::<f64>()
.sqrt();
Self::Gaussian {
key,
sweep,
item,
attempt,
norm,
}
}
}
}
fn component(&self, axis: usize) -> f64 {
match self {
Self::Sign(x) => *x,
Self::Plane(x, y) => {
if axis == 0 {
*x
} else {
*y
}
}
Self::Sphere(x, y, z) => match axis {
0 => *x,
1 => *y,
_ => *z,
},
Self::Gaussian {
key,
sweep,
item,
attempt,
norm,
} => normal(*key, *sweep, *item, axis as u64, *attempt) / norm,
}
}
}
fn normal(key: IndexedRng, sweep: u64, item: u64, axis: u64, attempt: u64) -> f64 {
if attempt == 0 {
return key.standard_normal(sweep, d::HAAR_COMPONENT, item, axis);
}
let u1 = (((key.indexed_word(sweep, d::HAAR_COMPONENT, item, axis, attempt * 2) >> 11) as f64)
+ 0.5)
/ ((1_u64 << 53) as f64);
let u2 = key.unit_f64(sweep, d::HAAR_COMPONENT, item, axis, attempt * 2 + 1);
(-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
}