physics_in_parallel 4.2.0-alpha

High-performance infrastructure for numerical simulations in physics
Documentation
//! Exact-composition placement and explicit largest-remainder apportionment.

use crate::rng::{IndexedRng, ResolvedRng, RngError, domains};
use std::{error::Error, fmt};

/// Invalid composition, destination, or indexed random method.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum CountPlacementError {
    CountOverflow,
    LengthMismatch { expected: usize, actual: usize },
    InvalidFrequencies,
    FrequencyResolution,
    Rng(RngError),
}
impl fmt::Display for CountPlacementError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CountOverflow => write!(f, "composition count total overflows usize"),
            Self::LengthMismatch { expected, actual } => write!(
                f,
                "composition requires {expected} sites, destination has {actual}"
            ),
            Self::InvalidFrequencies => write!(
                f,
                "frequencies must be finite, nonnegative, nonempty, and have positive total"
            ),
            Self::FrequencyResolution => write!(
                f,
                "requested counts exceed reliable f64 apportionment resolution"
            ),
            Self::Rng(e) => e.fmt(f),
        }
    }
}
impl Error for CountPlacementError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        if let Self::Rng(e) = self {
            Some(e)
        } else {
            None
        }
    }
}

/// Fills exactly the supplied multiplicities and applies unbiased Fisher-Yates.
///
/// Validates the checked total, destination length, and indexed RNG before
/// mutation. Input order and step are part of the reproducibility contract.
/// Equal values may occur in multiple entries; their multiplicities add.
/// Empty counts are valid for an empty destination. The shuffle is sequential
/// and independent of thread count, with no additional placement-sized buffer.
pub fn fill_with_counts<T: Clone>(
    values: &mut [T],
    counts: &[(T, usize)],
    rng: ResolvedRng,
    step: u64,
) -> Result<ResolvedRng, CountPlacementError> {
    let total = counts
        .iter()
        .try_fold(0_usize, |sum, (_, count)| sum.checked_add(*count))
        .ok_or(CountPlacementError::CountOverflow)?;
    if total != values.len() {
        return Err(CountPlacementError::LengthMismatch {
            expected: total,
            actual: values.len(),
        });
    }
    IndexedRng::new(rng).map_err(CountPlacementError::Rng)?;
    let mut offset = 0;
    for (value, count) in counts {
        values[offset..offset + count].fill(value.clone());
        offset += count;
    }
    super::shuffle::shuffle_slice_indexed_at(values, rng, step, domains::COUNT_PLACEMENT)
        .map_err(CountPlacementError::Rng)
}

/// Normalizes frequencies and allocates a total by largest remainders.
///
/// Equal remainders favor the earlier input entry. Zero frequencies receive no
/// sites. Apportionment uses f64, so totals above 2^53 are rejected; explicit
/// integer counts have no such restriction. This helper does not draw randomness.
pub fn counts_from_frequencies(
    frequencies: &[f64],
    total: usize,
) -> Result<Vec<usize>, CountPlacementError> {
    if frequencies.is_empty() || frequencies.iter().any(|w| !w.is_finite() || *w < 0.0) {
        return Err(CountPlacementError::InvalidFrequencies);
    }
    let maximum = frequencies.iter().copied().fold(0.0_f64, f64::max);
    if maximum == 0.0 {
        return Err(CountPlacementError::InvalidFrequencies);
    }
    if total as u128 > 1_u128 << 53 {
        return Err(CountPlacementError::FrequencyResolution);
    }
    let sum: f64 = frequencies.iter().map(|w| w / maximum).sum();
    let mut counts = Vec::with_capacity(frequencies.len());
    let mut remainders = Vec::with_capacity(frequencies.len());
    for (index, weight) in frequencies.iter().enumerate() {
        let exact = (weight / maximum) / sum * total as f64;
        counts.push(exact.floor() as usize);
        if *weight > 0.0 {
            remainders.push((index, exact.fract()));
        }
    }
    let assigned: u128 = counts.iter().map(|n| *n as u128).sum();
    if assigned > total as u128 {
        return Err(CountPlacementError::FrequencyResolution);
    }
    let remaining = total - assigned as usize;
    if remaining > frequencies.iter().filter(|w| **w > 0.0).count() {
        return Err(CountPlacementError::FrequencyResolution);
    }
    remainders.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
    for &(index, _) in remainders.iter().take(remaining) {
        counts[index] += 1;
    }
    Ok(counts)
}