oarust 0.20.0

GPU-first semantic computing runtime written in Rust
Documentation
//! Mergeable fixed-bin streaming approximations for binary ROC-AUC and PR-AUC.

use crate::{DType, Error, Matrix, Result};

/// Fixed-bin histogram accumulator for streaming approximate binary ROC-AUC and PR-AUC.
///
/// Exact ROC-AUC and PR-AUC require retaining and sorting every score on the host
/// (`oa::ml::metric::roc_auc` and `oa::ml::metric::pr_auc`). When evaluation runs
/// over arbitrarily partitioned or streaming batches without keeping all scores in
/// memory, `StreamingBinaryCurves` quantizes scores into `num_bins` uniform bins
/// over `[min_score, max_score]` and records its exact threshold edges via
/// [`StreamingBinaryCurves::thresholds`].
///
/// The accumulated state is pure additive per-bin `(positive, negative)` counts, so
/// [`StreamingBinaryCurves::merge`] produces bitwise identical curves regardless of
/// batch partitioning. Scores outside `[min_score, max_score]` clamp to the nearest
/// boundary bin.
#[derive(Clone, Debug, PartialEq)]
pub struct StreamingBinaryCurves {
	num_bins: usize,
	min_score: f64,
	max_score: f64,
	positive_bins: Vec<u64>,
	negative_bins: Vec<u64>,
}

impl StreamingBinaryCurves {
	/// Construct an empty streaming binary curve accumulator over `[0.0, 1.0]`.
	///
	/// # Errors
	///
	/// Returns an error when `num_bins == 0`.
	pub fn new(num_bins: usize) -> Result<Self> {
		Self::with_range(num_bins, 0.0, 1.0)
	}

	/// Construct an empty streaming binary curve accumulator over `[min_score, max_score]`.
	///
	/// # Errors
	///
	/// Returns an error when `num_bins == 0`, either bound is non-finite, or
	/// `max_score <= min_score`.
	pub fn with_range(num_bins: usize, min_score: f64, max_score: f64) -> Result<Self> {
		if num_bins == 0 {
			return Err(Error::invalid_argument(
				"streaming binary curves require at least one bin",
			));
		}
		if !min_score.is_finite() || !max_score.is_finite() || max_score <= min_score {
			return Err(Error::invalid_argument(format!(
				"streaming binary curves require finite min_score < max_score; found [{min_score}, {max_score}]"
			)));
		}
		Ok(Self {
			num_bins,
			min_score,
			max_score,
			positive_bins: vec![0; num_bins],
			negative_bins: vec![0; num_bins],
		})
	}

	/// Return the number of histogram bins.
	#[must_use]
	pub const fn num_bins(&self) -> usize {
		self.num_bins
	}

	/// Return the inclusive lower score bound.
	#[must_use]
	pub const fn min_score(&self) -> f64 {
		self.min_score
	}

	/// Return the inclusive upper score bound.
	#[must_use]
	pub const fn max_score(&self) -> f64 {
		self.max_score
	}

	/// Return the `num_bins + 1` monotonically ascending bin-edge thresholds.
	#[must_use]
	pub fn thresholds(&self) -> Vec<f64> {
		let span = self.max_score - self.min_score;
		let mut edges = Vec::with_capacity(self.num_bins + 1);
		for index in 0..self.num_bins {
			edges.push(self.min_score + span * (index as f64 / self.num_bins as f64));
		}
		edges.push(self.max_score);
		edges
	}

	/// Return the total number of observed positive samples (`label == 1`).
	#[must_use]
	pub fn positives(&self) -> u64 {
		self.positive_bins.iter().copied().sum()
	}

	/// Return the total number of observed negative samples (`label == 0`).
	#[must_use]
	pub fn negatives(&self) -> u64 {
		self.negative_bins.iter().copied().sum()
	}

	/// Return the total number of observed samples.
	#[must_use]
	pub fn samples(&self) -> u64 {
		self.positives().saturating_add(self.negatives())
	}

	/// Accumulate one host batch of positive-class scores and binary (`0`/`1`) labels.
	///
	/// # Errors
	///
	/// Returns an error when slice lengths differ, any score is non-finite, or any
	/// label is outside `{0, 1}`. Validation runs before mutating state.
	pub fn update(&mut self, scores: &[f32], labels: &[u32]) -> Result<()> {
		if scores.len() != labels.len() {
			return Err(Error::invalid_argument(format!(
				"streaming binary curves require equal score and label counts; found {} and {}",
				scores.len(),
				labels.len()
			)));
		}
		for (&score, &label) in scores.iter().zip(labels) {
			if !score.is_finite() {
				return Err(Error::invalid_argument(
					"streaming binary curves require finite scores",
				));
			}
			if label > 1 {
				return Err(Error::invalid_argument(format!(
					"streaming binary curves require binary 0/1 labels; found {label}"
				)));
			}
		}
		let span = self.max_score - self.min_score;
		let bins_f64 = self.num_bins as f64;
		let last_bin = self.num_bins - 1;
		for (&score, &label) in scores.iter().zip(labels) {
			let clamped = f64::from(score).clamp(self.min_score, self.max_score);
			let normalized = (clamped - self.min_score) / span;
			let bin = ((normalized * bins_f64).floor() as usize).min(last_bin);
			if label == 1 {
				self.positive_bins[bin] = self.positive_bins[bin].saturating_add(1);
			} else {
				self.negative_bins[bin] = self.negative_bins[bin].saturating_add(1);
			}
		}
		Ok(())
	}

