#![forbid(unsafe_code)]
#![warn(rustdoc::broken_intra_doc_links)]
use std::{cmp::Ordering, mem::size_of};
use bumpalo::{Bump, collections::Vec as BumpVec};
use fp_columnar::{Column, ColumnError};
use fp_frame::{FrameError, Series};
use fp_index::{Index, IndexError, IndexLabel, align_union, validate_alignment_plan};
use fp_runtime::{EvidenceLedger, RuntimePolicy};
use fp_types::{DType, IntervalClosed, NullKind, PeriodFreq, Scalar, Timedelta, Timestamp};
use rustc_hash::{FxHashMap, FxHashSet};
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GroupByOptions {
pub dropna: bool,
pub sort: bool,
}
impl Default for GroupByOptions {
fn default() -> Self {
Self {
dropna: true,
sort: true,
}
}
}
#[derive(Debug, Error)]
pub enum GroupByError {
#[error(transparent)]
Frame(#[from] FrameError),
#[error(transparent)]
Index(#[from] IndexError),
#[error(transparent)]
Column(#[from] ColumnError),
}
pub const DEFAULT_ARENA_BUDGET_BYTES: usize = 256 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GroupByExecutionOptions {
pub use_arena: bool,
pub arena_budget_bytes: usize,
}
impl Default for GroupByExecutionOptions {
fn default() -> Self {
Self {
use_arena: true,
arena_budget_bytes: DEFAULT_ARENA_BUDGET_BYTES,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct GroupByExecutionTrace {
used_arena: bool,
input_rows: usize,
estimated_bytes: usize,
}
pub fn groupby_sum(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_sum_with_options(
keys,
values,
options,
policy,
ledger,
GroupByExecutionOptions::default(),
)
}
pub fn groupby_sum_with_options(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
exec_options: GroupByExecutionOptions,
) -> Result<Series, GroupByError> {
let (result, _trace) =
groupby_sum_with_trace(keys, values, options, policy, ledger, exec_options)?;
Ok(result)
}
fn groupby_sum_with_trace(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
exec_options: GroupByExecutionOptions,
) -> Result<(Series, GroupByExecutionTrace), GroupByError> {
let aligned_storage = if keys.index() == values.index() && !keys.index().has_duplicates() {
None
} else {
let plan = align_union(keys.index(), values.index());
validate_alignment_plan(&plan)?;
let aligned_keys = keys.column().reindex_by_positions(&plan.left_positions)?;
let aligned_values = values
.column()
.reindex_by_positions(&plan.right_positions)?;
Some((aligned_keys, aligned_values))
};
let (aligned_keys_values, aligned_values_values): (&[Scalar], &[Scalar]) =
if let Some((aligned_keys, aligned_values)) = aligned_storage.as_ref() {
(aligned_keys.values(), aligned_values.values())
} else {
(keys.values(), values.values())
};
let input_rows = aligned_keys_values.len();
let _ = policy.decide_join_admission(input_rows, ledger);
let estimated_bytes = estimate_groupby_intermediate_bytes(input_rows);
let use_arena = exec_options.use_arena && estimated_bytes <= exec_options.arena_budget_bytes;
let result = if use_arena {
groupby_sum_with_arena(aligned_keys_values, aligned_values_values, options)?
} else {
groupby_sum_with_global_allocator(aligned_keys_values, aligned_values_values, options)?
};
Ok((
result,
GroupByExecutionTrace {
used_arena: use_arena,
input_rows,
estimated_bytes,
},
))
}
fn estimate_groupby_intermediate_bytes(input_rows: usize) -> usize {
input_rows.saturating_mul(
size_of::<f64>()
.saturating_add(size_of::<bool>())
.saturating_add(size_of::<i64>())
.saturating_add(64), )
}
fn groupby_sum_with_global_allocator(
aligned_keys_values: &[Scalar],
aligned_values_values: &[Scalar],
options: GroupByOptions,
) -> Result<Series, GroupByError> {
if is_timedelta_values(aligned_values_values) {
return groupby_sum_timedelta64(aligned_keys_values, aligned_values_values, options);
}
if is_utf8_values(aligned_values_values) {
return groupby_sum_utf8(aligned_keys_values, aligned_values_values, options);
}
if is_int64_or_bool_values(aligned_values_values) {
return groupby_sum_int64(aligned_keys_values, aligned_values_values, options);
}
if let Some((out_index, out_values)) = try_groupby_sum_dense_int64(
aligned_keys_values,
aligned_values_values,
options.dropna,
options.sort,
) {
let out_column = Column::from_values(out_values)?;
return Ok(Series::new("sum", Index::new(out_index), out_column)?);
}
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut slot = FxHashMap::<GroupKeyRef<'_>, (usize, f64)>::default();
for (pos, (key, value)) in aligned_keys_values
.iter()
.zip(aligned_values_values.iter())
.enumerate()
{
if options.dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = slot.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, 0.0)
});
if value.is_missing() {
continue;
}
if let Ok(v) = value.to_f64() {
entry.1 += v;
}
}
if options.sort {
sort_group_ordering_by(aligned_keys_values, &mut ordering, |key| {
slot.get(key)
.expect("ordering references only inserted keys")
.0
});
}
emit_groupby_result(aligned_keys_values, &ordering, &mut slot)
}
fn groupby_sum_with_arena(
aligned_keys_values: &[Scalar],
aligned_values_values: &[Scalar],
options: GroupByOptions,
) -> Result<Series, GroupByError> {
if is_timedelta_values(aligned_values_values) {
return groupby_sum_timedelta64(aligned_keys_values, aligned_values_values, options);
}
if is_utf8_values(aligned_values_values) {
return groupby_sum_utf8(aligned_keys_values, aligned_values_values, options);
}
if is_int64_or_bool_values(aligned_values_values) {
return groupby_sum_int64(aligned_keys_values, aligned_values_values, options);
}
if let Some((out_index, out_values)) = try_groupby_sum_dense_int64_arena(
aligned_keys_values,
aligned_values_values,
options.dropna,
options.sort,
) {
let out_column = Column::from_values(out_values)?;
return Ok(Series::new("sum", Index::new(out_index), out_column)?);
}
let arena = Bump::new();
let mut ordering = BumpVec::<GroupKeyRef<'_>>::new_in(&arena);
let mut slot = FxHashMap::<GroupKeyRef<'_>, (usize, f64)>::default();
for (pos, (key, value)) in aligned_keys_values
.iter()
.zip(aligned_values_values.iter())
.enumerate()
{
if options.dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = slot.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, 0.0)
});
if value.is_missing() {
continue;
}
if let Ok(v) = value.to_f64() {
entry.1 += v;
}
}
if options.sort {
sort_group_ordering_by(aligned_keys_values, ordering.as_mut_slice(), |key| {
slot.get(key)
.expect("ordering references only inserted keys")
.0
});
}
emit_groupby_result(aligned_keys_values, ordering.as_slice(), &mut slot)
}
fn emit_groupby_result<'a>(
source_keys: &[Scalar],
ordering: &[GroupKeyRef<'a>],
slot: &mut FxHashMap<GroupKeyRef<'a>, (usize, f64)>,
) -> Result<Series, GroupByError> {
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in ordering {
let (source_idx, sum) = slot
.remove(key)
.expect("ordering references only inserted keys");
let label = &source_keys[source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN) | Scalar::Null(NullKind::Null) => {
IndexLabel::Null(NullKind::NaN)
}
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(Scalar::Float64(sum));
}
let out_column = Column::from_values(out_values)?;
Ok(Series::new("sum", Index::new(out_index), out_column)?)
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
enum GroupKeyRef<'a> {
Bool(bool),
Int64(i64),
FloatBits(u64),
Utf8(&'a str),
Null(NullKind),
Timedelta64(i64),
Datetime64(i64),
Period(i64),
Interval(u64, u64, fp_types::IntervalClosed),
}
impl<'a> GroupKeyRef<'a> {
fn from_scalar(key: &'a Scalar) -> Self {
match key {
Scalar::Bool(v) => Self::Bool(*v),
Scalar::Int64(v) => Self::Int64(*v),
Scalar::Float64(v) => {
if v.is_nan() {
Self::FloatBits(f64::NAN.to_bits())
} else {
let normalized = if *v == 0.0 { 0.0 } else { *v };
Self::FloatBits(normalized.to_bits())
}
}
Scalar::Utf8(v) => Self::Utf8(v.as_str()),
Scalar::Null(kind) => Self::Null(*kind),
Scalar::Timedelta64(v) => {
if *v == Timedelta::NAT {
Self::Null(NullKind::NaT)
} else {
Self::Timedelta64(*v)
}
}
Scalar::Datetime64(v) => {
if *v == Timestamp::NAT {
Self::Null(NullKind::NaT)
} else {
Self::Datetime64(*v)
}
}
Scalar::Period(v) => {
if v.ordinal == i64::MIN {
Self::Null(NullKind::NaT)
} else {
Self::Period(v.ordinal)
}
}
Scalar::Interval(iv) => {
Self::Interval(iv.left.to_bits(), iv.right.to_bits(), iv.closed)
}
}
}
}
fn compare_group_labels(left: &Scalar, right: &Scalar) -> Ordering {
match (left.is_missing(), right.is_missing()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => left.semantic_cmp(right),
}
}
fn sort_group_ordering_by<'a, F>(
source_keys: &[Scalar],
ordering: &mut [GroupKeyRef<'a>],
source_idx_for: F,
) where
F: Fn(&GroupKeyRef<'a>) -> usize,
{
ordering.sort_by(|left, right| {
compare_group_labels(
&source_keys[source_idx_for(left)],
&source_keys[source_idx_for(right)],
)
});
}
fn is_timedelta_values(values: &[Scalar]) -> bool {
let mut saw_td = false;
for v in values {
if v.is_missing() {
continue;
}
match v {
Scalar::Timedelta64(_) => saw_td = true,
_ => return false,
}
}
saw_td
}
fn groupby_sum_timedelta64(
keys: &[Scalar],
values: &[Scalar],
options: GroupByOptions,
) -> Result<Series, GroupByError> {
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut slot = FxHashMap::<GroupKeyRef<'_>, (usize, i64)>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if options.dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = slot.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, 0_i64)
});
if value.is_missing() {
continue;
}
if let Scalar::Timedelta64(ns) = value {
entry.1 = Timedelta::add(entry.1, *ns);
}
}
if options.sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
slot.get(key)
.expect("ordering references only inserted keys")
.0
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let (source_idx, sum) = slot
.remove(key)
.expect("ordering references only inserted keys");
let label = &keys[source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN) | Scalar::Null(NullKind::Null) => {
IndexLabel::Null(NullKind::NaN)
}
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(Scalar::Timedelta64(sum));
}
let out_column = Column::new(DType::Timedelta64, out_values)?;
Ok(Series::new("sum", Index::new(out_index), out_column)?)
}
fn is_utf8_values(values: &[Scalar]) -> bool {
let mut saw_utf8 = false;
for v in values {
if v.is_missing() {
continue;
}
match v {
Scalar::Utf8(_) => saw_utf8 = true,
_ => return false,
}
}
saw_utf8
}
fn groupby_sum_utf8(
keys: &[Scalar],
values: &[Scalar],
options: GroupByOptions,
) -> Result<Series, GroupByError> {
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut slot = FxHashMap::<GroupKeyRef<'_>, (usize, String)>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if options.dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = slot.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, String::new())
});
if let Scalar::Utf8(s) = value {
entry.1.push_str(s);
}
}
if options.sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
slot.get(key)
.expect("ordering references only inserted keys")
.0
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let (source_idx, joined) = slot
.remove(key)
.expect("ordering references only inserted keys");
let label = &keys[source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN) | Scalar::Null(NullKind::Null) => {
IndexLabel::Null(NullKind::NaN)
}
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(Scalar::Utf8(joined));
}
let out_column = Column::new(DType::Utf8, out_values)?;
Ok(Series::new("sum", Index::new(out_index), out_column)?)
}
fn is_int64_or_bool_values(values: &[Scalar]) -> bool {
let mut saw = false;
for v in values {
if v.is_missing() {
return false;
}
match v {
Scalar::Int64(_) | Scalar::Bool(_) => saw = true,
_ => return false,
}
}
saw
}
fn groupby_sum_int64(
keys: &[Scalar],
values: &[Scalar],
options: GroupByOptions,
) -> Result<Series, GroupByError> {
if let Some((out_index, out_values)) =
try_groupby_sum_dense_int64_values(keys, values, options.dropna, options.sort)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new("sum", Index::new(out_index), out_column)?);
}
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut slot = FxHashMap::<GroupKeyRef<'_>, (usize, i128)>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if options.dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = slot.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, 0_i128)
});
match value {
Scalar::Int64(v) => entry.1 += i128::from(*v),
Scalar::Bool(b) => entry.1 += i128::from(*b),
_ => {} }
}
if options.sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
slot.get(key)
.expect("ordering references only inserted keys")
.0
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let (source_idx, total) = slot
.remove(key)
.expect("ordering references only inserted keys");
let label = &keys[source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN) | Scalar::Null(NullKind::Null) => {
IndexLabel::Null(NullKind::NaN)
}
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(match i64::try_from(total) {
Ok(v) => Scalar::Int64(v),
Err(_) => Scalar::Float64(total as f64),
});
}
let out_column = Column::from_values(out_values)?;
Ok(Series::new("sum", Index::new(out_index), out_column)?)
}
const DENSE_INT_KEY_RANGE_LIMIT: i128 = 65_536;
fn dense_int64_range(keys: &[Scalar], dropna: bool) -> Option<(i64, i64, bool)> {
let mut min_key = i64::MAX;
let mut max_key = i64::MIN;
let mut saw_int_key = false;
for key in keys {
match key {
Scalar::Int64(v) => {
saw_int_key = true;
min_key = min_key.min(*v);
max_key = max_key.max(*v);
}
Scalar::Null(_) if dropna => continue,
_ => return None,
}
}
Some((min_key, max_key, saw_int_key))
}
fn try_groupby_sum_dense_int64_values(
keys: &[Scalar],
values: &[Scalar],
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
let (min_key, max_key, saw_int_key) = dense_int64_range(keys, dropna)?;
if !saw_int_key {
return Some((Vec::new(), Vec::new()));
}
let span = i128::from(max_key) - i128::from(min_key) + 1;
if span <= 0 || span > DENSE_INT_KEY_RANGE_LIMIT {
return None;
}
let bucket_len = usize::try_from(span).ok()?;
let mut sums = vec![0_i128; bucket_len];
let mut seen = vec![false; bucket_len];
let mut ordering = Vec::<i64>::new();
for (key, value) in keys.iter().zip(values.iter()) {
let key = match key {
Scalar::Int64(v) => *v,
Scalar::Null(_) if dropna => continue,
_ => return None,
};
let raw = i128::from(key) - i128::from(min_key);
let bucket = usize::try_from(raw).ok()?;
if !seen[bucket] {
seen[bucket] = true;
ordering.push(key);
}
match value {
Scalar::Int64(v) => sums[bucket] += i128::from(*v),
Scalar::Bool(v) => sums[bucket] += i128::from(*v),
_ => return None,
}
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
if sort {
for (bucket, was_seen) in seen.iter().enumerate() {
if !*was_seen {
continue;
}
let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
out_index.push(IndexLabel::Int64(key));
out_values.push(match i64::try_from(sums[bucket]) {
Ok(value) => Scalar::Int64(value),
Err(_) => Scalar::Float64(sums[bucket] as f64),
});
}
} else {
for key in ordering {
let raw = i128::from(key) - i128::from(min_key);
let bucket = usize::try_from(raw).ok()?;
out_index.push(IndexLabel::Int64(key));
out_values.push(match i64::try_from(sums[bucket]) {
Ok(value) => Scalar::Int64(value),
Err(_) => Scalar::Float64(sums[bucket] as f64),
});
}
}
Some((out_index, out_values))
}
fn try_groupby_sum_dense_int64(
keys: &[Scalar],
values: &[Scalar],
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
let (min_key, max_key, saw_int_key) = dense_int64_range(keys, dropna)?;
if !saw_int_key {
return Some((Vec::new(), Vec::new()));
}
let span = i128::from(max_key) - i128::from(min_key) + 1;
if span <= 0 || span > DENSE_INT_KEY_RANGE_LIMIT {
return None;
}
let bucket_len = usize::try_from(span).ok()?;
let mut sums = vec![0.0f64; bucket_len];
let mut seen = vec![false; bucket_len];
let mut ordering = Vec::<i64>::new();
for (key, value) in keys.iter().zip(values.iter()) {
let key = match key {
Scalar::Int64(v) => *v,
Scalar::Null(_) if dropna => continue,
_ => return None,
};
let raw = i128::from(key) - i128::from(min_key);
let bucket = usize::try_from(raw).ok()?;
if !seen[bucket] {
seen[bucket] = true;
ordering.push(key);
}
if value.is_missing() {
continue;
}
if let Ok(v) = value.to_f64() {
sums[bucket] += v;
}
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
if sort {
for (bucket, was_seen) in seen.iter().enumerate() {
if !*was_seen {
continue;
}
let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
out_index.push(IndexLabel::Int64(key));
out_values.push(Scalar::Float64(sums[bucket]));
}
} else {
for key in ordering {
let raw = i128::from(key) - i128::from(min_key);
let bucket = usize::try_from(raw).ok()?;
out_index.push(IndexLabel::Int64(key));
out_values.push(Scalar::Float64(sums[bucket]));
}
}
Some((out_index, out_values))
}
fn try_groupby_sum_dense_int64_arena(
keys: &[Scalar],
values: &[Scalar],
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
let (min_key, max_key, saw_int_key) = dense_int64_range(keys, dropna)?;
if !saw_int_key {
return Some((Vec::new(), Vec::new()));
}
let span = i128::from(max_key) - i128::from(min_key) + 1;
if span <= 0 || span > DENSE_INT_KEY_RANGE_LIMIT {
return None;
}
let bucket_len = usize::try_from(span).ok()?;
let arena = Bump::new();
let mut sums = BumpVec::<f64>::with_capacity_in(bucket_len, &arena);
sums.resize(bucket_len, 0.0f64);
let mut seen = BumpVec::<bool>::with_capacity_in(bucket_len, &arena);
seen.resize(bucket_len, false);
let mut ordering = BumpVec::<i64>::new_in(&arena);
for (key, value) in keys.iter().zip(values.iter()) {
let key = match key {
Scalar::Int64(v) => *v,
Scalar::Null(_) if dropna => continue,
_ => return None,
};
let raw = i128::from(key) - i128::from(min_key);
let bucket = usize::try_from(raw).ok()?;
if !seen[bucket] {
seen[bucket] = true;
ordering.push(key);
}
if value.is_missing() {
continue;
}
if let Ok(v) = value.to_f64() {
sums[bucket] += v;
}
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
if sort {
for (bucket, was_seen) in seen.iter().enumerate() {
if !*was_seen {
continue;
}
let key = min_key.checked_add(i64::try_from(bucket).ok()?)?;
out_index.push(IndexLabel::Int64(key));
out_values.push(Scalar::Float64(sums[bucket]));
}
} else {
for key in ordering.iter().copied() {
let raw = i128::from(key) - i128::from(min_key);
let bucket = usize::try_from(raw).ok()?;
out_index.push(IndexLabel::Int64(key));
out_values.push(Scalar::Float64(sums[bucket]));
}
}
Some((out_index, out_values))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AggFunc {
Sum,
Mean,
Count,
Min,
Max,
First,
Last,
Std,
Var,
Median,
Nunique,
Prod,
Size,
}
#[allow(clippy::too_many_arguments)]
fn try_groupby_agg_dense_int64(
keys: &[Scalar],
values: &[Scalar],
func: AggFunc,
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
if !matches!(
func,
AggFunc::Mean
| AggFunc::Count
| AggFunc::Size
| AggFunc::First
| AggFunc::Last
| AggFunc::Min
| AggFunc::Max
| AggFunc::Prod
| AggFunc::Var
| AggFunc::Std
) {
return None;
}
if matches!(func, AggFunc::Prod)
&& values
.iter()
.find(|v| !v.is_missing())
.is_some_and(|v| matches!(v, Scalar::Int64(_) | Scalar::Bool(_)))
{
return None;
}
let (min_key, max_key, saw_int_key) = dense_int64_range(keys, dropna)?;
if !saw_int_key {
return Some((Vec::new(), Vec::new()));
}
let span = i128::from(max_key) - i128::from(min_key) + 1;
if span <= 0 || span > DENSE_INT_KEY_RANGE_LIMIT {
return None;
}
let bucket_len = usize::try_from(span).ok()?;
let needs_var = matches!(func, AggFunc::Var | AggFunc::Std);
let needs_mean = matches!(func, AggFunc::Mean) || needs_var;
let needs_prod = matches!(func, AggFunc::Prod);
let needs_value = matches!(
func,
AggFunc::First | AggFunc::Last | AggFunc::Min | AggFunc::Max
);
let mut sum = vec![0.0_f64; bucket_len];
let mut prod = if needs_prod {
vec![1.0_f64; bucket_len]
} else {
Vec::new()
};
let mut non_missing = vec![0_i64; bucket_len];
let mut total = vec![0_i64; bucket_len];
let mut value_slot: Vec<Option<Scalar>> = if needs_value {
vec![None; bucket_len]
} else {
Vec::new()
};
let mut first_seen = vec![false; bucket_len];
let mut ordering = Vec::<i64>::new();
for (key, value) in keys.iter().zip(values.iter()) {
let key = match key {
Scalar::Int64(v) => *v,
Scalar::Null(_) if dropna => continue,
_ => return None,
};
let bucket = usize::try_from(i128::from(key) - i128::from(min_key)).ok()?;
if !first_seen[bucket] {
first_seen[bucket] = true;
ordering.push(key);
}
total[bucket] += 1;
if value.is_missing() {
continue;
}
non_missing[bucket] += 1;
if needs_mean {
let x = value.to_f64().ok()?;
sum[bucket] += x;
}
if needs_prod {
let x = value.to_f64().ok()?;
prod[bucket] *= x;
}
if needs_value {
match func {
AggFunc::First if value_slot[bucket].is_none() => {
value_slot[bucket] = Some(value.clone());
}
AggFunc::Last => value_slot[bucket] = Some(value.clone()),
AggFunc::Min => {
let replace = match (value_slot[bucket].as_ref(), value) {
(None, _) => true,
(Some(Scalar::Int64(a)), Scalar::Int64(b)) => b < a,
(Some(Scalar::Float64(a)), Scalar::Float64(b)) => b < a,
_ => return None,
};
if replace {
value_slot[bucket] = Some(value.clone());
}
}
AggFunc::Max => {
let replace = match (value_slot[bucket].as_ref(), value) {
(None, _) => true,
(Some(Scalar::Int64(a)), Scalar::Int64(b)) => b > a,
(Some(Scalar::Float64(a)), Scalar::Float64(b)) => b > a,
_ => return None,
};
if replace {
value_slot[bucket] = Some(value.clone());
}
}
_ => {}
}
}
}
let mut sum_sq = Vec::new();
if needs_var {
sum_sq = vec![0.0_f64; bucket_len];
for (key, value) in keys.iter().zip(values.iter()) {
let key = match key {
Scalar::Int64(v) => *v,
Scalar::Null(_) if dropna => continue,
_ => return None,
};
if value.is_missing() {
continue;
}
let bucket = (i128::from(key) - i128::from(min_key)) as usize;
let mean = sum[bucket] / non_missing[bucket] as f64;
let x = value.to_f64().ok()?;
sum_sq[bucket] += (x - mean).powi(2);
}
}
if sort {
ordering.sort_unstable();
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for &key in &ordering {
let bucket = (i128::from(key) - i128::from(min_key)) as usize;
out_index.push(IndexLabel::Int64(key));
let agg = match func {
AggFunc::Mean => {
if non_missing[bucket] == 0 {
Scalar::Null(NullKind::NaN)
} else {
Scalar::Float64(sum[bucket] / non_missing[bucket] as f64)
}
}
AggFunc::Count => Scalar::Int64(non_missing[bucket]),
AggFunc::Size => Scalar::Int64(total[bucket]),
AggFunc::First | AggFunc::Last | AggFunc::Min | AggFunc::Max => value_slot[bucket]
.take()
.unwrap_or(Scalar::Null(NullKind::NaN)),
AggFunc::Prod => Scalar::Float64(prod[bucket]),
AggFunc::Var | AggFunc::Std => {
let n = non_missing[bucket];
if n <= 1 {
Scalar::Null(NullKind::NaN)
} else {
let var = sum_sq[bucket] / (n - 1) as f64;
Scalar::Float64(if matches!(func, AggFunc::Std) {
var.sqrt()
} else {
var
})
}
}
_ => unreachable!("dense path gated to the supported aggregations"),
};
out_values.push(agg);
}
Some((out_index, out_values))
}
fn try_groupby_nunique_dense_int64(
keys: &[Scalar],
values: &[Scalar],
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
let (min_key, max_key, saw_int_key) = dense_int64_range(keys, dropna)?;
if !saw_int_key {
return Some((Vec::new(), Vec::new()));
}
let key_span = i128::from(max_key) - i128::from(min_key) + 1;
if key_span <= 0 || key_span > DENSE_INT_KEY_RANGE_LIMIT {
return None;
}
let key_span = key_span as usize;
let mut v_min = i64::MAX;
let mut v_max = i64::MIN;
let mut saw_value = false;
for value in values {
match value {
Scalar::Int64(v) => {
saw_value = true;
v_min = v_min.min(*v);
v_max = v_max.max(*v);
}
other if other.is_missing() => {}
_ => return None,
}
}
let value_span = if saw_value {
(i128::from(v_max) - i128::from(v_min) + 1) as usize
} else {
1
};
let cells = (key_span as i128) * (value_span as i128);
if cells > (1_i128 << 24) {
return None;
}
let mut seen = vec![false; cells as usize];
let mut nunique = vec![0_i64; key_span];
let mut first_seen = vec![false; key_span];
let mut ordering = Vec::<i64>::new();
for (key, value) in keys.iter().zip(values.iter()) {
let key = match key {
Scalar::Int64(v) => *v,
Scalar::Null(_) if dropna => continue,
_ => return None,
};
let bucket = (i128::from(key) - i128::from(min_key)) as usize;
if !first_seen[bucket] {
first_seen[bucket] = true;
ordering.push(key);
}
let v = match value {
Scalar::Int64(v) => *v,
other if other.is_missing() => continue,
_ => return None,
};
let cell = bucket * value_span + (i128::from(v) - i128::from(v_min)) as usize;
if !seen[cell] {
seen[cell] = true;
nunique[bucket] += 1;
}
}
if sort {
ordering.sort_unstable();
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for &key in &ordering {
let bucket = (i128::from(key) - i128::from(min_key)) as usize;
out_index.push(IndexLabel::Int64(key));
out_values.push(Scalar::Int64(nunique[bucket]));
}
Some((out_index, out_values))
}
fn try_groupby_median_dense_int64(
keys: &[Scalar],
values: &[Scalar],
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
let (min_key, max_key, saw_int_key) = dense_int64_range(keys, dropna)?;
if !saw_int_key {
return Some((Vec::new(), Vec::new()));
}
let key_span = i128::from(max_key) - i128::from(min_key) + 1;
if key_span <= 0 || key_span > DENSE_INT_KEY_RANGE_LIMIT {
return None;
}
let key_span = key_span as usize;
let mut count = vec![0_usize; key_span];
let mut first_seen = vec![false; key_span];
let mut ordering = Vec::<i64>::new();
for (key, value) in keys.iter().zip(values.iter()) {
let key = match key {
Scalar::Int64(v) => *v,
Scalar::Null(_) if dropna => continue,
_ => return None,
};
let bucket = (i128::from(key) - i128::from(min_key)) as usize;
if !first_seen[bucket] {
first_seen[bucket] = true;
ordering.push(key);
}
if value.is_missing() {
continue;
}
if matches!(value, Scalar::Timedelta64(_)) {
return None;
}
count[bucket] += 1;
}
let mut offsets = vec![0_usize; key_span + 1];
for b in 0..key_span {
offsets[b + 1] = offsets[b] + count[b];
}
let total = offsets[key_span];
let mut flat = vec![0.0_f64; total];
let mut cursor = offsets.clone();
for (key, value) in keys.iter().zip(values.iter()) {
let key = match key {
Scalar::Int64(v) => *v,
Scalar::Null(_) if dropna => continue,
_ => return None,
};
if value.is_missing() {
continue;
}
let x = value.to_f64().ok()?;
let bucket = (i128::from(key) - i128::from(min_key)) as usize;
flat[cursor[bucket]] = x;
cursor[bucket] += 1;
}
if sort {
ordering.sort_unstable();
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for &key in &ordering {
let bucket = (i128::from(key) - i128::from(min_key)) as usize;
out_index.push(IndexLabel::Int64(key));
let slice = &mut flat[offsets[bucket]..offsets[bucket] + count[bucket]];
let agg = if slice.is_empty() {
Scalar::Null(NullKind::NaN)
} else {
let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
let mid = slice.len() / 2;
if slice
.iter()
.any(|x| x.is_nan() || (*x == 0.0 && x.is_sign_negative()))
{
slice.sort_by(cmp);
if slice.len().is_multiple_of(2) {
Scalar::Float64((slice[mid - 1] + slice[mid]) / 2.0)
} else {
Scalar::Float64(slice[mid])
}
} else if slice.len().is_multiple_of(2) {
let (lo_part, &mut hi, _) = slice.select_nth_unstable_by(mid, cmp);
let lo = lo_part.iter().copied().fold(f64::NEG_INFINITY, f64::max);
Scalar::Float64((lo + hi) / 2.0)
} else {
let (_, &mut median, _) = slice.select_nth_unstable_by(mid, cmp);
Scalar::Float64(median)
}
};
out_values.push(agg);
}
Some((out_index, out_values))
}
fn try_groupby_count_size_counter(
keys: &[Scalar],
values: &[Scalar],
func: AggFunc,
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
if !matches!(func, AggFunc::Count | AggFunc::Size) {
return None;
}
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, (usize, i64, i64)>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, 0, 0)
});
if !value.is_missing() {
entry.1 += 1;
}
entry.2 += 1;
}
if sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.0
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let (source_idx, non_missing, total) = groups
.get(key)
.expect("ordering references only inserted keys");
let label = &keys[*source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN | NullKind::Null) => IndexLabel::Null(NullKind::NaN),
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(Scalar::Int64(if matches!(func, AggFunc::Count) {
*non_missing
} else {
*total
}));
}
Some((out_index, out_values))
}
fn try_groupby_mean_numeric_counter(
keys: &[Scalar],
values: &[Scalar],
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, (usize, f64, usize)>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, 0.0, 0)
});
if value.is_missing() {
continue;
}
let value = value.to_f64().ok()?;
entry.1 += value;
entry.2 += 1;
}
if sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.0
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let (source_idx, sum, count) = groups
.get(key)
.expect("ordering references only inserted keys");
let label = &keys[*source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN | NullKind::Null) => IndexLabel::Null(NullKind::NaN),
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(if *count == 0 {
Scalar::Null(NullKind::NaN)
} else {
Scalar::Float64(*sum / *count as f64)
});
}
Some((out_index, out_values))
}
#[derive(Debug, Clone)]
struct VarStdScalarAccumulator {
source_idx: usize,
sum: f64,
count: usize,
sum_sq: f64,
}
fn try_groupby_var_std_numeric_counter(
keys: &[Scalar],
values: &[Scalar],
func: AggFunc,
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
if !matches!(func, AggFunc::Var | AggFunc::Std) {
return None;
}
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, VarStdScalarAccumulator>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
VarStdScalarAccumulator {
source_idx: pos,
sum: 0.0,
count: 0,
sum_sq: 0.0,
}
});
if value.is_missing() {
continue;
}
if matches!(value, Scalar::Timedelta64(_)) {
return None;
}
let value = value.to_f64().ok()?;
entry.sum += value;
entry.count += 1;
}
for (key, value) in keys.iter().zip(values.iter()) {
if dropna && key.is_missing() {
continue;
}
if value.is_missing() {
continue;
}
if matches!(value, Scalar::Timedelta64(_)) {
return None;
}
let value = value.to_f64().ok()?;
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups
.get_mut(&key_id)
.expect("second pass references only first-pass groups");
let mean = entry.sum / entry.count as f64;
entry.sum_sq += (value - mean).powi(2);
}
if sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.source_idx
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let group = groups
.get(key)
.expect("ordering references only inserted keys");
let label = &keys[group.source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN | NullKind::Null) => IndexLabel::Null(NullKind::NaN),
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(if group.count <= 1 {
Scalar::Null(NullKind::NaN)
} else {
let var = group.sum_sq / (group.count - 1) as f64;
Scalar::Float64(if matches!(func, AggFunc::Std) {
var.sqrt()
} else {
var
})
});
}
Some((out_index, out_values))
}
fn scalar_group_label(label: &Scalar) -> IndexLabel {
match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN | NullKind::Null) => IndexLabel::Null(NullKind::NaN),
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
}
}
fn numeric_median_scalar(values: &mut [f64]) -> Scalar {
if values.is_empty() {
return Scalar::Null(NullKind::NaN);
}
let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(Ordering::Equal);
let mid = values.len() / 2;
if values
.iter()
.any(|x| x.is_nan() || (*x == 0.0 && x.is_sign_negative()))
{
values.sort_by(cmp);
if values.len().is_multiple_of(2) {
Scalar::Float64((values[mid - 1] + values[mid]) / 2.0)
} else {
Scalar::Float64(values[mid])
}
} else if values.len().is_multiple_of(2) {
let (lo_part, &mut hi, _) = values.select_nth_unstable_by(mid, cmp);
let lo = lo_part.iter().copied().fold(f64::NEG_INFINITY, f64::max);
Scalar::Float64((lo + hi) / 2.0)
} else {
let (_, &mut median, _) = values.select_nth_unstable_by(mid, cmp);
Scalar::Float64(median)
}
}
fn try_groupby_median_numeric_vectors(
keys: &[Scalar],
values: &[Scalar],
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, (usize, Vec<f64>)>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, Vec::new())
});
if value.is_missing() {
continue;
}
if matches!(value, Scalar::Timedelta64(_)) {
return None;
}
entry.1.push(value.to_f64().ok()?);
}
if sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.0
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let (source_idx, values) = groups
.get_mut(key)
.expect("ordering references only inserted keys");
out_index.push(scalar_group_label(&keys[*source_idx]));
out_values.push(numeric_median_scalar(values));
}
Some((out_index, out_values))
}
#[derive(Hash, PartialEq, Eq)]
enum NuniqueValueKey<'a> {
Bool(bool),
Int64(i64),
FloatBits(u64),
Utf8(&'a str),
Timedelta64(i64),
Datetime64(i64),
Period(i64, PeriodFreq),
Interval(u64, u64, IntervalClosed),
}
fn nunique_value_key(value: &Scalar) -> Option<NuniqueValueKey<'_>> {
if value.is_missing() {
return None;
}
Some(match value {
Scalar::Bool(v) => NuniqueValueKey::Bool(*v),
Scalar::Int64(v) => NuniqueValueKey::Int64(*v),
Scalar::Float64(v) => {
let normalized = if *v == 0.0 { 0.0 } else { *v };
NuniqueValueKey::FloatBits(normalized.to_bits())
}
Scalar::Utf8(v) => NuniqueValueKey::Utf8(v.as_str()),
Scalar::Timedelta64(v) => NuniqueValueKey::Timedelta64(*v),
Scalar::Datetime64(v) => NuniqueValueKey::Datetime64(*v),
Scalar::Period(v) => NuniqueValueKey::Period(v.ordinal, v.freq),
Scalar::Interval(v) => NuniqueValueKey::Interval(
if v.left == 0.0 { 0.0 } else { v.left }.to_bits(),
if v.right == 0.0 { 0.0 } else { v.right }.to_bits(),
v.closed,
),
Scalar::Null(_) => return None,
})
}
struct NuniqueScalarAccumulator<'a> {
source_idx: usize,
seen: FxHashSet<NuniqueValueKey<'a>>,
}
fn try_groupby_nunique_borrowed_sets(
keys: &[Scalar],
values: &[Scalar],
dropna: bool,
sort: bool,
) -> (Vec<IndexLabel>, Vec<Scalar>) {
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, NuniqueScalarAccumulator<'_>>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
NuniqueScalarAccumulator {
source_idx: pos,
seen: FxHashSet::default(),
}
});
if let Some(value_key) = nunique_value_key(value) {
entry.seen.insert(value_key);
}
}
if sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.source_idx
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let group = groups
.get(key)
.expect("ordering references only inserted keys");
out_index.push(scalar_group_label(&keys[group.source_idx]));
out_values.push(Scalar::Int64(group.seen.len() as i64));
}
(out_index, out_values)
}
fn update_min_max_scalar_slot(
slot: &mut Option<Scalar>,
invalid: &mut bool,
value: &Scalar,
take_min: bool,
) {
if value.is_missing() || *invalid {
return;
}
let Some(current) = slot else {
*slot = Some(value.clone());
return;
};
let replace = match (&*current, value) {
(Scalar::Int64(a), Scalar::Int64(b)) => {
if take_min {
b < a
} else {
b > a
}
}
(Scalar::Float64(a), Scalar::Float64(b)) => {
if take_min {
b < a
} else {
b > a
}
}
(Scalar::Utf8(a), Scalar::Utf8(b)) => {
if take_min {
b < a
} else {
b > a
}
}
(Scalar::Bool(a), Scalar::Bool(b)) => {
if take_min {
b < a
} else {
b > a
}
}
(Scalar::Timedelta64(a), Scalar::Timedelta64(b)) => {
if take_min {
b < a
} else {
b > a
}
}
(a, b) => match (a.to_f64(), b.to_f64()) {
(Ok(af), Ok(bf)) => {
if take_min {
bf < af
} else {
bf > af
}
}
_ => {
*invalid = true;
false
}
},
};
if replace {
*current = value.clone();
}
}
fn try_groupby_min_max_scalar_slot(
keys: &[Scalar],
values: &[Scalar],
func: AggFunc,
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
if !matches!(func, AggFunc::Min | AggFunc::Max) {
return None;
}
let take_min = matches!(func, AggFunc::Min);
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, (usize, Option<Scalar>, bool)>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, None, false)
});
update_min_max_scalar_slot(&mut entry.1, &mut entry.2, value, take_min);
}
if sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.0
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let (source_idx, slot, invalid) = groups
.get(key)
.expect("ordering references only inserted keys");
let label = &keys[*source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN | NullKind::Null) => IndexLabel::Null(NullKind::NaN),
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(if *invalid {
Scalar::Null(NullKind::NaN)
} else {
slot.clone().unwrap_or(Scalar::Null(NullKind::NaN))
});
}
Some((out_index, out_values))
}
fn try_groupby_first_last_scalar_slot(
keys: &[Scalar],
values: &[Scalar],
func: AggFunc,
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
if !matches!(func, AggFunc::First | AggFunc::Last) {
return None;
}
let take_first = matches!(func, AggFunc::First);
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, (usize, Option<Scalar>)>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, None)
});
if value.is_missing() {
continue;
}
if !take_first || entry.1.is_none() {
entry.1 = Some(value.clone());
}
}
if sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.0
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let (source_idx, slot) = groups
.get(key)
.expect("ordering references only inserted keys");
let label = &keys[*source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN | NullKind::Null) => IndexLabel::Null(NullKind::NaN),
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(slot.clone().unwrap_or(Scalar::Null(NullKind::NaN)));
}
Some((out_index, out_values))
}
#[derive(Debug, Clone)]
struct SumProdScalarAccumulator {
source_idx: usize,
sum: i128,
prod_i128: Option<i128>,
prod_f64: f64,
}
#[derive(Debug, Clone)]
struct SumProdFloatAccumulator {
source_idx: usize,
sum: f64,
prod: f64,
}
fn try_groupby_sum_prod_integer_counter(
keys: &[Scalar],
values: &[Scalar],
func: AggFunc,
value_dtype: DType,
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
if !matches!(func, AggFunc::Sum | AggFunc::Prod)
|| !matches!(value_dtype, DType::Int64 | DType::Bool)
{
return None;
}
let take_sum = matches!(func, AggFunc::Sum);
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, SumProdScalarAccumulator>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
SumProdScalarAccumulator {
source_idx: pos,
sum: 0,
prod_i128: Some(1),
prod_f64: 1.0,
}
});
let value_i128 = match value {
Scalar::Int64(x) => i128::from(*x),
Scalar::Bool(b) => i128::from(u8::from(*b)),
_ => continue,
};
if take_sum {
entry.sum += value_i128;
} else {
entry.prod_i128 = entry
.prod_i128
.and_then(|prod| prod.checked_mul(value_i128));
entry.prod_f64 *= value_i128 as f64;
}
}
if sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.source_idx
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let group = groups
.get(key)
.expect("ordering references only inserted keys");
let label = &keys[group.source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN | NullKind::Null) => IndexLabel::Null(NullKind::NaN),
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(if take_sum {
match i64::try_from(group.sum) {
Ok(sum) => Scalar::Int64(sum),
Err(_) => Scalar::Float64(group.sum as f64),
}
} else {
match group.prod_i128.and_then(|prod| i64::try_from(prod).ok()) {
Some(prod) => Scalar::Int64(prod),
None => Scalar::Float64(group.prod_f64),
}
});
}
Some((out_index, out_values))
}
fn try_groupby_sum_prod_float_counter(
keys: &[Scalar],
values: &[Scalar],
func: AggFunc,
value_dtype: DType,
dropna: bool,
sort: bool,
) -> Option<(Vec<IndexLabel>, Vec<Scalar>)> {
if !matches!(func, AggFunc::Sum | AggFunc::Prod) || !matches!(value_dtype, DType::Float64) {
return None;
}
let take_sum = matches!(func, AggFunc::Sum);
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, SumProdFloatAccumulator>::default();
for (pos, (key, value)) in keys.iter().zip(values.iter()).enumerate() {
if dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
SumProdFloatAccumulator {
source_idx: pos,
sum: 0.0,
prod: 1.0,
}
});
if value.is_missing() {
continue;
}
let Scalar::Float64(x) = value else {
return None;
};
if take_sum {
entry.sum += *x;
} else {
entry.prod *= *x;
}
}
if sort {
sort_group_ordering_by(keys, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.source_idx
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let group = groups
.get(key)
.expect("ordering references only inserted keys");
let label = &keys[group.source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN | NullKind::Null) => IndexLabel::Null(NullKind::NaN),
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
out_values.push(Scalar::Float64(if take_sum {
group.sum
} else {
group.prod
}));
}
Some((out_index, out_values))
}
pub fn groupby_agg(
keys: &Series,
values: &Series,
func: AggFunc,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
let aligned_storage = if keys.index() == values.index() && !keys.index().has_duplicates() {
None
} else {
let plan = align_union(keys.index(), values.index());
validate_alignment_plan(&plan)?;
let aligned_keys = keys.column().reindex_by_positions(&plan.left_positions)?;
let aligned_values = values
.column()
.reindex_by_positions(&plan.right_positions)?;
Some((aligned_keys, aligned_values))
};
let (key_vals, val_vals): (&[Scalar], &[Scalar]) =
if let Some((ref ak, ref av)) = aligned_storage {
(ak.values(), av.values())
} else {
(keys.values(), values.values())
};
let _ = policy.decide_join_admission(key_vals.len(), ledger);
let value_dtype = values.column().dtype();
let agg_name = match func {
AggFunc::Sum => "sum",
AggFunc::Mean => "mean",
AggFunc::Count => "count",
AggFunc::Min => "min",
AggFunc::Max => "max",
AggFunc::First => "first",
AggFunc::Last => "last",
AggFunc::Std => "std",
AggFunc::Var => "var",
AggFunc::Median => "median",
AggFunc::Nunique => "nunique",
AggFunc::Prod => "prod",
AggFunc::Size => "size",
};
if let Some((out_index, out_values)) =
try_groupby_agg_dense_int64(key_vals, val_vals, func, options.dropna, options.sort)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if let Some((out_index, out_values)) =
try_groupby_count_size_counter(key_vals, val_vals, func, options.dropna, options.sort)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::Mean)
&& let Some((out_index, out_values)) =
try_groupby_mean_numeric_counter(key_vals, val_vals, options.dropna, options.sort)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::Var | AggFunc::Std)
&& let Some((out_index, out_values)) = try_groupby_var_std_numeric_counter(
key_vals,
val_vals,
func,
options.dropna,
options.sort,
)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::Median)
&& let Some((out_index, out_values)) =
try_groupby_median_numeric_vectors(key_vals, val_vals, options.dropna, options.sort)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::Min | AggFunc::Max)
&& let Some((out_index, out_values)) =
try_groupby_min_max_scalar_slot(key_vals, val_vals, func, options.dropna, options.sort)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::First | AggFunc::Last)
&& let Some((out_index, out_values)) = try_groupby_first_last_scalar_slot(
key_vals,
val_vals,
func,
options.dropna,
options.sort,
)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::Sum | AggFunc::Prod)
&& let Some((out_index, out_values)) = try_groupby_sum_prod_integer_counter(
key_vals,
val_vals,
func,
value_dtype,
options.dropna,
options.sort,
)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::Sum | AggFunc::Prod)
&& let Some((out_index, out_values)) = try_groupby_sum_prod_float_counter(
key_vals,
val_vals,
func,
value_dtype,
options.dropna,
options.sort,
)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::Nunique)
&& let Some((out_index, out_values)) =
try_groupby_nunique_dense_int64(key_vals, val_vals, options.dropna, options.sort)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::Nunique) {
let (out_index, out_values) =
try_groupby_nunique_borrowed_sets(key_vals, val_vals, options.dropna, options.sort);
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
if matches!(func, AggFunc::Median)
&& let Some((out_index, out_values)) =
try_groupby_median_dense_int64(key_vals, val_vals, options.dropna, options.sort)
{
let out_column = Column::from_values(out_values)?;
return Ok(Series::new(agg_name, Index::new(out_index), out_column)?);
}
let mut ordering = Vec::<GroupKeyRef<'_>>::new();
let mut groups = FxHashMap::<GroupKeyRef<'_>, (usize, Vec<Scalar>, usize)>::default();
for (pos, (key, value)) in key_vals.iter().zip(val_vals.iter()).enumerate() {
if options.dropna && key.is_missing() {
continue;
}
let key_id = GroupKeyRef::from_scalar(key);
let entry = groups.entry(key_id.clone()).or_insert_with(|| {
ordering.push(key_id.clone());
(pos, Vec::new(), 0)
});
entry.2 += 1; if !value.is_missing() {
entry.1.push(value.clone());
}
}
if options.sort {
sort_group_ordering_by(key_vals, &mut ordering, |key| {
groups
.get(key)
.expect("ordering references only inserted keys")
.0
});
}
let mut out_index = Vec::with_capacity(ordering.len());
let mut out_values = Vec::with_capacity(ordering.len());
for key in &ordering {
let (source_idx, vals, total_count) = groups
.get(key)
.expect("ordering references only inserted keys");
let label = &key_vals[*source_idx];
out_index.push(match label {
Scalar::Int64(v) => IndexLabel::Int64(*v),
Scalar::Utf8(v) => IndexLabel::Utf8(v.clone()),
Scalar::Bool(v) => IndexLabel::Utf8(if *v { "True" } else { "False" }.to_string()),
Scalar::Null(NullKind::NaT) => IndexLabel::Null(NullKind::NaT),
Scalar::Null(NullKind::NaN | NullKind::Null) => IndexLabel::Null(NullKind::NaN),
Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
Scalar::Timedelta64(v) => IndexLabel::Utf8(Timedelta::format(*v)),
Scalar::Datetime64(v) => IndexLabel::Datetime64(*v),
Scalar::Period(v) => IndexLabel::Utf8(v.calendar_string()),
Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
});
let agg_value = match func {
AggFunc::Sum if matches!(value_dtype, DType::Int64 | DType::Bool) => {
let mut total = 0_i128;
for v in vals {
match v {
Scalar::Int64(x) => total += i128::from(*x),
Scalar::Bool(b) => total += i128::from(*b),
_ => {}
}
}
match i64::try_from(total) {
Ok(x) => Scalar::Int64(x),
Err(_) => Scalar::Float64(total as f64),
}
}
AggFunc::Sum => fp_types::nansum(vals),
AggFunc::Mean => fp_types::nanmean(vals),
AggFunc::Count => fp_types::nancount(vals),
AggFunc::Min => fp_types::nanmin(vals),
AggFunc::Max => fp_types::nanmax(vals),
AggFunc::First => {
if vals.is_empty() {
Scalar::Null(NullKind::NaN)
} else {
vals[0].clone()
}
}
AggFunc::Last => {
if vals.is_empty() {
Scalar::Null(NullKind::NaN)
} else {
vals[vals.len() - 1].clone()
}
}
AggFunc::Var => fp_types::nanvar(vals, 1),
AggFunc::Std => fp_types::nanstd(vals, 1),
AggFunc::Median => fp_types::nanmedian(vals),
AggFunc::Nunique => fp_types::nannunique(vals),
AggFunc::Prod if matches!(value_dtype, DType::Int64 | DType::Bool) => {
let mut total: Option<i128> = Some(1);
for v in vals {
let x = match v {
Scalar::Int64(x) => i128::from(*x),
Scalar::Bool(b) => i128::from(*b),
_ => continue,
};
total = total.and_then(|t| t.checked_mul(x));
}
match total.and_then(|t| i64::try_from(t).ok()) {
Some(x) => Scalar::Int64(x),
None => fp_types::nanprod(vals),
}
}
AggFunc::Prod => fp_types::nanprod(vals),
AggFunc::Size => Scalar::Int64(*total_count as i64),
};
out_values.push(agg_value);
}
let out_column = Column::from_values(out_values)?;
Ok(Series::new(agg_name, Index::new(out_index), out_column)?)
}
pub fn groupby_mean(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Mean, options, policy, ledger)
}
pub fn groupby_count(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Count, options, policy, ledger)
}
pub fn groupby_min(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Min, options, policy, ledger)
}
pub fn groupby_max(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Max, options, policy, ledger)
}
pub fn groupby_first(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::First, options, policy, ledger)
}
pub fn groupby_last(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Last, options, policy, ledger)
}
pub fn groupby_std(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Std, options, policy, ledger)
}
pub fn groupby_var(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Var, options, policy, ledger)
}
pub fn groupby_median(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Median, options, policy, ledger)
}
pub fn groupby_nunique(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Nunique, options, policy, ledger)
}
pub fn groupby_prod(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Prod, options, policy, ledger)
}
pub fn groupby_size(
keys: &Series,
values: &Series,
options: GroupByOptions,
policy: &RuntimePolicy,
ledger: &mut EvidenceLedger,
) -> Result<Series, GroupByError> {
groupby_agg(keys, values, AggFunc::Size, options, policy, ledger)
}
fn sketch_hash(value: u64, seed: u64) -> u64 {
let mut h = value.wrapping_add(seed);
h = (h ^ (h >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
h = (h ^ (h >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
h ^ (h >> 31)
}
fn scalar_to_hash_bits(value: &Scalar) -> u64 {
match value {
Scalar::Int64(v) => *v as u64,
Scalar::Float64(v) => {
if v.is_nan() {
return 0xDEAD_BEEF_CAFE_BABE;
}
v.to_bits()
}
Scalar::Bool(v) => u64::from(*v),
Scalar::Utf8(s) => {
let mut h = 0xcbf2_9ce4_8422_2325_u64;
for b in s.bytes() {
h ^= u64::from(b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
}
Scalar::Null(_) => 0,
Scalar::Timedelta64(v) => *v as u64,
Scalar::Datetime64(v) => *v as u64,
Scalar::Period(v) => v.ordinal as u64,
Scalar::Interval(iv) => iv.left.to_bits() ^ iv.right.to_bits(),
}
}
pub struct HyperLogLog {
registers: Vec<u8>,
p: u32,
}
impl HyperLogLog {
#[must_use]
pub fn new(p: u32) -> Self {
let p = p.clamp(6, 18);
let m = 1_usize << p;
Self {
registers: vec![0_u8; m],
p,
}
}
#[must_use]
pub fn default_precision() -> Self {
Self::new(14)
}
pub fn insert_hash(&mut self, hash: u64) {
let m = self.registers.len();
let idx = (hash >> (64 - self.p)) as usize;
let remaining = hash << self.p;
let sentinel = if self.p == 0 {
0
} else {
1_u64 << (self.p - 1)
};
let rho = (remaining | sentinel).leading_zeros() as u8 + 1;
if rho > self.registers[idx % m] {
self.registers[idx % m] = rho;
}
}
pub fn insert(&mut self, value: &Scalar) {
let raw = scalar_to_hash_bits(value);
let hash = sketch_hash(raw, 0x1234_5678);
self.insert_hash(hash);
}
#[must_use]
pub fn estimate(&self) -> f64 {
let m = self.registers.len() as f64;
let alpha = match self.registers.len() {
16 => 0.673,
32 => 0.697,
64 => 0.709,
_ => 0.7213 / (1.0 + 1.079 / m),
};
let raw_estimate = alpha * m * m
/ self
.registers
.iter()
.map(|&r| 2_f64.powi(i32::from(r)).recip())
.sum::<f64>();
let zeros = self.registers.iter().filter(|&&r| r == 0).count();
if raw_estimate <= 2.5 * m && zeros > 0 {
m * (m / zeros as f64).ln()
} else {
raw_estimate
}
}
#[must_use]
pub fn memory_bytes(&self) -> usize {
self.registers.len()
}
}
pub struct KllSketch {
compactors: Vec<Vec<f64>>,
k: usize,
size: usize,
compact_count: usize,
}
impl KllSketch {
#[must_use]
pub fn new(k: usize) -> Self {
let k = k.max(8);
Self {
compactors: vec![Vec::with_capacity(k * 2)],
k,
size: 0,
compact_count: 0,
}
}
#[must_use]
pub fn default_accuracy() -> Self {
Self::new(256)
}
pub fn insert(&mut self, value: f64) {
self.compactors[0].push(value);
self.size += 1;
if self.compactors[0].len() >= self.capacity_at_level(0) {
self.compact(0);
}
}
fn capacity_at_level(&self, _level: usize) -> usize {
2 * self.k
}
fn compact(&mut self, level: usize) {
self.compactors[level]
.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let offset = (self.compact_count + level) % 2;
self.compact_count = self.compact_count.wrapping_add(1);
let promoted: Vec<f64> = self.compactors[level]
.iter()
.copied()
.enumerate()
.filter_map(|(i, v)| if i % 2 == offset { Some(v) } else { None })
.collect();
self.compactors[level].clear();
if level + 1 >= self.compactors.len() {
self.compactors.push(Vec::with_capacity(self.k * 2));
}
self.compactors[level + 1].extend(promoted);
if self.compactors[level + 1].len() >= self.capacity_at_level(level + 1) {
self.compact(level + 1);
}
}
#[must_use]
pub fn quantile(&self, q: f64) -> Option<f64> {
if self.size == 0 {
return None;
}
let q = q.clamp(0.0, 1.0);
let mut weighted: Vec<(f64, u64)> = Vec::new();
for (level, compactor) in self.compactors.iter().enumerate() {
let weight = 1_u64.checked_shl(level as u32).unwrap_or(u64::MAX);
for &value in compactor {
weighted.push((value, weight));
}
}
weighted
.sort_unstable_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
let total_weight: u64 = weighted
.iter()
.map(|(_, w)| w)
.fold(0_u64, |acc, &w| acc.saturating_add(w));
let target = (q * total_weight as f64).ceil() as u64;
let target = target.max(1).min(total_weight);
let mut cumulative = 0_u64;
for &(value, weight) in &weighted {
cumulative += weight;
if cumulative >= target {
return Some(value);
}
}
weighted.last().map(|&(v, _)| v)
}
#[must_use]
pub fn len(&self) -> usize {
self.size
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.size == 0
}
}
pub struct CountMinSketch {
counters: Vec<Vec<u64>>,
width: usize,
seeds: Vec<u64>,
}
impl CountMinSketch {
#[must_use]
pub fn new(width: usize, depth: usize) -> Self {
let width = width.max(16);
let depth = depth.max(2);
let seeds: Vec<u64> = (0..depth)
.map(|i| sketch_hash(i as u64, 0xBEEF_CAFE))
.collect();
Self {
counters: vec![vec![0_u64; width]; depth],
width,
seeds,
}
}
#[must_use]
pub fn default_accuracy() -> Self {
Self::new(1024, 5)
}
pub fn insert(&mut self, value: &Scalar) {
let raw = scalar_to_hash_bits(value);
for (d, seed) in self.seeds.iter().enumerate() {
let h = sketch_hash(raw, *seed) as usize % self.width;
self.counters[d][h] = self.counters[d][h].saturating_add(1);
}
}
#[must_use]
pub fn estimate(&self, value: &Scalar) -> u64 {
let raw = scalar_to_hash_bits(value);
self.seeds
.iter()
.enumerate()
.map(|(d, seed)| {
let h = sketch_hash(raw, *seed) as usize % self.width;
self.counters[d][h]
})
.min()
.unwrap_or(0)
}
}
#[derive(Debug, Clone)]
pub struct SketchResult {
pub value: f64,
pub error_bound: f64,
pub memory_bytes: usize,
}
pub fn approx_nunique(values: &[Scalar]) -> SketchResult {
let mut hll = HyperLogLog::default_precision();
for v in values {
if !v.is_missing() {
hll.insert(v);
}
}
let estimate = hll.estimate();
let m = hll.registers.len() as f64;
let std_error = 1.04 / m.sqrt();
SketchResult {
value: estimate,
error_bound: std_error * estimate, memory_bytes: hll.memory_bytes(),
}
}
pub fn approx_quantile(values: &[Scalar], q: f64) -> Option<SketchResult> {
let mut kll = KllSketch::default_accuracy();
for v in values {
if let Ok(f) = v.to_f64() {
kll.insert(f);
}
}
kll.quantile(q).map(|value| SketchResult {
value,
error_bound: 1.0 / kll.k as f64, memory_bytes: kll.compactors.iter().map(|c| c.len() * 8).sum(),
})
}
pub fn approx_value_counts(values: &[Scalar]) -> Vec<(Scalar, u64)> {
let mut cm = CountMinSketch::default_accuracy();
let mut seen = Vec::<Scalar>::new();
for v in values {
if v.is_missing() {
continue;
}
cm.insert(v);
if !seen.iter().any(|s| s == v) {
seen.push(v.clone());
}
}
seen.into_iter()
.map(|v| {
let freq = cm.estimate(&v);
(v, freq)
})
.collect()
}
#[cfg(test)]
mod tests {
use fp_frame::Series;
use fp_index::IndexLabel;
use fp_runtime::{EvidenceLedger, RuntimePolicy};
use fp_types::{NullKind, Scalar};
use super::{
GroupByExecutionOptions, GroupByOptions, groupby_nunique, groupby_prod, groupby_size,
groupby_sum, groupby_sum_with_options, groupby_sum_with_trace,
try_groupby_sum_dense_int64_values,
};
#[test]
fn groupby_sum_dense_int64_keys_match_naive_reference_fuzz_xbrt8() {
use std::collections::BTreeMap;
let mut st: u64 = 0xD1B5_4A32_D192_ED03;
let mut next = || {
st = st
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
st >> 33
};
for _ in 0..400 {
let n = (next() % 8 + 1) as usize;
let raw_keys: Vec<Option<i64>> = (0..n)
.map(|_| {
let r = next() % 7;
if r == 6 { None } else { Some(r as i64 - 3) }
})
.collect();
let raw_vals: Vec<Option<f64>> = (0..n)
.map(|i| {
if next() % 5 == 0 {
None
} else {
Some(((i as i64 + 1) * 10) as f64)
}
})
.collect();
let keys = Series::from_values(
"k",
(0..n).map(|i| (i as i64).into()).collect(),
raw_keys
.iter()
.map(|k| k.map_or(Scalar::Null(NullKind::Null), Scalar::Int64))
.collect(),
)
.unwrap();
let vals = Series::from_values(
"v",
(0..n).map(|i| (i as i64).into()).collect(),
raw_vals
.iter()
.map(|v| v.map_or(Scalar::Null(NullKind::NaN), Scalar::Float64))
.collect(),
)
.unwrap();
let out = groupby_sum(
&keys,
&vals,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut EvidenceLedger::new(),
)
.unwrap();
let mut groups: BTreeMap<i64, f64> = BTreeMap::new();
for i in 0..n {
if let Some(k) = raw_keys[i] {
let entry = groups.entry(k).or_insert(0.0);
if let Some(v) = raw_vals[i] {
*entry += v;
}
}
}
let exp_idx: Vec<IndexLabel> = groups.keys().map(|&k| IndexLabel::Int64(k)).collect();
let exp_val: Vec<Scalar> = groups.values().map(|&v| Scalar::Float64(v)).collect();
assert_eq!(
out.index().labels(),
exp_idx.as_slice(),
"index mismatch for keys={raw_keys:?}"
);
assert_eq!(
out.values(),
exp_val.as_slice(),
"values mismatch for keys={raw_keys:?} vals={raw_vals:?}"
);
}
}
#[test]
fn groupby_sum_sorts_keys_by_default() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(out.values(), &[Scalar::Int64(6), Scalar::Int64(4)]);
}
#[test]
fn dense_int64_groupby_matches_handcomputed_oracle_k3zcv() {
use std::collections::BTreeMap;
let mut state: u64 = 0x1234_5678_9abc_def1;
let mut next = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(state >> 33) as u32
};
for iter in 0..1200u32 {
let n = (next() % 14) as usize + 1;
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let key_vals: Vec<i64> = (0..n).map(|_| (next() % 5) as i64 - 2).collect();
let val_vals: Vec<i64> = (0..n).map(|_| (next() % 21) as i64 - 10).collect();
let keys = Series::from_values(
"k",
idx.clone(),
key_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.expect("keys");
let values = Series::from_values(
"v",
idx,
val_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.expect("values");
let mut groups: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
for (k, v) in key_vals.iter().zip(val_vals.iter()) {
groups.entry(*k).or_default().push(*v);
}
let exp_keys: Vec<IndexLabel> = groups.keys().map(|&k| IndexLabel::Int64(k)).collect();
let exp_sum: Vec<Scalar> = groups
.values()
.map(|vs| Scalar::Int64(vs.iter().sum()))
.collect();
let exp_count: Vec<Scalar> = groups
.values()
.map(|vs| Scalar::Int64(vs.len() as i64))
.collect();
let exp_min: Vec<Scalar> = groups
.values()
.map(|vs| Scalar::Int64(*vs.iter().min().unwrap()))
.collect();
let exp_max: Vec<Scalar> = groups
.values()
.map(|vs| Scalar::Int64(*vs.iter().max().unwrap()))
.collect();
let ctx = format!("iter={iter} keys={key_vals:?} vals={val_vals:?}");
let opts = || GroupByOptions::default();
let pol = RuntimePolicy::strict();
let mut led = EvidenceLedger::new();
let s = groupby_sum(&keys, &values, opts(), &pol, &mut led).expect("sum");
assert_eq!(s.index().labels(), exp_keys, "sum keys {ctx}");
assert_eq!(s.values(), exp_sum.as_slice(), "sum vals {ctx}");
let c = groupby_count(&keys, &values, opts(), &pol, &mut led).expect("count");
assert_eq!(c.values(), exp_count.as_slice(), "count vals {ctx}");
let mn = groupby_min(&keys, &values, opts(), &pol, &mut led).expect("min");
assert_eq!(mn.values(), exp_min.as_slice(), "min vals {ctx}");
let mx = groupby_max(&keys, &values, opts(), &pol, &mut led).expect("max");
assert_eq!(mx.values(), exp_max.as_slice(), "max vals {ctx}");
}
}
#[test]
fn dense_int64_groupby_first_last_matches_handcomputed_oracle_ypgw6() {
use std::collections::BTreeMap;
let mut state: u64 = 0x6b1e_55ed_a17a_c0de;
let mut next = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(state >> 33) as u32
};
for iter in 0..1200u32 {
let n = (next() % 14) as usize + 1;
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let key_vals: Vec<i64> = (0..n).map(|_| (next() % 5) as i64 - 2).collect();
let val_vals: Vec<i64> = (0..n).map(|_| (next() % 41) as i64 - 20).collect();
let keys = Series::from_values(
"k",
idx.clone(),
key_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.expect("keys");
let values = Series::from_values(
"v",
idx,
val_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.expect("values");
let mut groups: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
for (k, v) in key_vals.iter().zip(val_vals.iter()) {
groups.entry(*k).or_default().push(*v);
}
let exp_first: Vec<Scalar> = groups.values().map(|vs| Scalar::Int64(vs[0])).collect();
let exp_last: Vec<Scalar> = groups
.values()
.map(|vs| Scalar::Int64(*vs.last().unwrap()))
.collect();
let exp_keys: Vec<IndexLabel> = groups.keys().map(|&k| IndexLabel::Int64(k)).collect();
let ctx = format!("iter={iter} keys={key_vals:?} vals={val_vals:?}");
let pol = RuntimePolicy::strict();
let mut led = EvidenceLedger::new();
let f = groupby_first(&keys, &values, GroupByOptions::default(), &pol, &mut led)
.expect("first");
assert_eq!(f.index().labels(), exp_keys, "first keys {ctx}");
assert_eq!(f.values(), exp_first.as_slice(), "first vals {ctx}");
let l = groupby_last(&keys, &values, GroupByOptions::default(), &pol, &mut led)
.expect("last");
assert_eq!(l.values(), exp_last.as_slice(), "last vals {ctx}");
}
}
#[test]
fn dense_int64_groupby_nunique_matches_handcomputed_oracle_xnbl7() {
use std::collections::{BTreeMap, BTreeSet};
let mut state: u64 = 0x09e2_177b_1dea_d5e7_u64.wrapping_mul(3);
let mut next = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(state >> 33) as u32
};
for iter in 0..1200u32 {
let n = (next() % 14) as usize + 1;
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let key_vals: Vec<i64> = (0..n).map(|_| (next() % 5) as i64 - 2).collect();
let val_vals: Vec<i64> = (0..n).map(|_| (next() % 6) as i64).collect();
let keys = Series::from_values(
"k",
idx.clone(),
key_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.expect("keys");
let values = Series::from_values(
"v",
idx,
val_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.expect("values");
let mut groups: BTreeMap<i64, BTreeSet<i64>> = BTreeMap::new();
for (k, v) in key_vals.iter().zip(val_vals.iter()) {
groups.entry(*k).or_default().insert(*v);
}
let exp_keys: Vec<IndexLabel> = groups.keys().map(|&k| IndexLabel::Int64(k)).collect();
let exp_nunique: Vec<Scalar> = groups
.values()
.map(|set| Scalar::Int64(set.len() as i64))
.collect();
let ctx = format!("iter={iter} keys={key_vals:?} vals={val_vals:?}");
let mut led = EvidenceLedger::new();
let out = groupby_nunique(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut led,
)
.expect("nunique");
assert_eq!(out.index().labels(), exp_keys, "nunique keys {ctx}");
assert_eq!(out.values(), exp_nunique.as_slice(), "nunique vals {ctx}");
}
}
#[test]
fn dense_int64_groupby_prod_matches_handcomputed_oracle_ybda2() {
use std::collections::BTreeMap;
let mut state: u64 = 0x70d_face_b00c_1357u64.wrapping_mul(5);
let mut next = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(state >> 33) as u32
};
for iter in 0..1200u32 {
let n = (next() % 12) as usize + 1;
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let key_vals: Vec<i64> = (0..n).map(|_| (next() % 5) as i64 - 2).collect();
let val_vals: Vec<i64> = (0..n).map(|_| (next() % 3) as i64).collect();
let keys = Series::from_values(
"k",
idx.clone(),
key_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.expect("keys");
let values = Series::from_values(
"v",
idx,
val_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.expect("values");
let mut groups: BTreeMap<i64, i64> = BTreeMap::new();
let mut keys_seen: BTreeMap<i64, ()> = BTreeMap::new();
for (k, v) in key_vals.iter().zip(val_vals.iter()) {
keys_seen.entry(*k).or_default();
let e = groups.entry(*k).or_insert(1);
*e *= *v;
}
let exp_keys: Vec<IndexLabel> =
keys_seen.keys().map(|&k| IndexLabel::Int64(k)).collect();
let exp_prod: Vec<Scalar> = groups.values().map(|&p| Scalar::Int64(p)).collect();
let ctx = format!("iter={iter} keys={key_vals:?} vals={val_vals:?}");
let mut led = EvidenceLedger::new();
let out = groupby_prod(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut led,
)
.expect("prod");
assert_eq!(out.index().labels(), exp_keys, "prod keys {ctx}");
assert_eq!(out.values(), exp_prod.as_slice(), "prod vals {ctx}");
}
}
#[test]
fn groupby_order_invariant_aggregations_q60t7() {
let mut s: u64 = 0x0d2e_4c91_a17a_5e7f;
let mut next = || {
s = s
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(s >> 33) as u32
};
use super::GroupByError;
type GbFn = fn(
&Series,
&Series,
GroupByOptions,
&RuntimePolicy,
&mut EvidenceLedger,
) -> Result<Series, GroupByError>;
let aggs: [(&str, GbFn); 5] = [
("sum", groupby_sum),
("count", groupby_count),
("min", groupby_min),
("max", groupby_max),
("prod", groupby_prod),
];
for iter in 0..1000u32 {
let n = (next() % 12) as usize + 1;
let key_vals: Vec<i64> = (0..n).map(|_| (next() % 5) as i64 - 2).collect();
let val_vals: Vec<i64> = (0..n).map(|_| (next() % 3) as i64).collect();
let mk = |keyv: &[i64], valv: &[i64]| {
let idx: Vec<IndexLabel> = (0..keyv.len() as i64).map(IndexLabel::Int64).collect();
let k = Series::from_values(
"k",
idx.clone(),
keyv.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
)
.unwrap();
let v = Series::from_values(
"v",
idx,
valv.iter().copied().map(Scalar::Int64).collect::<Vec<_>>(),
)
.unwrap();
(k, v)
};
let (k1, v1) = mk(&key_vals, &val_vals);
let mut rk = key_vals.clone();
let mut rv = val_vals.clone();
rk.reverse();
rv.reverse();
let (k2, v2) = mk(&rk, &rv);
for (name, f) in aggs {
let mut l1 = EvidenceLedger::new();
let mut l2 = EvidenceLedger::new();
let a = f(
&k1,
&v1,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut l1,
)
.expect("agg orig");
let b = f(
&k2,
&v2,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut l2,
)
.expect("agg rev");
assert_eq!(
a.index().labels(),
b.index().labels(),
"{name} keys order-invariance iter={iter} keys={key_vals:?}"
);
assert_eq!(
a.values(),
b.values(),
"{name} vals order-invariance iter={iter} keys={key_vals:?} vals={val_vals:?}"
);
}
}
}
#[test]
fn groupby_size_sum_equals_n_5cb23() {
let mut s: u64 = 0x4c0b_0c2d_2d3e_4f50;
let mut next = || {
s = s
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(s >> 33) as u32
};
let pol = RuntimePolicy::strict();
for iter in 0..400u32 {
let n = (next() % 20) as usize + 1;
let keys: Vec<i64> = (0..n).map(|_| (next() % 4) as i64).collect();
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let ks = Series::from_values(
"k",
idx.clone(),
keys.iter().map(|&x| Scalar::Int64(x)).collect::<Vec<_>>(),
)
.unwrap();
let vs = Series::from_values(
"v",
idx,
(0..n).map(|i| Scalar::Int64(i as i64)).collect::<Vec<_>>(),
)
.unwrap();
let mut l = EvidenceLedger::new();
let size = groupby_size(&ks, &vs, GroupByOptions::default(), &pol, &mut l).unwrap();
let total: i64 = size
.values()
.iter()
.map(|c| match c {
Scalar::Int64(x) => *x,
Scalar::Float64(x) => *x as i64,
_ => 0,
})
.sum();
assert_eq!(total, n as i64, "sum(size)==n iter={iter}");
}
}
#[test]
fn groupby_min_le_mean_le_max_3obe6() {
let mut s: u64 = 0x4c0b_0b2c_2d3e_4f50;
let mut next = || {
s = s
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(s >> 33) as u32
};
let getf = |c: &[Scalar]| -> Vec<f64> {
c.iter()
.map(|v| match v {
Scalar::Int64(x) => *x as f64,
Scalar::Float64(x) => *x,
_ => f64::NAN,
})
.collect()
};
let pol = RuntimePolicy::strict();
for iter in 0..400u32 {
let n = (next() % 16) as usize + 1;
let keys: Vec<i64> = (0..n).map(|_| (next() % 4) as i64).collect();
let vals: Vec<f64> = (0..n).map(|_| (next() % 200) as f64 / 3.0 - 33.0).collect();
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let ks = Series::from_values(
"k",
idx.clone(),
keys.iter().map(|&x| Scalar::Int64(x)).collect::<Vec<_>>(),
)
.unwrap();
let vs = Series::from_values(
"v",
idx,
vals.iter().map(|&x| Scalar::Float64(x)).collect::<Vec<_>>(),
)
.unwrap();
let mut l = EvidenceLedger::new();
let mins = getf(
groupby_min(&ks, &vs, GroupByOptions::default(), &pol, &mut l)
.unwrap()
.values(),
);
let means = getf(
groupby_mean(&ks, &vs, GroupByOptions::default(), &pol, &mut l)
.unwrap()
.values(),
);
let maxs = getf(
groupby_max(&ks, &vs, GroupByOptions::default(), &pol, &mut l)
.unwrap()
.values(),
);
for g in 0..mins.len() {
assert!(mins[g] <= means[g] + 1e-9, "min<=mean iter={iter} g={g}");
assert!(means[g] <= maxs[g] + 1e-9, "mean<=max iter={iter} g={g}");
}
}
}
#[test]
fn groupby_sum_equals_mean_times_count_0czr8() {
let mut s: u64 = 0x4c0c_0b1c_2d3e_4f50;
let mut next = || {
s = s
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(s >> 33) as u32
};
let getf = |c: &[Scalar]| -> Vec<f64> {
c.iter()
.map(|v| match v {
Scalar::Int64(x) => *x as f64,
Scalar::Float64(x) => *x,
_ => f64::NAN,
})
.collect()
};
let pol = RuntimePolicy::strict();
for iter in 0..400u32 {
let n = (next() % 16) as usize + 1;
let keys: Vec<i64> = (0..n).map(|_| (next() % 4) as i64).collect();
let vals: Vec<f64> = (0..n).map(|_| (next() % 100) as f64 / 3.0).collect();
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let ks = Series::from_values(
"k",
idx.clone(),
keys.iter().map(|&x| Scalar::Int64(x)).collect::<Vec<_>>(),
)
.unwrap();
let vs = Series::from_values(
"v",
idx,
vals.iter().map(|&x| Scalar::Float64(x)).collect::<Vec<_>>(),
)
.unwrap();
let mut l = EvidenceLedger::new();
let sums = getf(
groupby_sum(&ks, &vs, GroupByOptions::default(), &pol, &mut l)
.unwrap()
.values(),
);
let means = getf(
groupby_mean(&ks, &vs, GroupByOptions::default(), &pol, &mut l)
.unwrap()
.values(),
);
let counts = getf(
groupby_count(&ks, &vs, GroupByOptions::default(), &pol, &mut l)
.unwrap()
.values(),
);
assert_eq!(sums.len(), means.len(), "len iter={iter}");
assert_eq!(sums.len(), counts.len(), "len iter={iter}");
for g in 0..sums.len() {
assert!(
(sums[g] - means[g] * counts[g]).abs() < 1e-6,
"sum==mean*count iter={iter} g={g}"
);
}
}
}
#[test]
fn groupby_count_vs_size_null_values_z1o82() {
let idx: Vec<IndexLabel> = (0..3i64).map(IndexLabel::Int64).collect();
let keys = Series::from_values(
"k",
idx.clone(),
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"v",
idx,
vec![
Scalar::Float64(10.0),
Scalar::Float64(f64::NAN),
Scalar::Float64(20.0),
],
)
.unwrap();
let pol = RuntimePolicy::strict();
let mut l1 = EvidenceLedger::new();
let mut l2 = EvidenceLedger::new();
let count =
groupby_count(&keys, &values, GroupByOptions::default(), &pol, &mut l1).unwrap();
let size = groupby_size(&keys, &values, GroupByOptions::default(), &pol, &mut l2).unwrap();
assert_eq!(
count.values(),
&[Scalar::Int64(1), Scalar::Int64(1)],
"count excludes NaN"
);
assert_eq!(
size.values(),
&[Scalar::Int64(2), Scalar::Int64(1)],
"size counts all rows"
);
}
#[test]
fn groupby_drops_null_key_rows_tr1un() {
let idx: Vec<IndexLabel> = (0..4i64).map(IndexLabel::Int64).collect();
let keys = Series::from_values(
"k",
idx.clone(),
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Null(NullKind::Null),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"v",
idx,
vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
Scalar::Int64(40),
],
)
.unwrap();
let mut led = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut led,
)
.unwrap();
assert_eq!(out.len(), 2, "null-key group dropped");
assert_eq!(
out.index().labels(),
&[
IndexLabel::Utf8("a".to_owned()),
IndexLabel::Utf8("b".to_owned())
]
);
assert_eq!(
out.values(),
&[Scalar::Int64(40), Scalar::Int64(40)],
"sums exclude null-key value 20"
);
}
#[test]
fn groupby_var_std_two_pass_oracle_7io1l() {
use std::collections::BTreeMap;
let mut st: u64 = 0x7a20_1c0d_2b3e_4f50;
let mut next = || {
st = st
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(st >> 33) as u32
};
let num = |s: &Scalar| -> f64 {
match s {
Scalar::Float64(x) => *x,
Scalar::Int64(x) => *x as f64,
_ => f64::NAN,
}
};
for iter in 0..800u32 {
let n = (next() % 12) as usize + 1;
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let key_vals: Vec<i64> = (0..n).map(|_| (next() % 4) as i64 - 1).collect();
let val_vals: Vec<i64> = (0..n).map(|_| (next() % 21) as i64 - 10).collect();
let keys = Series::from_values(
"k",
idx.clone(),
key_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.unwrap();
let values = Series::from_values(
"v",
idx,
val_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.unwrap();
let mut groups: BTreeMap<i64, Vec<f64>> = BTreeMap::new();
for (k, v) in key_vals.iter().zip(val_vals.iter()) {
groups.entry(*k).or_default().push(*v as f64);
}
let exp_var: Vec<f64> = groups
.values()
.map(|vs| {
if vs.len() < 2 {
f64::NAN
} else {
let m = vs.iter().sum::<f64>() / vs.len() as f64;
vs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (vs.len() as f64 - 1.0)
}
})
.collect();
let pol = RuntimePolicy::strict();
let mut led = EvidenceLedger::new();
let var = groupby_var(&keys, &values, GroupByOptions::default(), &pol, &mut led)
.expect("var");
let std = groupby_std(&keys, &values, GroupByOptions::default(), &pol, &mut led)
.expect("std");
let ctx = format!("iter={iter} keys={key_vals:?} vals={val_vals:?}");
for (i, ev) in exp_var.iter().enumerate() {
let gv = num(&var.values()[i]);
let gs = num(&std.values()[i]);
if ev.is_nan() {
assert!(gv.is_nan(), "var NaN {ctx} i={i}");
assert!(gs.is_nan(), "std NaN {ctx} i={i}");
} else {
assert!((gv - ev).abs() < 1e-7, "var {ctx} i={i}: {gv} vs {ev}");
assert!((gs - ev.sqrt()).abs() < 1e-7, "std {ctx} i={i}");
}
}
}
}
#[test]
fn groupby_median_matches_sorted_middle_oracle_k3awo() {
use std::collections::BTreeMap;
let mut st: u64 = 0x6ed1_a40c_3b2a_1908;
let mut next = || {
st = st
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(st >> 33) as u32
};
for iter in 0..1000u32 {
let n = (next() % 12) as usize + 1;
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let key_vals: Vec<i64> = (0..n).map(|_| (next() % 4) as i64 - 1).collect();
let val_vals: Vec<i64> = (0..n).map(|_| (next() % 21) as i64 - 10).collect();
let keys = Series::from_values(
"k",
idx.clone(),
key_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.unwrap();
let values = Series::from_values(
"v",
idx,
val_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.unwrap();
let mut groups: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
for (k, v) in key_vals.iter().zip(val_vals.iter()) {
groups.entry(*k).or_default().push(*v);
}
let exp_keys: Vec<IndexLabel> = groups.keys().map(|&k| IndexLabel::Int64(k)).collect();
let exp_median: Vec<f64> = groups
.values()
.map(|vs| {
let mut s = vs.clone();
s.sort_unstable();
let m = s.len() / 2;
if s.len() % 2 == 1 {
s[m] as f64
} else {
(s[m - 1] + s[m]) as f64 / 2.0
}
})
.collect();
let ctx = format!("iter={iter} keys={key_vals:?} vals={val_vals:?}");
let mut led = EvidenceLedger::new();
let out = groupby_median(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut led,
)
.expect("median");
assert_eq!(out.index().labels(), exp_keys, "median keys {ctx}");
for (i, got) in out.values().iter().enumerate() {
let g = match got {
Scalar::Float64(x) => *x,
Scalar::Int64(x) => *x as f64,
_ => f64::NAN,
};
assert!(
(g - exp_median[i]).abs() < 1e-9,
"median val {ctx} i={i}: {g} vs {}",
exp_median[i]
);
}
}
}
#[test]
fn dense_int64_groupby_sparse_keys_matches_oracle_u4c5a() {
use std::collections::BTreeMap;
const WIDE_KEYS: [i64; 6] = [0, 1, -1, 1_000_000, -500_000, 7];
let mut st: u64 = 0x5a2e_5e00_4c5a_d00d;
let mut next = || {
st = st
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(st >> 33) as u32
};
for iter in 0..1000u32 {
let n = (next() % 14) as usize + 1;
let idx: Vec<IndexLabel> = (0..n as i64).map(IndexLabel::Int64).collect();
let key_vals: Vec<i64> = (0..n)
.map(|_| WIDE_KEYS[(next() as usize) % WIDE_KEYS.len()])
.collect();
let val_vals: Vec<i64> = (0..n).map(|_| (next() % 21) as i64 - 10).collect();
let keys = Series::from_values(
"k",
idx.clone(),
key_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.unwrap();
let values = Series::from_values(
"v",
idx,
val_vals
.iter()
.copied()
.map(Scalar::Int64)
.collect::<Vec<_>>(),
)
.unwrap();
let mut groups: BTreeMap<i64, Vec<i64>> = BTreeMap::new();
for (k, v) in key_vals.iter().zip(val_vals.iter()) {
groups.entry(*k).or_default().push(*v);
}
let exp_keys: Vec<IndexLabel> = groups.keys().map(|&k| IndexLabel::Int64(k)).collect();
let exp_sum: Vec<Scalar> = groups
.values()
.map(|vs| Scalar::Int64(vs.iter().sum()))
.collect();
let exp_count: Vec<Scalar> = groups
.values()
.map(|vs| Scalar::Int64(vs.len() as i64))
.collect();
let ctx = format!("iter={iter} keys={key_vals:?}");
let pol = RuntimePolicy::strict();
let mut led = EvidenceLedger::new();
let sum = groupby_sum(&keys, &values, GroupByOptions::default(), &pol, &mut led)
.expect("sum");
assert_eq!(sum.index().labels(), exp_keys, "sparse sum keys {ctx}");
assert_eq!(sum.values(), exp_sum.as_slice(), "sparse sum vals {ctx}");
let cnt = groupby_count(&keys, &values, GroupByOptions::default(), &pol, &mut led)
.expect("count");
assert_eq!(
cnt.values(),
exp_count.as_slice(),
"sparse count vals {ctx}"
);
}
}
#[test]
fn groupby_sum_concatenates_string_values_like_pandas() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("x".to_owned()),
Scalar::Null(NullKind::Null),
Scalar::Utf8("y".to_owned()),
Scalar::Utf8("z".to_owned()),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(
out.values(),
&[Scalar::Utf8("xy".to_owned()), Scalar::Utf8("z".to_owned()),]
);
}
#[test]
fn groupby_sum_sort_false_preserves_first_seen_key_order() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions {
sort: false,
..GroupByOptions::default()
},
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels(), &["b".into(), "a".into()]);
assert_eq!(out.values(), &[Scalar::Int64(4), Scalar::Int64(6)]);
}
#[test]
fn groupby_sum_records_runtime_admission_evidence() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
)
.expect("values");
let policy = RuntimePolicy::strict();
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.expect("groupby");
assert_eq!(out.values(), &[Scalar::Int64(4), Scalar::Int64(2)]);
assert_eq!(ledger.records().len(), 1);
}
#[test]
fn groupby_sum_merges_negative_zero_and_zero_float_keys() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Float64(-0.0),
Scalar::Float64(1.0),
Scalar::Float64(0.0),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions {
sort: false,
..GroupByOptions::default()
},
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels().len(), 2);
assert_eq!(out.index().labels()[1], "1".into());
assert_eq!(out.values(), &[Scalar::Int64(5), Scalar::Int64(2)]);
}
#[test]
fn groupby_agg_records_runtime_admission_evidence() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("y".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![Scalar::Int64(5), Scalar::Int64(6), Scalar::Int64(7)],
)
.expect("values");
let policy = RuntimePolicy::strict();
let mut ledger = EvidenceLedger::new();
let out = groupby_agg(
&keys,
&values,
AggFunc::Count,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.expect("groupby agg");
assert_eq!(out.values(), &[Scalar::Int64(2), Scalar::Int64(1)]);
assert_eq!(ledger.records().len(), 1);
}
#[test]
fn groupby_sum_duplicate_equal_index_preserves_alignment_behavior() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 0_i64.into(), 1_i64.into()],
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 0_i64.into(), 1_i64.into()],
vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions {
sort: false,
..GroupByOptions::default()
},
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(out.values(), &[Scalar::Int64(6), Scalar::Int64(3)]);
}
#[test]
fn groupby_sum_int_dense_path_sorts_keys_by_default() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(10),
Scalar::Int64(5),
Scalar::Int64(10),
Scalar::Int64(-2),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(
out.index().labels(),
&[(-2_i64).into(), 5_i64.into(), 10_i64.into()]
);
assert_eq!(
out.values(),
&[Scalar::Int64(4), Scalar::Int64(2), Scalar::Int64(4),]
);
}
#[test]
fn groupby_sum_int_dense_path_preserves_first_seen_order_when_sort_disabled() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(10),
Scalar::Int64(5),
Scalar::Int64(10),
Scalar::Int64(-2),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions {
sort: false,
..GroupByOptions::default()
},
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(
out.index().labels(),
&[10_i64.into(), 5_i64.into(), (-2_i64).into()]
);
assert_eq!(
out.values(),
&[Scalar::Int64(4), Scalar::Int64(2), Scalar::Int64(4)]
);
}
#[test]
fn dense_int64_value_path_preserves_sort_and_first_seen_order() {
let keys = vec![
Scalar::Int64(10),
Scalar::Int64(5),
Scalar::Int64(10),
Scalar::Int64(-2),
];
let values = vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
];
let (sorted_index, sorted_values) =
try_groupby_sum_dense_int64_values(&keys, &values, true, true).expect("dense");
assert_eq!(
sorted_index,
vec![(-2_i64).into(), 5_i64.into(), 10_i64.into()]
);
assert_eq!(
sorted_values,
vec![Scalar::Int64(4), Scalar::Int64(2), Scalar::Int64(4)]
);
let (first_seen_index, first_seen_values) =
try_groupby_sum_dense_int64_values(&keys, &values, true, false).expect("dense");
assert_eq!(
first_seen_index,
vec![10_i64.into(), 5_i64.into(), (-2_i64).into()]
);
assert_eq!(
first_seen_values,
vec![Scalar::Int64(4), Scalar::Int64(2), Scalar::Int64(4)]
);
}
#[test]
fn groupby_sum_dense_int64_value_path_preserves_bool_and_overflow() {
let bool_keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(2)],
)
.expect("keys");
let bool_values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&bool_keys,
&bool_values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels(), &[1_i64.into(), 2_i64.into()]);
assert_eq!(out.values(), &[Scalar::Int64(1), Scalar::Int64(1)]);
let overflow_keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Int64(7), Scalar::Int64(7)],
)
.expect("keys");
let overflow_values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Int64(i64::MAX), Scalar::Int64(1)],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&overflow_keys,
&overflow_values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels(), &[7_i64.into()]);
assert_eq!(
out.values(),
&[Scalar::Float64((i128::from(i64::MAX) + 1) as f64)]
);
}
#[test]
fn groupby_sum_dropna_false_keeps_null_group_sorted_last() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Null(NullKind::Null),
Scalar::Int64(10),
Scalar::Int64(10),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions {
dropna: false,
..GroupByOptions::default()
},
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(
out.index().labels(),
&[10_i64.into(), IndexLabel::Null(NullKind::NaN)]
);
assert_eq!(out.values(), &[Scalar::Int64(5), Scalar::Int64(1)]);
}
#[test]
fn groupby_sum_int_keys_generic_path_wide_span() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(0),
Scalar::Int64(100_000), Scalar::Int64(0),
Scalar::Int64(100_000),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions {
sort: false,
..GroupByOptions::default()
},
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels(), &[0_i64.into(), 100_000_i64.into()]);
assert_eq!(out.values(), &[Scalar::Int64(4), Scalar::Int64(6)]);
}
#[test]
fn groupby_sum_single_group() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Utf8("only".to_owned()),
Scalar::Utf8("only".to_owned()),
Scalar::Utf8("only".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels(), &["only".into()]);
assert_eq!(out.values(), &[Scalar::Int64(60)]);
}
#[test]
fn groupby_sum_empty_input() {
let keys = Series::from_values("key", Vec::<IndexLabel>::new(), Vec::<Scalar>::new())
.expect("keys");
let values = Series::from_values("value", Vec::<IndexLabel>::new(), Vec::<Scalar>::new())
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels().len(), 0);
assert_eq!(out.values().len(), 0);
}
#[test]
fn groupby_sum_missing_values_in_sum() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("b".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(5),
Scalar::Null(NullKind::Null),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::Null),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(out.values(), &[Scalar::Float64(5.0), Scalar::Float64(0.0)]);
}
#[test]
fn groupby_sum_large_cardinality() {
let n = 10_000usize;
let labels: Vec<IndexLabel> = (0..n).map(|i| IndexLabel::Int64(i as i64)).collect();
let key_values: Vec<Scalar> = (0..n).map(|i| Scalar::Utf8(format!("key_{}", i))).collect();
let sum_values: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
let keys = Series::from_values("key", labels.clone(), key_values).expect("keys");
let values = Series::from_values("value", labels, sum_values).expect("values");
let mut ledger = EvidenceLedger::new();
let out = groupby_sum(
&keys,
&values,
GroupByOptions {
sort: false,
..GroupByOptions::default()
},
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("groupby");
assert_eq!(out.index().labels().len(), n);
assert_eq!(out.values().len(), n);
assert_eq!(out.values()[0], Scalar::Int64(0));
assert_eq!(out.values()[999], Scalar::Int64(999));
assert_eq!(out.values()[9999], Scalar::Int64(9999));
}
#[test]
fn groupby_isomorphism_generic_vs_dense() {
use fp_index::IndexLabel;
let dense_keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(5),
Scalar::Int64(3),
Scalar::Int64(5),
Scalar::Int64(3),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
Scalar::Int64(40),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let dense_out = groupby_sum(
&dense_keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("dense groupby");
let generic_keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("5".to_owned()),
Scalar::Utf8("3".to_owned()),
Scalar::Utf8("5".to_owned()),
Scalar::Utf8("3".to_owned()),
],
)
.expect("keys");
let generic_out = groupby_sum(
&generic_keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.expect("generic groupby");
assert_eq!(dense_out.values(), generic_out.values());
assert_eq!(
dense_out.index().labels().len(),
generic_out.index().labels().len()
);
assert_eq!(
dense_out.index().labels(),
&[IndexLabel::Int64(3), IndexLabel::Int64(5)]
);
assert_eq!(
generic_out.index().labels(),
&[
IndexLabel::Utf8("3".to_owned()),
IndexLabel::Utf8("5".to_owned())
]
);
}
#[test]
fn arena_groupby_matches_global_allocator_behavior() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let global = groupby_sum_with_options(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
GroupByExecutionOptions {
use_arena: false,
arena_budget_bytes: 0,
},
)
.expect("global groupby");
let arena = groupby_sum_with_options(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
GroupByExecutionOptions::default(),
)
.expect("arena groupby");
assert_eq!(arena.index().labels(), global.index().labels());
assert_eq!(arena.values(), global.values());
}
#[test]
fn arena_groupby_falls_back_when_budget_too_small() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let options = GroupByExecutionOptions {
use_arena: true,
arena_budget_bytes: 1,
};
let (fallback_out, trace) = groupby_sum_with_trace(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
options,
)
.expect("fallback groupby");
let global_out = groupby_sum_with_options(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
GroupByExecutionOptions {
use_arena: false,
arena_budget_bytes: 0,
},
)
.expect("global groupby");
assert_eq!(fallback_out.index().labels(), global_out.index().labels());
assert_eq!(fallback_out.values(), global_out.values());
assert!(!trace.used_arena);
assert!(trace.estimated_bytes > options.arena_budget_bytes);
}
#[test]
fn arena_groupby_dense_path_matches_global() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(10),
Scalar::Int64(5),
Scalar::Int64(10),
Scalar::Int64(-2),
],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let global = groupby_sum_with_options(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
GroupByExecutionOptions {
use_arena: false,
arena_budget_bytes: 0,
},
)
.expect("global groupby");
let arena = groupby_sum_with_options(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
GroupByExecutionOptions::default(),
)
.expect("arena groupby");
assert_eq!(arena.index().labels(), global.index().labels());
assert_eq!(arena.values(), global.values());
}
#[test]
fn arena_groupby_stable_across_repeated_operations() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Utf8("x".to_owned()), Scalar::Utf8("y".to_owned())],
)
.expect("keys");
let values = Series::from_values(
"value",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Int64(10), Scalar::Int64(20)],
)
.expect("values");
let mut ledger = EvidenceLedger::new();
let options = GroupByExecutionOptions::default();
for _ in 0..1_000 {
let out = groupby_sum_with_options(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
options,
)
.expect("arena groupby");
assert_eq!(out.index().labels().len(), 2);
assert_eq!(out.values(), &[Scalar::Int64(10), Scalar::Int64(20)]);
}
}
use super::{
AggFunc, groupby_agg, groupby_count, groupby_first, groupby_last, groupby_max,
groupby_mean, groupby_median, groupby_min, groupby_std, groupby_var,
};
fn make_grouped_data() -> (Series, Series) {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
Scalar::Int64(40),
],
)
.unwrap();
(keys, values)
}
#[test]
fn groupby_mean_basic() {
let (keys, values) = make_grouped_data();
let mut ledger = EvidenceLedger::new();
let out = groupby_mean(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(
out.values(),
&[Scalar::Float64(20.0), Scalar::Float64(30.0)]
);
assert_eq!(out.name(), "mean");
}
#[test]
fn groupby_count_basic() {
let (keys, values) = make_grouped_data();
let mut ledger = EvidenceLedger::new();
let out = groupby_count(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(out.values(), &[Scalar::Int64(2), Scalar::Int64(2)]);
assert_eq!(out.name(), "count");
}
#[test]
fn groupby_min_basic() {
let (keys, values) = make_grouped_data();
let mut ledger = EvidenceLedger::new();
let out = groupby_min(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(out.values(), &[Scalar::Int64(10), Scalar::Int64(20)]);
assert_eq!(out.name(), "min");
}
#[test]
fn groupby_max_basic() {
let (keys, values) = make_grouped_data();
let mut ledger = EvidenceLedger::new();
let out = groupby_max(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(out.values(), &[Scalar::Int64(30), Scalar::Int64(40)]);
assert_eq!(out.name(), "max");
}
#[test]
fn groupby_min_max_utf8_keys_skip_missing_and_keep_order() {
let keys = Series::from_values(
"key",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
5_i64.into(),
],
vec![
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("c".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
5_i64.into(),
],
vec![
Scalar::Int64(3),
Scalar::Null(NullKind::Null),
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(5),
Scalar::Int64(2),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let min_sorted = groupby_min(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let max_sorted = groupby_max(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(
min_sorted.index().labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(
max_sorted.index().labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(
&min_sorted.values()[..2],
&[Scalar::Int64(5), Scalar::Int64(1)]
);
assert_eq!(
&max_sorted.values()[..2],
&[Scalar::Int64(5), Scalar::Int64(3)]
);
assert!(min_sorted.values()[2].is_missing());
assert!(max_sorted.values()[2].is_missing());
let first_seen = GroupByOptions {
sort: false,
..GroupByOptions::default()
};
let min_unsorted = groupby_min(
&keys,
&values,
first_seen,
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let max_unsorted = groupby_max(
&keys,
&values,
first_seen,
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(
min_unsorted.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
max_unsorted.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
&min_unsorted.values()[..2],
&[Scalar::Int64(1), Scalar::Int64(5)]
);
assert_eq!(
&max_unsorted.values()[..2],
&[Scalar::Int64(3), Scalar::Int64(5)]
);
assert!(min_unsorted.values()[2].is_missing());
assert!(max_unsorted.values()[2].is_missing());
}
#[test]
fn groupby_min_max_object_key_incomparable_values_return_nan() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Utf8("a".into()), Scalar::Utf8("a".into())],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Utf8("x".into()), Scalar::Int64(1)],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out_min = groupby_min(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let out_max = groupby_max(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out_min.index().labels(), &["a".into()]);
assert_eq!(out_max.index().labels(), &["a".into()]);
assert!(out_min.values()[0].is_missing());
assert!(out_max.values()[0].is_missing());
}
#[test]
fn groupby_first_basic() {
let (keys, values) = make_grouped_data();
let mut ledger = EvidenceLedger::new();
let out = groupby_first(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(out.values(), &[Scalar::Int64(10), Scalar::Int64(20)]);
assert_eq!(out.name(), "first");
}
#[test]
fn groupby_last_basic() {
let (keys, values) = make_grouped_data();
let mut ledger = EvidenceLedger::new();
let out = groupby_last(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(out.values(), &[Scalar::Int64(30), Scalar::Int64(40)]);
assert_eq!(out.name(), "last");
}
#[test]
fn groupby_first_last_utf8_keys_skip_missing_and_keep_order() {
let keys = Series::from_values(
"key",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
5_i64.into(),
],
vec![
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("c".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
5_i64.into(),
],
vec![
Scalar::Null(NullKind::Null),
Scalar::Int64(10),
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(5),
Scalar::Int64(2),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let first_sorted = groupby_first(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let last_sorted = groupby_last(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(
first_sorted.index().labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(
last_sorted.index().labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(
&first_sorted.values()[..2],
&[Scalar::Int64(10), Scalar::Int64(1)]
);
assert_eq!(
&last_sorted.values()[..2],
&[Scalar::Int64(5), Scalar::Int64(2)]
);
assert!(first_sorted.values()[2].is_missing());
assert!(last_sorted.values()[2].is_missing());
let first_seen = GroupByOptions {
sort: false,
..GroupByOptions::default()
};
let first_unsorted = groupby_first(
&keys,
&values,
first_seen,
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let last_unsorted = groupby_last(
&keys,
&values,
first_seen,
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(
first_unsorted.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
last_unsorted.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
&first_unsorted.values()[..2],
&[Scalar::Int64(1), Scalar::Int64(10)]
);
assert_eq!(
&last_unsorted.values()[..2],
&[Scalar::Int64(2), Scalar::Int64(5)]
);
assert!(first_unsorted.values()[2].is_missing());
assert!(last_unsorted.values()[2].is_missing());
}
#[test]
fn groupby_first_last_object_values_preserve_selected_scalar() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Utf8("a".into()), Scalar::Utf8("a".into())],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Utf8("x".into()), Scalar::Int64(7)],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out_first = groupby_first(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let out_last = groupby_last(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out_first.values(), &[Scalar::Utf8("x".into())]);
assert_eq!(out_last.values(), &[Scalar::Int64(7)]);
}
#[test]
fn groupby_agg_sum_matches_dedicated_sum() {
let (keys, values) = make_grouped_data();
let mut ledger = EvidenceLedger::new();
let agg = groupby_agg(
&keys,
&values,
AggFunc::Sum,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let dedicated = groupby_sum(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(agg.index().labels(), dedicated.index().labels());
assert_eq!(agg.values(), dedicated.values());
}
#[test]
fn groupby_agg_sum_prod_utf8_keys_stream_integer_slots() {
let keys = Series::from_values(
"key",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
5_i64.into(),
],
vec![
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("c".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
5_i64.into(),
],
vec![
Scalar::Null(NullKind::Null),
Scalar::Int64(10),
Scalar::Int64(2),
Scalar::Null(NullKind::Null),
Scalar::Int64(5),
Scalar::Int64(3),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let sum_sorted = groupby_agg(
&keys,
&values,
AggFunc::Sum,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let prod_sorted = groupby_agg(
&keys,
&values,
AggFunc::Prod,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(
sum_sorted.index().labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(
prod_sorted.index().labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(
sum_sorted.values(),
&[Scalar::Int64(15), Scalar::Int64(5), Scalar::Int64(0)]
);
assert_eq!(
prod_sorted.values(),
&[Scalar::Int64(50), Scalar::Int64(6), Scalar::Int64(1)]
);
let first_seen = GroupByOptions {
sort: false,
..GroupByOptions::default()
};
let sum_unsorted = groupby_agg(
&keys,
&values,
AggFunc::Sum,
first_seen,
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let prod_unsorted = groupby_agg(
&keys,
&values,
AggFunc::Prod,
first_seen,
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(
sum_unsorted.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
prod_unsorted.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
sum_unsorted.values(),
&[Scalar::Int64(5), Scalar::Int64(15), Scalar::Int64(0)]
);
assert_eq!(
prod_unsorted.values(),
&[Scalar::Int64(6), Scalar::Int64(50), Scalar::Int64(1)]
);
}
#[test]
fn groupby_agg_sum_prod_bool_and_prod_overflow_preserve_fallbacks() {
let bool_keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
],
)
.unwrap();
let bool_values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let bool_sum = groupby_agg(
&bool_keys,
&bool_values,
AggFunc::Sum,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let bool_prod = groupby_agg(
&bool_keys,
&bool_values,
AggFunc::Prod,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(bool_sum.values(), &[Scalar::Int64(1), Scalar::Int64(1)]);
assert_eq!(bool_prod.values(), &[Scalar::Int64(0), Scalar::Int64(1)]);
let overflow_keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Utf8("a".into()), Scalar::Utf8("a".into())],
)
.unwrap();
let overflow_values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Int64(i64::MAX), Scalar::Int64(2)],
)
.unwrap();
let overflow_prod = groupby_agg(
&overflow_keys,
&overflow_values,
AggFunc::Prod,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(
overflow_prod.values(),
&[Scalar::Float64((i64::MAX as f64) * 2.0)]
);
}
#[test]
fn groupby_agg_sum_prod_float64_utf8_keys_stream_counters_2qb1i() {
let keys = Series::from_values(
"key",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
5_i64.into(),
],
vec![
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("c".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
5_i64.into(),
],
vec![
Scalar::Float64(1.5),
Scalar::Float64(2.0),
Scalar::Null(NullKind::NaN),
Scalar::Null(NullKind::Null),
Scalar::Float64(4.0),
Scalar::Float64(-2.0),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let sum_sorted = groupby_agg(
&keys,
&values,
AggFunc::Sum,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let prod_sorted = groupby_agg(
&keys,
&values,
AggFunc::Prod,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(
sum_sorted.index().labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(
prod_sorted.index().labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(
sum_sorted.values(),
&[
Scalar::Float64(6.0),
Scalar::Float64(-0.5),
Scalar::Float64(0.0),
]
);
assert_eq!(
prod_sorted.values(),
&[
Scalar::Float64(8.0),
Scalar::Float64(-3.0),
Scalar::Float64(1.0),
]
);
let first_seen = GroupByOptions {
sort: false,
..GroupByOptions::default()
};
let sum_unsorted = groupby_agg(
&keys,
&values,
AggFunc::Sum,
first_seen,
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let prod_unsorted = groupby_agg(
&keys,
&values,
AggFunc::Prod,
first_seen,
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(
sum_unsorted.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
prod_unsorted.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
sum_unsorted.values(),
&[
Scalar::Float64(-0.5),
Scalar::Float64(6.0),
Scalar::Float64(0.0),
]
);
assert_eq!(
prod_unsorted.values(),
&[
Scalar::Float64(-3.0),
Scalar::Float64(8.0),
Scalar::Float64(1.0),
]
);
}
#[test]
fn groupby_agg_sum_prod_timedelta_fallback_preserved_2qb1i() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Utf8("a".into()), Scalar::Utf8("a".into())],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Timedelta64(2), Scalar::Timedelta64(3)],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let sum = groupby_agg(
&keys,
&values,
AggFunc::Sum,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let prod = groupby_agg(
&keys,
&values,
AggFunc::Prod,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(sum.values(), &[Scalar::Timedelta64(5)]);
assert!(prod.values()[0].is_missing());
}
#[test]
fn groupby_mean_with_nulls_skips_missing() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Int64(10),
Scalar::Null(NullKind::Null),
Scalar::Int64(30),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out = groupby_mean(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.values(), &[Scalar::Float64(20.0)]);
}
#[test]
fn groupby_count_excludes_nulls() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Int64(10),
Scalar::Null(NullKind::Null),
Scalar::Int64(30),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out = groupby_count(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.values(), &[Scalar::Int64(2)]); }
#[test]
fn groupby_min_all_nulls_returns_null() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Utf8("a".into()), Scalar::Utf8("a".into())],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Null(NullKind::Null), Scalar::Null(NullKind::Null)],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out = groupby_min(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert!(out.values()[0].is_missing());
}
#[test]
fn groupby_agg_empty_input() {
let keys =
Series::from_values("key", Vec::<IndexLabel>::new(), Vec::<Scalar>::new()).unwrap();
let values =
Series::from_values("val", Vec::<IndexLabel>::new(), Vec::<Scalar>::new()).unwrap();
let mut ledger = EvidenceLedger::new();
for func in [
AggFunc::Sum,
AggFunc::Mean,
AggFunc::Count,
AggFunc::Min,
AggFunc::Max,
AggFunc::First,
AggFunc::Last,
] {
let out = groupby_agg(
&keys,
&values,
func,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert!(
out.is_empty(),
"empty input should give empty output for {func:?}"
);
}
}
#[test]
fn groupby_agg_sorts_keys_by_default() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("c".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out = groupby_mean(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into(), "c".into()]);
}
#[test]
fn groupby_agg_sort_false_preserves_first_seen_order() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("c".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("a".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out = groupby_mean(
&keys,
&values,
GroupByOptions {
sort: false,
..GroupByOptions::default()
},
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["c".into(), "a".into(), "b".into()]);
}
#[test]
fn groupby_std_basic() {
let (keys, values) = make_grouped_data();
let mut ledger = EvidenceLedger::new();
let out = groupby_std(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert!(
matches!(out.values()[0], Scalar::Float64(_)),
"expected Float64"
);
let a_std = match &out.values()[0] {
Scalar::Float64(v) => *v,
_ => 0.0,
};
assert!((a_std - 200.0_f64.sqrt()).abs() < 1e-10, "a std={a_std}");
assert_eq!(out.name(), "std");
}
#[test]
fn groupby_var_basic() {
let (keys, values) = make_grouped_data();
let mut ledger = EvidenceLedger::new();
let out = groupby_var(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(
out.values(),
&[Scalar::Float64(200.0), Scalar::Float64(200.0)]
);
assert_eq!(out.name(), "var");
}
#[test]
fn groupby_var_std_match_pandas() {
let mut ledger = EvidenceLedger::new();
let idx: Vec<_> = (0..9).map(|i| (i as i64).into()).collect();
let mut kvals = vec![Scalar::Utf8("a".into()); 4];
kvals.extend(vec![Scalar::Utf8("b".into()); 5]);
let keys = Series::from_values("g", idx.clone(), kvals).unwrap();
let values = Series::from_values(
"v",
idx,
[1.0, 2.0, 4.0, 8.0, 1.0, 1.0, 1.0, 5.0, 9.0]
.iter()
.map(|x| Scalar::Float64(*x))
.collect(),
)
.unwrap();
let nums = |s: &Series| -> Vec<f64> {
s.values()
.iter()
.filter_map(|v| {
if let Scalar::Float64(f) = v {
Some(*f)
} else {
None
}
})
.collect()
};
let approx = |a: f64, b: f64, ctx: &str| {
assert!((a - b).abs() < 1e-9, "{ctx}: got {a}, expected {b}");
};
let var = groupby_var(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let vv = nums(&var);
approx(vv[0], 9.583333333333334, "var a");
approx(vv[1], 12.8, "var b");
let std = groupby_std(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
let sv = nums(&std);
approx(sv[0], 3.095_695_936_882_199, "std a");
approx(sv[1], 3.5777087639996634, "std b");
}
#[test]
fn groupby_median_basic() {
let keys = Series::from_values(
"key",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
],
vec![
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("b".into()),
Scalar::Utf8("b".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
],
vec![
Scalar::Int64(10),
Scalar::Int64(20),
Scalar::Int64(30),
Scalar::Int64(5),
Scalar::Int64(15),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out = groupby_median(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(
out.values(),
&[Scalar::Float64(20.0), Scalar::Float64(10.0)]
);
assert_eq!(out.name(), "median");
}
#[test]
fn groupby_std_single_value_returns_null() {
let keys =
Series::from_values("key", vec![0_i64.into()], vec![Scalar::Utf8("a".into())]).unwrap();
let values =
Series::from_values("val", vec![0_i64.into()], vec![Scalar::Int64(42)]).unwrap();
let mut ledger = EvidenceLedger::new();
let out = groupby_std(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert!(out.values()[0].is_missing());
}
#[test]
fn groupby_var_with_nulls_skips_missing() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Int64(10),
Scalar::Null(NullKind::Null),
Scalar::Int64(30),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out = groupby_var(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.values(), &[Scalar::Float64(200.0)]);
}
#[test]
fn groupby_var_std_utf8_keys_stream_numeric_counters_uza04202() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let keys = Series::from_values(
"key",
(0..7).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("c".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("d".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"val",
(0..7).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Float64(1.0),
Scalar::Null(NullKind::Null),
Scalar::Float64(3.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(5.0),
Scalar::Null(NullKind::Null),
Scalar::Float64(10.0),
],
)
.unwrap();
let sorted_var = groupby_var(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
let sorted_std = groupby_std(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
assert_eq!(
sorted_var.index().labels(),
&["a".into(), "b".into(), "c".into(), "d".into()]
);
assert_eq!(sorted_std.index().labels(), sorted_var.index().labels());
assert!(sorted_var.values()[0].is_missing());
assert_eq!(sorted_var.values()[1], Scalar::Float64(2.0));
assert!(sorted_var.values()[2].is_missing());
assert!(sorted_var.values()[3].is_missing());
let b_std = match sorted_std.values()[1] {
Scalar::Float64(v) => v,
_ => f64::NAN,
};
assert!((b_std - 2.0_f64.sqrt()).abs() < 1e-12);
let first_seen = GroupByOptions {
dropna: true,
sort: false,
};
let unsorted_var = groupby_var(&keys, &values, first_seen, &policy, &mut ledger).unwrap();
assert_eq!(
unsorted_var.index().labels(),
&["b".into(), "a".into(), "c".into(), "d".into()]
);
assert_eq!(unsorted_var.values()[0], Scalar::Float64(2.0));
assert!(unsorted_var.values()[1].is_missing());
}
#[test]
fn groupby_var_std_timedelta_fallback_preserves_dtype_uza04202() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let keys = Series::from_values(
"key",
(0..4).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("b".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"td",
(0..4).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Timedelta64(10),
Scalar::Timedelta64(20),
Scalar::Timedelta64(30),
Scalar::Null(NullKind::NaT),
],
)
.unwrap();
let var = groupby_var(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
let std = groupby_std(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
assert_eq!(var.index().labels(), &["a".into(), "b".into()]);
assert_eq!(std.index().labels(), var.index().labels());
assert_eq!(
var.values(),
&[
Scalar::Timedelta64(50),
Scalar::Timedelta64(fp_types::Timedelta::NAT)
]
);
assert_eq!(
std.values(),
&[
Scalar::Timedelta64(7),
Scalar::Timedelta64(fp_types::Timedelta::NAT)
]
);
}
#[test]
fn groupby_median_utf8_keys_numeric_vectors_uza04203() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let keys = Series::from_values(
"key",
(0..8).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("c".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("d".to_owned()),
Scalar::Utf8("a".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"val",
(0..8).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Float64(1.0),
Scalar::Float64(10.0),
Scalar::Float64(5.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(2.0),
Scalar::Null(NullKind::Null),
Scalar::Float64(8.0),
Scalar::Float64(6.0),
],
)
.unwrap();
let sorted = groupby_median(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
assert_eq!(
sorted.index().labels(),
&["a".into(), "b".into(), "c".into(), "d".into()]
);
assert_eq!(
sorted.values(),
&[
Scalar::Float64(6.0),
Scalar::Float64(3.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(8.0)
]
);
let first_seen = GroupByOptions {
dropna: true,
sort: false,
};
let unsorted = groupby_median(&keys, &values, first_seen, &policy, &mut ledger).unwrap();
assert_eq!(
unsorted.index().labels(),
&["b".into(), "a".into(), "c".into(), "d".into()]
);
assert_eq!(
unsorted.values(),
&[
Scalar::Float64(3.0),
Scalar::Float64(6.0),
Scalar::Null(NullKind::NaN),
Scalar::Float64(8.0)
]
);
}
#[test]
fn groupby_median_timedelta_fallback_preserves_dtype_uza04203() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let keys = Series::from_values(
"key",
(0..5).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("b".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"td",
(0..5).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Timedelta64(10),
Scalar::Timedelta64(20),
Scalar::Timedelta64(30),
Scalar::Null(NullKind::NaT),
Scalar::Timedelta64(50),
],
)
.unwrap();
let out = groupby_median(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
assert_eq!(out.index().labels(), &["a".into(), "b".into()]);
assert_eq!(
out.values(),
&[Scalar::Timedelta64(15), Scalar::Timedelta64(40)]
);
}
#[test]
fn groupby_nunique_utf8_keys_borrowed_sets_uza04204() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let keys = Series::from_values(
"key",
(0..12).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("c".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("d".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("d".to_owned()),
Scalar::Utf8("e".to_owned()),
Scalar::Utf8("e".to_owned()),
Scalar::Utf8("e".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"val",
(0..12).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Utf8("x".to_owned()),
Scalar::Float64(-0.0),
Scalar::Utf8("x".to_owned()),
Scalar::Null(NullKind::NaN),
Scalar::Float64(0.0),
Scalar::Null(NullKind::Null),
Scalar::Timedelta64(5),
Scalar::Float64(1.0),
Scalar::Timedelta64(5),
Scalar::Bool(true),
Scalar::Int64(1),
Scalar::Float64(1.0),
],
)
.unwrap();
let sorted = groupby_agg(
&keys,
&values,
AggFunc::Nunique,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
assert_eq!(
sorted.index().labels(),
&["a".into(), "b".into(), "c".into(), "d".into(), "e".into()]
);
assert_eq!(
sorted.values(),
&[
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(0),
Scalar::Int64(1),
Scalar::Int64(3),
]
);
let first_seen = GroupByOptions {
dropna: true,
sort: false,
};
let unsorted = groupby_nunique(&keys, &values, first_seen, &policy, &mut ledger).unwrap();
assert_eq!(
unsorted.index().labels(),
&["b".into(), "a".into(), "c".into(), "d".into(), "e".into()]
);
assert_eq!(
unsorted.values(),
&[
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(0),
Scalar::Int64(1),
Scalar::Int64(3),
]
);
}
#[test]
fn groupby_median_even_count() {
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
Scalar::Utf8("a".into()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.unwrap();
let mut ledger = EvidenceLedger::new();
let out = groupby_median(
&keys,
&values,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert_eq!(out.values(), &[Scalar::Float64(2.5)]);
}
#[test]
fn groupby_agg_empty_input_std_var_median() {
let keys =
Series::from_values("key", Vec::<IndexLabel>::new(), Vec::<Scalar>::new()).unwrap();
let values =
Series::from_values("val", Vec::<IndexLabel>::new(), Vec::<Scalar>::new()).unwrap();
let mut ledger = EvidenceLedger::new();
for func in [AggFunc::Std, AggFunc::Var, AggFunc::Median] {
let out = groupby_agg(
&keys,
&values,
func,
GroupByOptions::default(),
&RuntimePolicy::strict(),
&mut ledger,
)
.unwrap();
assert!(
out.is_empty(),
"empty input should give empty output for {func:?}"
);
}
}
mod sketch_tests {
use fp_types::{NullKind, Scalar};
use super::super::*;
#[test]
fn hll_empty_estimate_is_zero() {
let hll = HyperLogLog::default_precision();
assert!(hll.estimate() < 1.0, "empty HLL should estimate ~0");
}
#[test]
fn hll_single_element() {
let mut hll = HyperLogLog::default_precision();
hll.insert(&Scalar::Int64(42));
let est = hll.estimate();
assert!((0.5..=2.0).contains(&est), "single element estimate={est}");
}
#[test]
fn hll_distinct_count_within_error_bound() {
let mut hll = HyperLogLog::default_precision();
let n = 10_000;
for i in 0..n {
hll.insert(&Scalar::Int64(i));
}
let est = hll.estimate();
let error = (est - n as f64).abs() / n as f64;
assert!(
error < 0.05,
"HLL estimate={est}, expected={n}, relative_error={error}"
);
}
#[test]
fn hll_duplicates_do_not_inflate_count() {
let mut hll = HyperLogLog::default_precision();
for _ in 0..100 {
for i in 0..100 {
hll.insert(&Scalar::Int64(i));
}
}
let est = hll.estimate();
assert!(
est < 200.0,
"duplicates inflated HLL: estimate={est}, expected ~100"
);
}
#[test]
fn hll_utf8_values() {
let mut hll = HyperLogLog::default_precision();
for i in 0..1000 {
hll.insert(&Scalar::Utf8(format!("key_{i}")));
}
let est = hll.estimate();
let error = (est - 1000.0).abs() / 1000.0;
assert!(
error < 0.1,
"HLL Utf8 estimate={est}, expected=1000, error={error}"
);
}
#[test]
fn hll_memory_usage() {
let hll = HyperLogLog::default_precision();
assert_eq!(hll.memory_bytes(), 16384, "p=14 -> 2^14 = 16384 bytes");
}
#[test]
fn hll_high_rho_does_not_overflow() {
let mut hll = HyperLogLog::new(6);
hll.registers[0] = 40;
hll.registers[1] = 50;
hll.registers[2] = 60;
let est = hll.estimate();
assert!(est.is_finite(), "HLL estimate overflowed: {est}");
assert!(est > 0.0, "HLL estimate should be positive: {est}");
}
#[test]
fn kll_empty_returns_none() {
let kll = KllSketch::default_accuracy();
assert!(kll.quantile(0.5).is_none());
assert!(kll.is_empty());
}
#[test]
fn kll_single_element_returns_it() {
let mut kll = KllSketch::new(64);
kll.insert(42.0);
assert_eq!(kll.quantile(0.0), Some(42.0));
assert_eq!(kll.quantile(0.5), Some(42.0));
assert_eq!(kll.quantile(1.0), Some(42.0));
}
#[test]
fn kll_median_within_error() {
let mut kll = KllSketch::default_accuracy();
let n = 10_000;
for i in 0..n {
kll.insert(i as f64);
}
assert_eq!(kll.len(), n);
let median = kll.quantile(0.5).expect("non-empty");
let error = (median - 4999.5).abs() / 10_000.0;
assert!(
error < 0.02,
"KLL median={median}, expected ~4999.5, rank_error={error}"
);
}
#[test]
fn kll_min_max_endpoints() {
let mut kll = KllSketch::default_accuracy();
for i in 0..1000 {
kll.insert(i as f64);
}
let min = kll.quantile(0.0).expect("min");
let max = kll.quantile(1.0).expect("max");
assert!(min <= 10.0, "KLL min={min}, expected near 0");
assert!(max >= 990.0, "KLL max={max}, expected near 999");
}
#[test]
fn kll_monotonic_quantiles() {
let mut kll = KllSketch::default_accuracy();
for i in 0..5000 {
kll.insert(i as f64);
}
let q25 = kll.quantile(0.25).expect("q25");
let q50 = kll.quantile(0.50).expect("q50");
let q75 = kll.quantile(0.75).expect("q75");
assert!(
q25 <= q50 && q50 <= q75,
"quantiles not monotonic: q25={q25}, q50={q50}, q75={q75}"
);
}
#[test]
fn cm_empty_estimate_is_zero() {
let cm = CountMinSketch::default_accuracy();
assert_eq!(cm.estimate(&Scalar::Int64(42)), 0);
}
#[test]
fn cm_single_element_exact() {
let mut cm = CountMinSketch::default_accuracy();
cm.insert(&Scalar::Int64(42));
assert_eq!(cm.estimate(&Scalar::Int64(42)), 1);
}
#[test]
fn cm_never_underestimates() {
let mut cm = CountMinSketch::default_accuracy();
for _ in 0..100 {
cm.insert(&Scalar::Utf8("a".into()));
}
for _ in 0..50 {
cm.insert(&Scalar::Utf8("b".into()));
}
assert!(
cm.estimate(&Scalar::Utf8("a".into())) >= 100,
"CM underestimated 'a'"
);
assert!(
cm.estimate(&Scalar::Utf8("b".into())) >= 50,
"CM underestimated 'b'"
);
}
#[test]
fn cm_overestimate_bounded() {
let mut cm = CountMinSketch::default_accuracy();
let n = 10_000;
for i in 0..n {
cm.insert(&Scalar::Int64(i));
}
let max_overestimate = 2 * n as u64 / 1024 + 1;
for i in 0..100 {
let est = cm.estimate(&Scalar::Int64(i));
assert!(
est <= 1 + max_overestimate,
"CM overestimate too high for key={i}: est={est}, max={max_overestimate}"
);
}
}
#[test]
fn approx_nunique_basic() {
let values: Vec<Scalar> = (0..1000).map(Scalar::Int64).collect();
let result = approx_nunique(&values);
let error = (result.value - 1000.0).abs() / 1000.0;
assert!(
error < 0.1,
"approx_nunique={}, expected=1000, error={error}",
result.value
);
}
#[test]
fn approx_nunique_skips_nulls() {
let values = vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(2),
Scalar::Null(NullKind::NaN),
Scalar::Int64(1),
];
let result = approx_nunique(&values);
assert!(
result.value >= 1.0 && result.value <= 4.0,
"approx_nunique={}, expected ~2",
result.value
);
}
#[test]
fn approx_quantile_basic() {
let values: Vec<Scalar> = (0..1000).map(|i| Scalar::Float64(i as f64)).collect();
let result = approx_quantile(&values, 0.5).expect("non-empty");
assert!(
(result.value - 499.5).abs() < 50.0,
"approx_quantile median={}, expected ~499.5",
result.value
);
}
#[test]
fn approx_quantile_empty_returns_none() {
let values: Vec<Scalar> = vec![Scalar::Null(NullKind::Null)];
assert!(approx_quantile(&values, 0.5).is_none());
}
#[test]
fn approx_value_counts_basic() {
let values = vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(1),
Scalar::Int64(3),
Scalar::Int64(1),
];
let counts = approx_value_counts(&values);
assert_eq!(counts.len(), 3, "3 distinct values");
let count_1 = counts
.iter()
.find(|(k, _)| k == &Scalar::Int64(1))
.map(|(_, c)| *c)
.expect("key 1 present");
assert!(count_1 >= 3, "count for 1 should be >= 3, got {count_1}");
}
#[test]
fn approx_value_counts_skips_nulls() {
let values = vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(1),
];
let counts = approx_value_counts(&values);
assert_eq!(counts.len(), 1, "only non-null values counted");
}
}
#[test]
fn groupby_nunique_basic() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let options = GroupByOptions::default();
let keys = Series::from_values(
"key",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
],
vec![
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("y".to_owned()),
Scalar::Utf8("y".to_owned()),
Scalar::Utf8("y".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![
0_i64.into(),
1_i64.into(),
2_i64.into(),
3_i64.into(),
4_i64.into(),
],
vec![
Scalar::Int64(1),
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.unwrap();
let result = groupby_nunique(&keys, &values, options, &policy, &mut ledger).unwrap();
assert_eq!(result.len(), 2);
assert_eq!(result.values()[0], Scalar::Int64(2)); assert_eq!(result.values()[1], Scalar::Int64(2)); }
#[test]
fn groupby_nunique_with_nulls() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let options = GroupByOptions::default();
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("x".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(1),
],
)
.unwrap();
let result = groupby_nunique(&keys, &values, options, &policy, &mut ledger).unwrap();
assert_eq!(result.values()[0], Scalar::Int64(1)); }
#[test]
fn groupby_prod_basic() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let options = GroupByOptions::default();
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("y".to_owned()),
Scalar::Utf8("y".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(2),
Scalar::Int64(3),
Scalar::Int64(4),
Scalar::Int64(5),
],
)
.unwrap();
let result = groupby_prod(&keys, &values, options, &policy, &mut ledger).unwrap();
assert_eq!(result.len(), 2);
assert_eq!(result.values()[0], Scalar::Int64(6)); assert_eq!(result.values()[1], Scalar::Int64(20)); }
#[test]
fn groupby_size_counts_including_nulls() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let options = GroupByOptions::default();
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("x".to_owned()),
Scalar::Utf8("y".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into(), 2_i64.into(), 3_i64.into()],
vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
Scalar::Int64(4),
],
)
.unwrap();
let result = groupby_size(&keys, &values, options, &policy, &mut ledger).unwrap();
assert_eq!(result.len(), 2);
assert_eq!(result.values()[0], Scalar::Int64(3)); assert_eq!(result.values()[1], Scalar::Int64(1)); }
#[test]
fn groupby_size_vs_count_difference() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let options = GroupByOptions::default();
let keys = Series::from_values(
"key",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Utf8("x".to_owned()), Scalar::Utf8("x".to_owned())],
)
.unwrap();
let values = Series::from_values(
"val",
vec![0_i64.into(), 1_i64.into()],
vec![Scalar::Null(NullKind::Null), Scalar::Int64(5)],
)
.unwrap();
let count_result = groupby_count(&keys, &values, options, &policy, &mut ledger).unwrap();
let size_result = groupby_size(&keys, &values, options, &policy, &mut ledger).unwrap();
assert_eq!(count_result.values()[0], Scalar::Int64(1)); assert_eq!(size_result.values()[0], Scalar::Int64(2)); }
#[test]
fn groupby_count_size_utf8_counter_path_preserves_null_and_order_semantics() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let keys = Series::from_values(
"key",
(0..6).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("c".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"val",
(0..6).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(2),
Scalar::Null(NullKind::NaN),
Scalar::Int64(5),
Scalar::Null(NullKind::Null),
],
)
.unwrap();
let count = groupby_count(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
let size = groupby_size(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
assert_eq!(
count.index().labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(
count.values(),
&[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(0)]
);
assert_eq!(
size.values(),
&[Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(1)]
);
let first_seen = GroupByOptions {
dropna: true,
sort: false,
};
let first_seen_size =
groupby_size(&keys, &values, first_seen, &policy, &mut ledger).unwrap();
assert_eq!(
first_seen_size.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
first_seen_size.values(),
&[Scalar::Int64(3), Scalar::Int64(2), Scalar::Int64(1)]
);
}
#[test]
fn groupby_mean_utf8_counter_path_preserves_null_and_order_semantics() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let keys = Series::from_values(
"key",
(0..6).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("c".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"val",
(0..6).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Int64(1),
Scalar::Null(NullKind::Null),
Scalar::Int64(3),
Scalar::Null(NullKind::NaN),
Scalar::Int64(5),
Scalar::Null(NullKind::Null),
],
)
.unwrap();
let mean = groupby_mean(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
assert_eq!(mean.index().labels(), &["a".into(), "b".into(), "c".into()]);
assert_eq!(
mean.values(),
&[
Scalar::Float64(5.0),
Scalar::Float64(2.0),
Scalar::Null(NullKind::NaN)
]
);
let first_seen = GroupByOptions {
dropna: true,
sort: false,
};
let first_seen_mean =
groupby_mean(&keys, &values, first_seen, &policy, &mut ledger).unwrap();
assert_eq!(
first_seen_mean.index().labels(),
&["b".into(), "a".into(), "c".into()]
);
assert_eq!(
first_seen_mean.values(),
&[
Scalar::Float64(2.0),
Scalar::Float64(5.0),
Scalar::Null(NullKind::NaN)
]
);
}
#[test]
fn groupby_mean_utf8_counter_path_preserves_timedelta_fallback() {
let policy = RuntimePolicy::default();
let mut ledger = EvidenceLedger::new();
let keys = Series::from_values(
"key",
(0..4).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("a".to_owned()),
Scalar::Utf8("b".to_owned()),
Scalar::Utf8("b".to_owned()),
],
)
.unwrap();
let values = Series::from_values(
"td",
(0..4).map(|i| (i as i64).into()).collect(),
vec![
Scalar::Timedelta64(10),
Scalar::Timedelta64(20),
Scalar::Timedelta64(30),
Scalar::Null(NullKind::NaT),
],
)
.unwrap();
let mean = groupby_mean(
&keys,
&values,
GroupByOptions::default(),
&policy,
&mut ledger,
)
.unwrap();
assert_eq!(mean.index().labels(), &["a".into(), "b".into()]);
assert_eq!(
mean.values(),
&[Scalar::Timedelta64(15), Scalar::Timedelta64(30)]
);
}
}