use crate::{DType, Error, Matrix, Result};
#[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 {
pub fn new(num_bins: usize) -> Result<Self> {
Self::with_range(num_bins, 0.0, 1.0)
}
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],
})
}
#[must_use]
pub const fn num_bins(&self) -> usize {
self.num_bins
}
#[must_use]
pub const fn min_score(&self) -> f64 {
self.min_score
}
#[must_use]
pub const fn max_score(&self) -> f64 {
self.max_score
}
#[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
}
#[must_use]
pub fn positives(&self) -> u64 {
self.positive_bins.iter().copied().sum()
}
#[must_use]
pub fn negatives(&self) -> u64 {
self.negative_bins.iter().copied().sum()
}
#[must_use]
pub fn samples(&self) -> u64 {
self.positives().saturating_add(self.negatives())
}
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(())
}
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)
}
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(())
}
#[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
}
#[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
}
pub fn reset(&mut self) {
self.positive_bins.fill(0);
self.negative_bins.fill(0);
}
}