use relate_core::temporal::{self, Temporal};
use relate_core::{Error, Result, Value};
use relate_ir::AggregateKind;
use crate::eval::{extreme_offer, Extreme};
#[derive(Clone)]
enum SumState {
Empty,
Num {
int: i64,
float: f64,
used_float: bool,
mean: f64,
n: usize,
},
Dur {
acc: Temporal,
n: usize,
},
}
#[derive(Clone)]
pub(crate) struct SumAcc {
state: SumState,
}
impl SumAcc {
pub(crate) fn new() -> Self {
Self {
state: SumState::Empty,
}
}
pub(crate) fn offer(&mut self, v: &Value, name: &str) -> Result<()> {
match v {
Value::Int(i) => self.offer_int(*i, name),
Value::Float(f) => self.offer_float(*f, name),
Value::Temporal(t @ Temporal::Duration { .. }) => self.offer_duration(t, name),
Value::Null => Ok(()),
_ => Err(needs_numbers(name)),
}
}
fn offer_int(&mut self, i: i64, name: &str) -> Result<()> {
match &mut self.state {
state @ SumState::Empty => {
*state = SumState::Num {
int: i,
float: 0.0,
used_float: false,
mean: i as f64,
n: 1,
};
}
SumState::Num {
int,
float,
used_float,
mean,
n,
} => {
match int.checked_add(i) {
Some(sum) => *int = sum,
None => {
*float += *int as f64 + i as f64;
*used_float = true;
*int = 0;
}
}
*n += 1;
mean_offer(mean, i as f64, *n);
}
SumState::Dur { .. } => return Err(Self::mix(name)),
}
Ok(())
}
fn offer_float(&mut self, f: f64, name: &str) -> Result<()> {
match &mut self.state {
state @ SumState::Empty => {
*state = SumState::Num {
int: 0,
float: f,
used_float: true,
mean: f,
n: 1,
};
}
SumState::Num {
float,
used_float,
mean,
n,
..
} => {
*float += f;
*used_float = true;
*n += 1;
mean_offer(mean, f, *n);
}
SumState::Dur { .. } => return Err(Self::mix(name)),
}
Ok(())
}
fn offer_duration(&mut self, t: &Temporal, name: &str) -> Result<()> {
match &mut self.state {
state @ SumState::Empty => {
*state = SumState::Dur {
acc: t.clone(),
n: 1,
};
}
SumState::Dur { acc, n } => {
*acc = temporal::add_duration(acc, t)?;
*n += 1;
}
SumState::Num { .. } => return Err(Self::mix(name)),
}
Ok(())
}
fn mix(name: &str) -> Error {
Error::invalid_argument_type(format!("{name}() cannot mix numbers and durations"))
}
pub(crate) fn finish_sum(self) -> Value {
match self.state {
SumState::Dur { acc, .. } => Value::Temporal(acc),
SumState::Empty => Value::Int(0),
SumState::Num {
int,
float,
used_float: true,
..
} => Value::Float(float + int as f64),
SumState::Num { int, .. } => Value::Int(int),
}
}
pub(crate) fn finish_avg(self) -> Result<Value> {
match self.state {
SumState::Dur { acc, n } => Ok(Value::Temporal(temporal::scale_duration(
&acc,
1.0 / n as f64,
)?)),
SumState::Empty => Ok(Value::Null),
SumState::Num {
int,
float,
mean,
n,
..
} => {
let sum = float + int as f64;
if sum.is_finite() {
Ok(Value::Float(sum / n as f64))
} else if mean.is_finite() {
Ok(Value::Float(mean))
} else {
Ok(Value::Float(sum / n as f64))
}
}
}
}
}
fn mean_offer(mean: &mut f64, value: f64, n: usize) {
*mean = *mean - *mean / n as f64 + value / n as f64;
}
fn numeric_operands(vals: &[Value], name: &str) -> Result<Vec<f64>> {
vals.iter()
.filter(|value| !value.is_null())
.map(|value| value.as_number().ok_or_else(|| needs_numbers(name)))
.collect()
}
fn needs_numbers(name: &str) -> Error {
Error::ty(format!("{name}() needs numbers"))
}
pub(crate) enum FoldInput {
Many(AggregateKind),
PercentileCont(f64),
PercentileDisc(f64),
}
impl FoldInput {
pub(crate) fn percentile(kind: AggregateKind, p: f64, name: &str) -> Result<Self> {
match kind {
AggregateKind::PercentileCont => Ok(Self::PercentileCont(p)),
AggregateKind::PercentileDisc => Ok(Self::PercentileDisc(p)),
AggregateKind::Count
| AggregateKind::Collect
| AggregateKind::Sum
| AggregateKind::Avg
| AggregateKind::Min
| AggregateKind::Max
| AggregateKind::StDev
| AggregateKind::StDevP => Err(Error::internal(format!(
"{name}() has the percentile arity but not a percentile kind"
))),
}
}
}
pub(crate) fn fold_aggregate(input: FoldInput, name: &str, vals: Vec<Value>) -> Result<Value> {
match input {
FoldInput::Many(kind) => match StreamFold::for_kind(kind) {
Some(mut fold) => {
for value in vals {
fold.offer(value, name)?;
}
fold.finish()
}
None => match kind {
AggregateKind::Collect => {
Value::checked_list(vals.into_iter().filter(|value| !value.is_null()).collect())
}
AggregateKind::PercentileCont | AggregateKind::PercentileDisc => {
Err(Error::internal(format!(
"{name}() percentile kind reached the fold without its percentile"
)))
}
AggregateKind::Count
| AggregateKind::Sum
| AggregateKind::Avg
| AggregateKind::Min
| AggregateKind::Max
| AggregateKind::StDev
| AggregateKind::StDevP => Err(Error::internal(format!(
"{name}() is a streaming kind with no streaming accumulator"
))),
},
},
FoldInput::PercentileCont(p) => Ok(fold_percentile_cont(numeric_operands(&vals, name)?, p)),
FoldInput::PercentileDisc(p) => Ok(fold_percentile_disc(numeric_operands(&vals, name)?, p)),
}
}
#[derive(Clone)]
pub(crate) enum StreamFold {
Count(i64),
Sum(SumAcc),
Avg(SumAcc),
Extreme {
extreme: Extreme,
best: Option<Value>,
},
Deviation {
population: bool,
n: usize,
mean: f64,
m2: f64,
},
}
impl StreamFold {
pub(crate) fn for_kind(kind: AggregateKind) -> Option<Self> {
match kind {
AggregateKind::Count => Some(Self::Count(0)),
AggregateKind::Sum => Some(Self::Sum(SumAcc::new())),
AggregateKind::Avg => Some(Self::Avg(SumAcc::new())),
AggregateKind::Min => Some(Self::extreme(Extreme::Min)),
AggregateKind::Max => Some(Self::extreme(Extreme::Max)),
AggregateKind::StDev => Some(Self::deviation(false)),
AggregateKind::StDevP => Some(Self::deviation(true)),
AggregateKind::Collect
| AggregateKind::PercentileCont
| AggregateKind::PercentileDisc => None,
}
}
fn extreme(extreme: Extreme) -> Self {
Self::Extreme {
extreme,
best: None,
}
}
fn deviation(population: bool) -> Self {
Self::Deviation {
population,
n: 0,
mean: 0.0,
m2: 0.0,
}
}
pub(crate) fn held_value(&self) -> Option<&Value> {
match self {
Self::Extreme { best, .. } => best.as_ref(),
Self::Count(_) | Self::Sum(_) | Self::Avg(_) | Self::Deviation { .. } => None,
}
}
pub(crate) fn offer(&mut self, value: Value, name: &str) -> Result<()> {
match self {
Self::Count(n) => {
if !value.is_null() {
*n += 1;
}
}
Self::Sum(acc) | Self::Avg(acc) => acc.offer(&value, name)?,
Self::Extreme { extreme, best } => {
extreme_offer(best, *extreme, value, Value::order_by_cmp);
}
Self::Deviation { n, mean, m2, .. } => {
if value.is_null() {
return Ok(());
}
let x = value.as_number().ok_or_else(|| needs_numbers(name))?;
*n += 1;
if *n == 1 {
*mean = x;
*m2 = 0.0;
} else {
let delta = x - *mean;
*mean += delta / *n as f64;
*m2 += delta * (x - *mean);
}
}
}
Ok(())
}
pub(crate) fn finish(self) -> Result<Value> {
match self {
Self::Count(n) => Ok(Value::Int(n)),
Self::Sum(acc) => Ok(acc.finish_sum()),
Self::Avg(acc) => acc.finish_avg(),
Self::Extreme { best, .. } => Ok(best.unwrap_or(Value::Null)),
Self::Deviation { n: 0, .. } => Ok(Value::Null),
Self::Deviation {
population: false,
n: 1,
..
} => Ok(Value::Float(0.0)),
Self::Deviation {
population, n, m2, ..
} => {
let divisor = if population { n } else { n - 1 };
Ok(Value::Float((m2 / divisor as f64).sqrt()))
}
}
}
}
fn sorted_sample(mut nums: Vec<f64>, p: f64) -> Option<Vec<f64>> {
debug_assert!(
(0.0..=1.0).contains(&p),
"percentile must be validated before the fold: {p}"
);
nums.sort_by(f64::total_cmp);
(!nums.is_empty()).then_some(nums)
}
fn fold_percentile_cont(nums: Vec<f64>, p: f64) -> Value {
let Some(nums) = sorted_sample(nums, p) else {
return Value::Null;
};
let h = p * (nums.len() - 1) as f64;
let lo = h.floor() as usize;
let hi = h.ceil() as usize;
let f = h - lo as f64;
let value = if f == 0.0 {
nums[lo]
} else {
nums[lo] * (1.0 - f) + nums[hi] * f
};
Value::Float(value)
}
fn fold_percentile_disc(nums: Vec<f64>, p: f64) -> Value {
let Some(nums) = sorted_sample(nums, p) else {
return Value::Null;
};
let idx = (((nums.len() as f64) * p).ceil() as usize).saturating_sub(1);
Value::Float(nums[idx])
}