physics_in_parallel 4.2.0-alpha

High-performance infrastructure for numerical simulations in physics
Documentation
//! Indexed lattice pairs with reusable buffers or allocation-free random access.
//!
//! Radii are in lattice-site units. Rank one retains truncation toward zero;
//! higher ranks round to nearest integer, with halfway cases away from zero.
//! For lower bounds of at least one site, zero displacements are redrawn.
//! Raw targets satisfy `target = source + displacement`. Flat target indices
//! require explicit geometry. Boundaries can turn a nonzero move into a self-pair.

mod buffered;
mod sampler;
pub use buffered::PairGenerator;
pub use sampler::PairSampler;

use super::kernel::{KernelError, KernelType};
use crate::math::TensorRandError;
use crate::rng::RngError;
use serde::{Deserialize, Serialize};
use std::{error::Error, fmt};

/// Pairing algorithm identity, separate from the indexed RNG word mapping.
pub const PAIRING_MAPPING_VERSION: &str = "2";

/// Rule for selecting each kernel pair's source coordinate.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceMode {
    Origin,
    RandomUniform,
}

/// Complete source/target rule. Independent endpoints allow self-pairs.
///
/// Mixtures select a complete child rule per `(sweep, pair_index)`. Weights must
/// be finite and nonnegative with a finite positive total. Zero weights are
/// never selected. Nesting is limited to 32 levels.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum PairingMethod {
    IndependentUniform,
    Kernel {
        kernel: KernelType,
        sources: SourceMode,
    },
    Mixture {
        components: Vec<(PairingMethod, f64)>,
    },
}

/// Invalid pair configuration or random-access output request.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum PairGenerationError {
    EmptyShape,
    ZeroAxis {
        axis: usize,
    },
    ZeroPairs,
    SiteCountOverflow,
    PairBufferOverflow {
        num_pairs: usize,
        rank: usize,
    },
    KernelRankMismatch {
        kernel_dimension: usize,
        rank: usize,
    },
    CoordinateOverflow,
    MissingGeometry,
    OutputRankMismatch {
        expected: usize,
        actual: usize,
    },
    InvalidMixture,
    MixtureTooDeep,
    Kernel(KernelError),
    Rng(RngError),
    TensorRand(TensorRandError),
}

impl fmt::Display for PairGenerationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyShape => write!(f, "pair-generator shape must have at least one axis"),
            Self::ZeroAxis { axis } => {
                write!(f, "pair-generator shape axis {axis} must be nonzero")
            }
            Self::ZeroPairs => write!(f, "pair-generator pair count must be positive"),
            Self::SiteCountOverflow => write!(
                f,
                "pair-generator shape exceeds the signed site-index space"
            ),
            Self::PairBufferOverflow { num_pairs, rank } => write!(
                f,
                "pair-generator buffer shape {num_pairs}x{rank} exceeds the signed index space"
            ),
            Self::KernelRankMismatch {
                kernel_dimension,
                rank,
            } => write!(
                f,
                "nearest-neighbor kernel dimension {kernel_dimension} does not match lattice rank {rank}"
            ),
            Self::CoordinateOverflow => write!(
                f,
                "shape and kernel radius exceed the signed coordinate space"
            ),
            Self::MissingGeometry => {
                write!(f, "flat target indices require explicit lattice geometry")
            }
            Self::OutputRankMismatch { expected, actual } => write!(
                f,
                "pair output rank mismatch: expected {expected}, got {actual}"
            ),
            Self::InvalidMixture => write!(
                f,
                "mixture requires finite nonnegative weights and a finite positive total"
            ),
            Self::MixtureTooDeep => write!(f, "pairing mixture nesting exceeds 32 levels"),
            Self::Kernel(e) => e.fmt(f),
            Self::Rng(e) => e.fmt(f),
            Self::TensorRand(e) => e.fmt(f),
        }
    }
}
impl Error for PairGenerationError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Kernel(e) => Some(e),
            Self::Rng(e) => Some(e),
            Self::TensorRand(e) => Some(e),
            _ => None,
        }
    }
}

impl From<KernelError> for PairGenerationError {
    fn from(error: KernelError) -> Self {
        Self::Kernel(error)
    }
}
impl From<RngError> for PairGenerationError {
    fn from(error: RngError) -> Self {
        Self::Rng(error)
    }
}
impl From<TensorRandError> for PairGenerationError {
    fn from(error: TensorRandError) -> Self {
        Self::TensorRand(error)
    }
}