	/// Read back one evaluation batch of device scores and binary labels and accumulate.
	///
	/// # Errors
	///
	/// Returns an error when `scores` is not F32, shapes/counts disagree, labels are
	/// not integer `0`/`1`, any score is non-finite, or readback fails.
	pub fn update_device(&mut self, scores: &Matrix, labels: &Matrix) -> Result<()> {
		if scores.dtype() != DType::F32 {
			return Err(Error::invalid_argument(format!(
				"streaming binary curves require F32 scores; found {}",
				scores.dtype().token()
			)));
		}
		if scores.num_elements() != labels.num_elements() {
			return Err(Error::invalid_argument(format!(
				"streaming binary curves received {} scores for {} labels",
				scores.num_elements(),
				labels.num_elements()
			)));
		}
		if !matches!(labels.dtype(), DType::U8 | DType::U32 | DType::I32) {
			return Err(Error::invalid_argument(format!(
				"streaming binary curves require U8, U32, or I32 labels; found {}",
				labels.dtype().token()
			)));
		}
		let score_values = scores.read_f32()?;
		let label_values: Vec<u32> = match labels.dtype() {
			DType::U8 => labels.read::<u8>()?.into_iter().map(u32::from).collect(),
			DType::U32 => labels.read::<u32>()?,
			DType::I32 => {
				let raw = labels.read::<i32>()?;
				let mut converted = Vec::with_capacity(raw.len());
				for value in raw {
					if !(0..=1).contains(&value) {
						return Err(Error::invalid_argument(format!(
							"streaming binary curves require binary 0/1 labels; found {value}"
						)));
					}
					converted.push(value as u32);
				}
				converted
			}
			_ => unreachable!(),
		};
		self.update(&score_values, &label_values)
	}

	/// Merge another accumulator's bin counts elementwise.
	///
	/// # Errors
	///
	/// Returns an error when the bin count or score range differs.
	pub fn merge(&mut self, other: &Self) -> Result<()> {
		if self.num_bins != other.num_bins
			|| self.min_score.to_bits() != other.min_score.to_bits()
			|| self.max_score.to_bits() != other.max_score.to_bits()
		{
			return Err(Error::invalid_argument(format!(
				"cannot merge streaming binary curves ({} bins on [{}, {}]) with ({} bins on [{}, {}])",
				self.num_bins,
				self.min_score,
				self.max_score,
				other.num_bins,
				other.min_score,
				other.max_score
			)));
		}
		for (dst, &src) in self.positive_bins.iter_mut().zip(&other.positive_bins) {
			*dst = dst.saturating_add(src);
		}
		for (dst, &src) in self.negative_bins.iter_mut().zip(&other.negative_bins) {
			*dst = dst.saturating_add(src);
		}
		Ok(())
	}

	/// Approximate ROC-AUC integrated over the recorded descending bin thresholds.
	///
	/// Returns `f64::NAN` when either the positive or negative class is absent.
	#[must_use]
	pub fn roc_auc(&self) -> f64 {
		let total_pos = self.positives();
		let total_neg = self.negatives();
		if total_pos == 0 || total_neg == 0 {
			return f64::NAN;
		}
		let total_pos = total_pos as f64;
		let total_neg = total_neg as f64;
		let mut tp = 0.0_f64;
		let mut fp = 0.0_f64;
		let mut prev_tpr = 0.0_f64;
		let mut prev_fpr = 0.0_f64;
		let mut auc = 0.0_f64;
		for bin in (0..self.num_bins).rev() {
			let pos = self.positive_bins[bin];
			let neg = self.negative_bins[bin];
			if pos == 0 && neg == 0 {
				continue;
			}
			tp += pos as f64;
			fp += neg as f64;
			let tpr = tp / total_pos;
			let fpr = fp / total_neg;
			auc += (fpr - prev_fpr) * (tpr + prev_tpr) * 0.5;
			prev_tpr = tpr;
			prev_fpr = fpr;
		}
		auc
	}

	/// Approximate PR-AUC (step-wise average precision) over descending bin thresholds.
	///
	/// Returns `f64::NAN` when no positive samples have been observed.
	#[must_use]
	pub fn pr_auc(&self) -> f64 {
		let total_pos = self.positives();
		if total_pos == 0 {
			return f64::NAN;
		}
		let total_pos = total_pos as f64;
		let mut tp = 0.0_f64;
		let mut fp = 0.0_f64;
		let mut prev_recall = 0.0_f64;
		let mut ap = 0.0_f64;
		for bin in (0..self.num_bins).rev() {
			let pos = self.positive_bins[bin];
			let neg = self.negative_bins[bin];
			if pos == 0 && neg == 0 {
				continue;
			}
			tp += pos as f64;
			fp += neg as f64;
			let recall = tp / total_pos;
			let precision = tp / (tp + fp);
			ap += (recall - prev_recall) * precision;
			prev_recall = recall;
		}
		ap
	}

	/// Drop all accumulated bin counts while keeping the bin configuration.
	pub fn reset(&mut self) {
		self.positive_bins.fill(0);
		self.negative_bins.fill(0);
	}
}