oarust 0.20.0

GPU-first semantic computing runtime written in Rust
Documentation
//! Mergeable weighted-mean state behind loss and regression reductions.

use crate::{Error, Result};

/// Additive numerator/denominator state for one weighted mean.
///
/// The result is `sum / weight` — never the mean of per-batch means, which
/// disagrees for uneven final batches. An empty denominator reports NaN
/// rather than zero, so merges with empty state are exact no-ops.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WeightedMean {
	sum: f64,
	weight: f64,
}

impl WeightedMean {
	/// Construct empty state.
	#[inline]
	#[must_use]
	pub fn new() -> Self {
		Self::default()
	}

	/// Add one batch's contribution.
	///
	/// # Errors
	///
	/// Returns an error when `weight` is negative or non-finite.
	pub fn update(&mut self, sum: f64, weight: f64) -> Result<()> {
		if weight < 0.0 || !weight.is_finite() {
			return Err(Error::invalid_argument(
				"weighted metric contributions require a finite non-negative weight",
			));
		}
		self.sum += sum;
		self.weight += weight;
		Ok(())
	}

	/// Merge another instance's accumulated state.
	pub fn merge(&mut self, other: &Self) {
		self.sum += other.sum;
		self.weight += other.weight;
	}

	/// Return `sum / weight`, or NaN when no weight has been observed.
	#[must_use]
	pub fn result(&self) -> f64 {
		if self.weight == 0.0 {
			f64::NAN
		} else {
			self.sum / self.weight
		}
	}

	/// Return the accumulated numerator.
	#[must_use]
	pub const fn sum(&self) -> f64 {
		self.sum
	}

	/// Return the accumulated denominator weight.
	#[must_use]
	pub const fn weight(&self) -> f64 {
		self.weight
	}

	/// Drop all accumulated state.
	pub fn reset(&mut self) {
		self.sum = 0.0;
		self.weight = 0.0;
	}
}