// MultiIndex level walks index several parallel arrays by the same counter; rewriting to
// iterators would obscure the level arithmetic without changing behaviour.
#![allow(clippy::needless_range_loop)]
#![forbid(unsafe_code)]
#![warn(rustdoc::broken_intra_doc_links)]
//! Row-label / index machinery for **frankenpandas** — every
//! `DataFrame` and `Series` in fp-frame carries an [`Index`] that
//! pairs labels with positional row indices, plus the alignment
//! algebra that pandas users expect from `Series + Series` and
//! `DataFrame.align()`.
//!
//! ## Core types
//!
//! - [`Index`]: the canonical row-label container. Internally a
//! typed `Vec<IndexLabel>` plus an O(1) label-lookup hashmap
//! built lazily on first use. Pandas `Index` shape: monotonic
//! probes, duplicate handling, range-style construction
//! (`Index::from_range(0..N)`), name metadata.
//! - [`IndexLabel`]: typed label enum — `Int64(i64)`, `Float64(f64)`,
//! `Utf8(String)`, `Bool(bool)`, `Datetime64(i64)`,
//! `Timedelta64(i64)`. Lets one `Index` carry mixed-type labels
//! without erasing to strings.
//! - [`MultiIndex`]: hierarchical multi-level index for
//! pandas-style row MultiIndex DataFrames. Each level is itself
//! a `Vec<IndexLabel>` plus an integer codes array.
//! - [`MultiIndexOrIndex`]: sum-type for code paths that accept
//! either flat `Index` or `MultiIndex`.
//! - [`DuplicateKeep`]: enum controlling `keep='first' | 'last'
//! | False` semantics in `Index.duplicated` /
//! `Index.drop_duplicates` etc.
//!
//! ## Alignment algebra
//!
//! Binary ops between two pandas-shaped frames need to align rows
//! by label. The aligner builds an [`AlignmentPlan`] (or
//! [`MultiAlignmentPlan`] for N-way joins) that the caller then
//! applies to each side's value buffers:
//!
//! - [`align`] dispatches on [`AlignMode`] (`Left`, `Right`,
//! `Inner`, `Outer`).
//! - [`align_inner`], [`align_left`], [`align_union`]: direct
//! single-mode entry points.
//! - [`leapfrog_union`] / [`leapfrog_intersection`]: N-way row
//! alignment via a leapfrog merge over already-sorted indexes
//! (used by [`multi_way_align`]).
//! - [`validate_alignment_plan`]: sanity check (lengths match,
//! indices in bounds).
//!
//! ## Date / time helpers
//!
//! Pandas `pd.date_range` / `pd.timedelta_range` analogs:
//!
//! - [`timedelta_range`]: pandas-style timedelta range builder.
//! - [`apply_date_offset`] / [`apply_date_offset_to_nanos`]:
//! evaluate a [`DateOffset`] against an anchor timestamp.
//! - [`infer_freq`] / [`infer_freq_from_timestamps`] /
//! [`infer_freq_from_nanos`]: pandas-style frequency inference
//! from a sample of timestamps.
//! - [`format_datetime_ns`]: render a nanosecond-since-epoch i64
//! as the canonical `YYYY-MM-DD HH:MM:SS[.f]` string used in
//! IndexLabel display and IO formatters.
//!
//! ## Error reporting
//!
//! - [`IndexError`]: structural / lookup failures (not-monotonic,
//! not-unique, missing-label, validation-mismatch).
//! - [`TimedeltaRangeError`] / [`DateRangeError`]: range builder
//! parse / step / overflow errors.
//!
//! ## Relationship to other crates
//!
//! - **fp-types** supplies [`Scalar`] / [`Timedelta`] /
//! `format_datetime_ns` primitives.
//! - **fp-frame** stores an `Index` per DataFrame / Series and uses
//! the alignment algebra here for binary ops.
//! - **fp-join** consumes alignment plans for merge-style joins.
use std::{
borrow::Cow,
collections::HashMap,
fmt,
sync::{
Arc, Mutex, OnceLock,
atomic::{AtomicU64, Ordering as AtomicOrdering},
},
};
use chrono::Datelike;
use fp_types::{
Interval, IntervalClosed, Period, PeriodFreq, Scalar, Timedelta, TimedeltaComponents,
Timestamp, interval_range,
};
// Dedup / set-op seen-sets key on &IndexLabel and read output order from the
// INPUT scan (first-seen filter / positional bool), never from map iteration —
// so the hasher is observationally invisible. FxHash (rustc-hash, pure safe
// Rust) replaces the std SipHasher on these hot membership maps; public-return
// maps (position_map_first, groupby) keep std HashMap to avoid an API change.
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
/// A total-ordering, hashable `f64` wrapper for use as an index label
/// (br-frankenpandas-i10en). `-0.0` is normalized to `+0.0` and all NaNs
/// collapse to one bucket, so `Eq`/`Hash`/`Ord` are mutually consistent
/// (a == b implies cmp == Equal) — matching pandas' Float64Index. NaN sorts
/// after every finite value (pandas NaN-last).
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(transparent)]
pub struct OrderedF64(pub f64);
impl OrderedF64 {
#[inline]
fn canonical_bits(self) -> u64 {
if self.0.is_nan() {
f64::NAN.to_bits()
} else if self.0 == 0.0 {
0.0_f64.to_bits()
} else {
self.0.to_bits()
}
}
}
impl PartialEq for OrderedF64 {
fn eq(&self, other: &Self) -> bool {
self.canonical_bits() == other.canonical_bits()
}
}
impl Eq for OrderedF64 {}
/// The canonical bits spread ([`fp_types::spread_float_bits`]): a round
/// float's raw bits end in zeros FxHash keeps where its tables take their
/// buckets from (br-frankenpandas-bss5q.3). Equal labels still hash equal.
impl std::hash::Hash for OrderedF64 {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
fp_types::spread_float_bits(self.canonical_bits()).hash(state);
}
}
impl Ord for OrderedF64 {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
use std::cmp::Ordering;
let (a, b) = (self.0, other.0);
match (a.is_nan(), b.is_nan()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => a.partial_cmp(&b).unwrap_or(Ordering::Equal),
}
}
}
impl PartialOrd for OrderedF64 {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
/// Labels compare as pandas' do: an int and a float are one number (`1 ==
/// 1.0`, hashed alike, as Python's), ordered by value beside each other;
/// every other kind equals only its own kind, and kinds order as declared
/// below with the numbers first (br-frankenpandas-l5sed: `Int64(1)` and
/// `Float64(1.0)` were different labels, so `s.loc[2.0]` missed an int
/// index).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
pub enum IndexLabel {
Int64(i64),
Utf8(String),
Timedelta64(i64),
Datetime64(i64),
/// pandas Float64Index label (br-frankenpandas-i10en). Placed before
/// `Null` so the derived cross-variant order keeps every concrete label
/// before nulls.
Float64(OrderedF64),
/// pandas boolean index label.
Bool(bool),
/// An object cell as a label (fvsao.66): a `datetime.date` from
/// `groupby(s.dt.date)`, kept as that object rather than its text.
/// Ordered by [`fp_types::ObjectValue::total_cmp`] (Python's own order
/// where it has one); before `Null` so null labels still sort last.
Object(fp_types::ObjectValue),
/// A period, a PeriodIndex's label (br-frankenpandas-45fzr): a Series /
/// DataFrame row index, groupby keys and value_counts over periods keep
/// them (they were their text). Ordered by ordinal (then freq); NaT
/// (ordinal `i64::MIN`) is missing. Before `Null` so null labels still
/// sort last.
Period(fp_types::Period),
/// An interval, an IntervalIndex's label (br-frankenpandas-c27hq): a
/// Series / DataFrame row index, value_counts(bins=), groupby over
/// pd.cut and a cut column's value_counts keep them (they were their
/// text). Ordered by left, then right endpoint; before `Null` so null
/// labels still sort last.
Interval(fp_types::Interval),
/// Typed missing label (br-frankenpandas-joeff): lets value_counts
/// (dropna=False) and friends keep pandas' distinct None / nan / NaT
/// buckets instead of collapsing them or colliding with genuine
/// "None"/"nan" strings. Appended LAST so the derived `Ord` sorts null
/// labels after every concrete label (pandas NaN-last sort order) without
/// disturbing the existing cross-variant order. `Eq`/`Hash` are
/// kind-SENSITIVE (None != nan != NaT), matching `ScalarKey::Null`
/// bucket identity.
Null(fp_types::NullKind),
}
/// `value` as the int it equals exactly, if it is one (no fraction, inside
/// i64's range).
#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] // checked round trip
fn exact_i64(value: f64) -> Option<i64> {
// 2^63 is the first float past i64's range.
const LIMIT: f64 = 9_223_372_036_854_775_808.0;
(value.fract() == 0.0 && (-LIMIT..LIMIT).contains(&value)).then_some(value as i64)
}
/// An int against a float, exactly: NaN after every number, as a float
/// index orders it.
#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] // checked range
fn cmp_int_float(int: i64, float: f64) -> std::cmp::Ordering {
use std::cmp::Ordering;
const LIMIT: f64 = 9_223_372_036_854_775_808.0;
if float.is_nan() || float >= LIMIT {
return Ordering::Less;
}
if float < -LIMIT {
return Ordering::Greater;
}
let whole = float.trunc();
match int.cmp(&(whole as i64)) {
Ordering::Equal if float > whole => Ordering::Less,
Ordering::Equal if float < whole => Ordering::Greater,
other => other,
}
}
impl IndexLabel {
/// The int this label equals: an int's own value, an integral float's
/// (`2.0` is `2`, as pandas looks it up in an int index); None for any
/// other label.
#[must_use]
pub fn exact_int(&self) -> Option<i64> {
match self {
Self::Int64(value) => Some(*value),
Self::Float64(value) => exact_i64(value.0),
_ => None,
}
}
/// The label's kind in the cross-kind order: numbers first (ints and
/// floats together), then the kinds as declared, missing last.
fn kind_rank(&self) -> u8 {
match self {
Self::Int64(_) | Self::Float64(_) => 0,
Self::Utf8(_) => 1,
Self::Timedelta64(_) => 2,
Self::Datetime64(_) => 3,
Self::Bool(_) => 4,
Self::Object(_) => 5,
Self::Period(_) => 6,
Self::Interval(_) => 7,
Self::Null(_) => 8,
}
}
}
impl PartialEq for IndexLabel {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Int64(a), Self::Int64(b))
| (Self::Timedelta64(a), Self::Timedelta64(b))
| (Self::Datetime64(a), Self::Datetime64(b)) => a == b,
(Self::Int64(int), Self::Float64(float)) | (Self::Float64(float), Self::Int64(int)) => {
exact_i64(float.0) == Some(*int)
}
(Self::Float64(a), Self::Float64(b)) => a == b,
(Self::Utf8(a), Self::Utf8(b)) => a == b,
(Self::Bool(a), Self::Bool(b)) => a == b,
(Self::Object(a), Self::Object(b)) => a == b,
(Self::Period(a), Self::Period(b)) => a == b,
(Self::Interval(a), Self::Interval(b)) => a == b,
(Self::Null(a), Self::Null(b)) => a == b,
_ => false,
}
}
}
impl Eq for IndexLabel {}
impl std::hash::Hash for IndexLabel {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
// An integral float hashes as the int it equals.
let integral = match self {
Self::Int64(value) => Some(*value),
Self::Float64(value) => exact_i64(value.0),
_ => None,
};
if let Some(value) = integral {
0_u8.hash(state);
value.hash(state);
return;
}
std::mem::discriminant(self).hash(state);
match self {
Self::Int64(_) => {}
Self::Utf8(text) => text.hash(state),
Self::Timedelta64(value) | Self::Datetime64(value) => value.hash(state),
Self::Float64(value) => value.hash(state),
Self::Bool(flag) => flag.hash(state),
Self::Object(object) => object.hash(state),
Self::Period(period) => period.hash(state),
Self::Interval(interval) => interval.hash(state),
Self::Null(kind) => kind.hash(state),
}
}
}
impl Ord for IndexLabel {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
match (self, other) {
(Self::Int64(a), Self::Int64(b))
| (Self::Timedelta64(a), Self::Timedelta64(b))
| (Self::Datetime64(a), Self::Datetime64(b)) => a.cmp(b),
(Self::Int64(int), Self::Float64(float)) => cmp_int_float(*int, float.0),
(Self::Float64(float), Self::Int64(int)) => cmp_int_float(*int, float.0).reverse(),
(Self::Float64(a), Self::Float64(b)) => a.cmp(b),
(Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
(Self::Bool(a), Self::Bool(b)) => a.cmp(b),
(Self::Object(a), Self::Object(b)) => a.cmp(b),
(Self::Period(a), Self::Period(b)) => a.cmp(b),
(Self::Interval(a), Self::Interval(b)) => a.cmp(b),
(Self::Null(a), Self::Null(b)) => a.cmp(b),
_ => self.kind_rank().cmp(&other.kind_rank()),
}
}
}
impl PartialOrd for IndexLabel {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl From<i64> for IndexLabel {
fn from(value: i64) -> Self {
Self::Int64(value)
}
}
impl From<&str> for IndexLabel {
fn from(value: &str) -> Self {
Self::Utf8(value.to_owned())
}
}
impl From<String> for IndexLabel {
fn from(value: String) -> Self {
Self::Utf8(value)
}
}
impl IndexLabel {
#[must_use]
pub fn is_missing(&self) -> bool {
match self {
Self::Timedelta64(value) => *value == Timedelta::NAT,
Self::Datetime64(value) => *value == i64::MIN,
Self::Float64(v) => v.0.is_nan(),
Self::Period(period) => period.is_nat(),
Self::Int64(_)
| Self::Utf8(_)
| Self::Bool(_)
| Self::Object(_)
| Self::Interval(_) => false,
Self::Null(_) => true,
}
}
}
/// `std::thread::available_parallelism()`, resolved ONCE per process.
///
/// br-frankenpandas-q1evw. A local copy of `fp_columnar::cached_available_parallelism`
/// rather than a shared call, because `fp-index` deliberately does not depend on
/// `fp-columnar` and six lines are cheaper than a new edge in the crate graph. Keep
/// the two in step.
///
/// WHY THIS IS CACHED AT ALL, measured on `fp-columnar` (br-frankenpandas-kko5z):
/// `available_parallelism` honours cgroup CPU quota by WALKING THE CGROUP HIERARCHY
/// ON THE FILESYSTEM — `/proc/self/cgroup` plus `cpu.max` at every level, 7 opens and
/// ~10 reads per call, six levels deep for a tmux-spawned process. That cost 66-68us
/// per elementwise call there.
///
/// `fp-index`'s two call sites were NOT the bug — both already sit inside an
/// `n >= FLATIDX_PAR_MIN_ROWS` (50_000) gate, so a small call never reached the walk.
/// That is the shape `fp-columnar` got wrong by calling it BEFORE its size check.
/// Caching is still worth it at the boundary, where the walk was a real fraction of
/// the parallel work it was sizing.
///
/// Caching means this will not notice an affinity or quota change made from outside a
/// running process; that is the right trade for sizing a worker pool. One worker while
/// a Python object cell is alive in the binding's process, as
/// `fp_columnar::cached_available_parallelism` (a worker touching one would wait on the
/// GIL its caller holds; 4qg5w.13).
fn cached_available_parallelism() -> usize {
static AVAILABLE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
if fp_types::host_values_block_workers() {
return 1;
}
*AVAILABLE
.get_or_init(|| std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get))
}
/// numpy's `around`: scale by 10^decimals (or divide, for a negative
/// `decimals`), round halves to even, scale back.
fn round_half_even(x: f64, decimals: i32) -> f64 {
if decimals >= 0 {
let scale = 10_f64.powi(decimals);
(x * scale).round_ties_even() / scale
} else {
let scale = 10_f64.powi(-decimals);
(x / scale).round_ties_even() * scale
}
}
fn index_label_is_truthy(label: &IndexLabel) -> bool {
if label.is_missing() {
return false;
}
match label {
IndexLabel::Int64(v) => *v != 0,
IndexLabel::Float64(v) => v.0 != 0.0,
IndexLabel::Bool(b) => *b,
IndexLabel::Utf8(s) => !s.is_empty(),
IndexLabel::Timedelta64(v) => *v != 0,
IndexLabel::Datetime64(v) => *v != 0,
// Python truth: an empty list is false, any other object true.
IndexLabel::Object(object) => object.as_list().is_none_or(|items| !items.is_empty()),
// A Period object is true (its NaT was missing above), an Interval
// object too.
IndexLabel::Period(_) | IndexLabel::Interval(_) => true,
// Unreachable: is_missing() returned true above for every Null.
IndexLabel::Null(_) => false,
}
}
/// Hand-rolled decimal itoa straight into a byte buffer, bit-identical to
/// `v.to_string()` (and therefore to `write!(buf, "{v}")`) for every `i64`.
/// Mirrored from `fp-columnar`'s proven `push_i64_decimal`; `fp-index` depends
/// only on `fp-types`, so it cannot reuse that one directly.
#[inline]
fn push_i64_decimal(buf: &mut Vec<u8>, v: i64) {
const LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\
20212223242526272829303132333435363738394041424344454647484950515253545556575859\
60616263646566676869707172737475767778798081828384858687888990919293949596979899";
let mut n: u64 = if v < 0 {
buf.push(b'-');
v.unsigned_abs()
} else {
v as u64
};
let mut tmp = [0u8; 20];
let mut i = 20usize;
while n >= 100 {
let r = (n % 100) as usize * 2;
n /= 100;
i -= 2;
tmp[i] = LUT[r];
tmp[i + 1] = LUT[r + 1];
}
if n >= 10 {
let r = (n as usize) * 2;
i -= 2;
tmp[i] = LUT[r];
tmp[i + 1] = LUT[r + 1];
} else {
i -= 1;
tmp[i] = b'0' + n as u8;
}
buf.extend_from_slice(&tmp[i..]);
}
impl fmt::Display for IndexLabel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Int64(v) => write!(f, "{v}"),
Self::Float64(v) => {
if v.0.is_nan() {
return write!(f, "NaN");
}
let t = format!("{}", v.0);
if t.contains('.') || t.contains('e') || t.contains("inf") {
write!(f, "{t}")
} else {
write!(f, "{t}.0")
}
}
Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
Self::Utf8(v) => write!(f, "{v}"),
Self::Timedelta64(v) => write!(f, "{}", Timedelta::format(*v)),
Self::Datetime64(v) => write!(f, "{}", format_datetime_ns(*v)),
// pandas prints an object label as its cell (`2020-01-05`).
Self::Object(object) => f.write_str(&object.pprint()),
// A period as its calendar text (`2024-03`, `2024Q1`, NaT).
Self::Period(period) => write!(f, "{period}"),
// An interval as pandas prints it (`(0, 1]`).
Self::Interval(interval) => write!(f, "{interval}"),
// Matches pandas' REPR of missing labels in an index (None / NaN /
// NaT — note uppercase NaN: the formatter surface, unlike
// str(nan)=='nan' which astype(str) uses). Verified pandas 2.2.3.
Self::Null(fp_types::NullKind::Null) => write!(f, "None"),
Self::Null(fp_types::NullKind::NaN) => write!(f, "NaN"),
Self::Null(fp_types::NullKind::NaT) => write!(f, "NaT"),
}
}
}
/// The canonical name a typed column label keys its column under: its
/// pandas text (`0`, `1.5`, `True`, `2024-01-01 00:00:00`), the string
/// itself for a string label. The binding keys columns by it, so a label
/// and its name always agree.
#[must_use]
pub fn column_key(label: &IndexLabel) -> String {
label.to_string()
}
/// A pandas name - a Series' name, an index's or a column axis' name: its
/// text - what it is keyed and printed as - and, when it is not a string,
/// the typed pandas label it stands for (`df[0]`'s name is the integer 0,
/// `df.set_index(0).index.name` too; they were the strings '0'; fvsao.32,
/// fvsao.64). It reads as the text (Deref, Display, Debug, serde,
/// comparison with a string), and the label rides along wherever the name
/// is cloned; a name rebuilt from text alone is a string.
#[derive(Clone, Default)]
pub struct LabelName {
text: String,
label: Option<IndexLabel>,
}
impl LabelName {
/// The name standing for `label`, keyed by its text (see
/// [`column_key`]); a string label is plain text.
#[must_use]
pub fn typed(label: IndexLabel) -> Self {
match label {
IndexLabel::Utf8(text) => Self { text, label: None },
label => Self {
text: column_key(&label),
label: Some(label),
},
}
}
/// The typed label this name stands for; the text as a string label for
/// a plain name.
#[must_use]
pub fn label(&self) -> IndexLabel {
self.label
.clone()
.filter(|label| column_key(label) == self.text)
.unwrap_or_else(|| IndexLabel::Utf8(self.text.clone()))
}
}
impl std::ops::Deref for LabelName {
type Target = String;
fn deref(&self) -> &String {
&self.text
}
}
impl AsRef<str> for LabelName {
fn as_ref(&self) -> &str {
&self.text
}
}
impl From<String> for LabelName {
fn from(text: String) -> Self {
Self { text, label: None }
}
}
impl From<&str> for LabelName {
fn from(text: &str) -> Self {
text.to_owned().into()
}
}
impl From<&String> for LabelName {
fn from(text: &String) -> Self {
text.clone().into()
}
}
impl From<&Self> for LabelName {
fn from(name: &Self) -> Self {
name.clone()
}
}
impl From<LabelName> for String {
fn from(name: LabelName) -> Self {
name.text
}
}
impl From<&LabelName> for String {
fn from(name: &LabelName) -> Self {
name.text.clone()
}
}
impl fmt::Display for LabelName {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.text, formatter)
}
}
impl fmt::Debug for LabelName {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.text, formatter)
}
}
/// Names are equal when their labels are: 0 and '0' differ, as in pandas
/// (whose `s + t` of those is unnamed).
impl PartialEq for LabelName {
fn eq(&self, other: &Self) -> bool {
self.text == other.text && self.label == other.label
}
}
impl Eq for LabelName {}
impl PartialEq<str> for LabelName {
fn eq(&self, other: &str) -> bool {
self.text == other
}
}
impl PartialEq<&str> for LabelName {
fn eq(&self, other: &&str) -> bool {
self.text == *other
}
}
impl PartialEq<String> for LabelName {
fn eq(&self, other: &String) -> bool {
&self.text == other
}
}
impl Serialize for LabelName {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.text.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for LabelName {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer).map(Self::from)
}
}
/// Hinnant `civil_from_days`: proleptic-Gregorian (year, month, day) for a day
/// count since the 1970-01-01 epoch. Floor-correct for negative (pre-epoch)
/// days. Identical algorithm to `fp-frame`'s `datetime64_civil_from_nanos`.
#[inline]
fn civil_from_epoch_days(days_since_epoch: i64) -> (i64, i64, i64) {
let days = days_since_epoch + 719_468;
let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
let doe = days - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if month <= 2 { y + 1 } else { y };
(year, month, day)
}
/// Append exactly two decimal digits of `n` (0..=99) — `{:02}`.
#[inline]
fn push_2d_str(buf: &mut String, n: i64) {
buf.push((b'0' + (n / 10 % 10) as u8) as char);
buf.push((b'0' + (n % 10) as u8) as char);
}
/// Append exactly four decimal digits of `n` (0..=9999) — `{:04}`.
#[inline]
fn push_4d_str(buf: &mut String, n: i64) {
buf.push((b'0' + (n / 1000 % 10) as u8) as char);
buf.push((b'0' + (n / 100 % 10) as u8) as char);
buf.push((b'0' + (n / 10 % 10) as u8) as char);
buf.push((b'0' + (n % 10) as u8) as char);
}
pub fn format_datetime_ns(nanos: i64) -> String {
if nanos == i64::MIN {
return "NaT".to_owned();
}
// Hand-rolled civil + ASCII (br-frankenpandas-dtns), bit-identical to the
// prior `chrono::from_timestamp_nanos(nanos).format("%Y-%m-%d %H:%M:%S")` +
// trailing-zero-trimmed subsecond fraction, but without the per-call chrono
// DateTime construction, the `DelayedFormat` strftime machinery, and the two
// `String`/`format!` allocations. `div_euclid`/`rem_euclid` reproduce
// chrono's floor semantics for pre-epoch instants (-0.5s renders as
// 1969-12-31 23:59:59.5). A datetime64[ns] year is always in [1677, 2262]
// (the i64-ns range) so `%Y` is exactly 4 digits, and the time fields are 2.
let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
let (y, m, d) = civil_from_epoch_days(days);
let secs_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
let h = secs_of_day / 3600;
let mi = (secs_of_day % 3600) / 60;
let sec = secs_of_day % 60;
let subsec = nanos.rem_euclid(Timedelta::NANOS_PER_SEC); // 0..=999_999_999
let mut rendered = String::with_capacity(if subsec != 0 { 29 } else { 19 });
push_4d_str(&mut rendered, y);
rendered.push('-');
push_2d_str(&mut rendered, m);
rendered.push('-');
push_2d_str(&mut rendered, d);
rendered.push(' ');
push_2d_str(&mut rendered, h);
rendered.push(':');
push_2d_str(&mut rendered, mi);
rendered.push(':');
push_2d_str(&mut rendered, sec);
if subsec != 0 {
// Nine zero-padded fraction digits with trailing zeros trimmed, matching
// the prior `format!("{subsec:09}")` + pop-'0' loop exactly.
let mut frac = [0u8; 9];
let mut v = subsec;
for slot in frac.iter_mut().rev() {
*slot = b'0' + (v % 10) as u8;
v /= 10;
}
let mut end = 9usize;
while end > 0 && frac[end - 1] == b'0' {
end -= 1;
}
rendered.push('.');
// SAFETY-FREE: frac[..end] is all ASCII digits.
rendered.push_str(std::str::from_utf8(&frac[..end]).unwrap_or(""));
}
rendered
}
/// AG-13: Detected sort order of an index's labels.
///
/// Enables adaptive backend selection: binary search for sorted indexes,
/// HashMap fallback for unsorted. Computed lazily via `OnceLock`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SortOrder {
/// Labels are not in any recognized sorted order.
Unsorted,
/// All labels are `Int64` and strictly ascending (no duplicates).
AscendingInt64,
/// All labels are `Utf8` and strictly ascending (no duplicates).
AscendingUtf8,
/// All labels are `Timedelta64` and strictly ascending (no duplicates).
AscendingTimedelta64,
/// All labels are `Datetime64` and strictly ascending (no duplicates).
AscendingDatetime64,
}
/// Which set operation a two-pointer sorted merge should emit
/// (br-frankenpandas-idxdup). Both inputs are strictly ascending and unique.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SetMergeKind {
/// Keep `self` labels that also appear in `other`.
Intersection,
/// Keep `self` labels that do NOT appear in `other`.
Difference,
}
/// Detect the sort order of the label slice.
fn detect_sort_order(labels: &[IndexLabel]) -> SortOrder {
if labels.len() <= 1 {
return match labels.first() {
Some(IndexLabel::Int64(_)) | None => SortOrder::AscendingInt64,
Some(IndexLabel::Utf8(_)) => SortOrder::AscendingUtf8,
Some(IndexLabel::Timedelta64(_)) => SortOrder::AscendingTimedelta64,
Some(IndexLabel::Datetime64(_)) => SortOrder::AscendingDatetime64,
// Float64/Bool/Object/Period/Interval/Null labels use the general
// (non-typed) backend.
Some(
IndexLabel::Float64(_)
| IndexLabel::Bool(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_),
) => SortOrder::Unsorted,
};
}
// Check if all Int64 and strictly ascending.
let all_int = labels.iter().all(|l| matches!(l, IndexLabel::Int64(_)));
if all_int {
let is_sorted = labels.windows(2).all(|w| {
if let (IndexLabel::Int64(a), IndexLabel::Int64(b)) = (&w[0], &w[1]) {
a < b
} else {
false
}
});
if is_sorted {
return SortOrder::AscendingInt64;
}
}
// Check if all Utf8 and strictly ascending.
let all_utf8 = labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)));
if all_utf8 {
let is_sorted = labels.windows(2).all(|w| {
if let (IndexLabel::Utf8(a), IndexLabel::Utf8(b)) = (&w[0], &w[1]) {
a < b
} else {
false
}
});
if is_sorted {
return SortOrder::AscendingUtf8;
}
}
// Check if all Timedelta64 and strictly ascending.
let all_td = labels
.iter()
.all(|l| matches!(l, IndexLabel::Timedelta64(_)));
if all_td {
let is_sorted = labels.windows(2).all(|w| {
if let (IndexLabel::Timedelta64(a), IndexLabel::Timedelta64(b)) = (&w[0], &w[1]) {
a < b
} else {
false
}
});
if is_sorted {
return SortOrder::AscendingTimedelta64;
}
}
// Check if all Datetime64 and strictly ascending.
let all_dt = labels
.iter()
.all(|l| matches!(l, IndexLabel::Datetime64(_)));
if all_dt {
let is_sorted = labels.windows(2).all(|w| {
if let (IndexLabel::Datetime64(a), IndexLabel::Datetime64(b)) = (&w[0], &w[1]) {
a < b
} else {
false
}
});
if is_sorted {
return SortOrder::AscendingDatetime64;
}
}
SortOrder::Unsorted
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DuplicateKeep {
First,
Last,
None,
}
static INDEX_LABEL_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
static INDEX_LABEL_EQUALITY_CACHE: OnceLock<Mutex<FxHashMap<(u64, u64), bool>>> = OnceLock::new();
const INDEX_LABEL_EQUALITY_CACHE_MAX: usize = 4096;
/// [`Index::label_kinds`] by the index's runtime label identity (labels never
/// change under one), as `INDEX_LABEL_EQUALITY_CACHE` keeps equality.
static INDEX_LABEL_KINDS_CACHE: OnceLock<Mutex<FxHashMap<u64, LabelKinds>>> = OnceLock::new();
const INDEX_LABEL_KINDS_CACHE_MAX: usize = 4096;
/// The kinds of label an index holds ([`Index::label_kinds`]): which
/// [`IndexLabel`] variants occur, a missing one split into NaT and any other
/// null (NaN, None). A set of kinds is itself a `LabelKinds` (`union`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct LabelKinds(u16);
impl LabelKinds {
pub const INT64: Self = Self(1);
pub const UTF8: Self = Self(1 << 1);
pub const TIMEDELTA64: Self = Self(1 << 2);
pub const DATETIME64: Self = Self(1 << 3);
pub const FLOAT64: Self = Self(1 << 4);
pub const BOOL: Self = Self(1 << 5);
pub const OBJECT: Self = Self(1 << 6);
pub const PERIOD: Self = Self(1 << 7);
pub const INTERVAL: Self = Self(1 << 8);
pub const NAT: Self = Self(1 << 9);
/// A missing label other than NaT: NaN or None.
pub const OTHER_NULL: Self = Self(1 << 10);
/// The kind of `label`.
#[must_use]
pub const fn of(label: &IndexLabel) -> Self {
match label {
IndexLabel::Int64(_) => Self::INT64,
IndexLabel::Utf8(_) => Self::UTF8,
IndexLabel::Timedelta64(_) => Self::TIMEDELTA64,
IndexLabel::Datetime64(_) => Self::DATETIME64,
IndexLabel::Float64(_) => Self::FLOAT64,
IndexLabel::Bool(_) => Self::BOOL,
IndexLabel::Object(_) => Self::OBJECT,
IndexLabel::Period(_) => Self::PERIOD,
IndexLabel::Interval(_) => Self::INTERVAL,
IndexLabel::Null(fp_types::NullKind::NaT) => Self::NAT,
IndexLabel::Null(_) => Self::OTHER_NULL,
}
}
/// Both sets of kinds.
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
/// Whether a label of a kind in `kinds` occurs.
#[must_use]
pub const fn intersects(self, kinds: Self) -> bool {
self.0 & kinds.0 != 0
}
/// Whether every label is of a kind in `kinds` (true of no label).
#[must_use]
pub const fn within(self, kinds: Self) -> bool {
self.0 & !kinds.0 == 0
}
}
type Int64PositionLookup = FxHashMap<i64, usize>;
type Utf8PositionLookup = FxHashMap<Box<str>, usize>;
type SharedInt64PositionLookup = Arc<Int64PositionLookup>;
type SharedUtf8PositionLookup = Arc<Utf8PositionLookup>;
type Int64PositionLookupCache = FxHashMap<u64, SharedInt64PositionLookup>;
type Utf8PositionLookupCache = FxHashMap<u64, Option<SharedUtf8PositionLookup>>;
type Datetime64PositionLookupCache = FxHashMap<u64, Option<SharedInt64PositionLookup>>;
type Timedelta64PositionLookupCache = FxHashMap<u64, Option<SharedInt64PositionLookup>>;
/// First-occurrence `i64 -> position` lookup tables for unsorted unique Int64
/// indexes, cached by the index's runtime label identity (mirrors
/// `INDEX_LABEL_EQUALITY_CACHE`). Lets repeated `loc[[labels]]` resolve each
/// requested label in O(1) without rebuilding the per-call pointer-key
/// `FxHashMap<&IndexLabel, Vec<usize>>` over the whole index every time.
static INDEX_INT64_POS_LOOKUP_CACHE: OnceLock<Mutex<Int64PositionLookupCache>> = OnceLock::new();
/// Each entry can hold a whole-index hashtable (O(n) memory), so bound the
/// entry count far more tightly than the boolean equality cache. The common
/// case is a handful of distinct loc'd frames; the cap only trips under
/// pathological churn, where a full clear (rebuild on next miss) is cheaper
/// than unbounded retention.
const INDEX_INT64_POS_LOOKUP_CACHE_MAX: usize = 64;
fn next_index_label_identity() -> u64 {
INDEX_LABEL_ID_COUNTER.fetch_add(1, AtomicOrdering::Relaxed)
}
/// Build-or-fetch the cached first-occurrence `i64 -> position` table for an
/// index lineage. `values` must be the index's raw `i64` view. Duplicate labels
/// retain their first position, matching pandas `get_loc` scalar lookup
/// semantics.
fn int64_position_lookup_cached(identity: u64, values: &[i64]) -> SharedInt64PositionLookup {
let cache = INDEX_INT64_POS_LOOKUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
if let Some(existing) = cache
.lock()
.expect("index int64 position lookup cache poisoned")
.get(&identity)
.cloned()
{
return existing;
}
let mut map: Int64PositionLookup = FxHashMap::default();
map.reserve(values.len());
for (pos, &value) in values.iter().enumerate() {
map.entry(value).or_insert(pos);
}
let arc = Arc::new(map);
let mut guard = cache
.lock()
.expect("index int64 position lookup cache poisoned");
if guard.len() >= INDEX_INT64_POS_LOOKUP_CACHE_MAX {
guard.clear();
}
Arc::clone(guard.entry(identity).or_insert(arc))
}
/// First-occurrence `String -> position` lookup tables for unique all-Utf8
/// indexes, cached by runtime label identity. The value is `Option`: `None`
/// records "this index is not all-Utf8" so the warm path stays O(1) instead of
/// rescanning a non-Utf8 index on every `loc` call.
static INDEX_UTF8_POS_LOOKUP_CACHE: OnceLock<Mutex<Utf8PositionLookupCache>> = OnceLock::new();
/// Each entry can hold a whole index's worth of boxed strings, so cap the entry
/// count tightly (utf8 entries are heavier than the i64 ones).
const INDEX_UTF8_POS_LOOKUP_CACHE_MAX: usize = 16;
/// Build-or-fetch the cached first-occurrence `String -> position` table for an
/// index lineage. Returns `None` (and caches that verdict) when the index is
/// not entirely Utf8. The caller has already proven the index is unique, so
/// first occurrence == only occurrence.
fn utf8_position_lookup_cached(
identity: u64,
index_labels: &[IndexLabel],
) -> Option<SharedUtf8PositionLookup> {
let cache = INDEX_UTF8_POS_LOOKUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
if let Some(existing) = cache
.lock()
.expect("index utf8 position lookup cache poisoned")
.get(&identity)
.cloned()
{
return existing;
}
let mut map: Utf8PositionLookup = FxHashMap::default();
map.reserve(index_labels.len());
let mut all_utf8 = true;
for (pos, label) in index_labels.iter().enumerate() {
match label {
IndexLabel::Utf8(value) => {
map.insert(value.as_str().into(), pos);
}
_ => {
all_utf8 = false;
break;
}
}
}
let result = if all_utf8 { Some(Arc::new(map)) } else { None };
let mut guard = cache
.lock()
.expect("index utf8 position lookup cache poisoned");
if guard.len() >= INDEX_UTF8_POS_LOOKUP_CACHE_MAX {
guard.clear();
}
guard.entry(identity).or_insert(result).clone()
}
/// First-occurrence `Datetime64-ns -> position` lookup tables for unique
/// all-Datetime64 indexes (the common pandas time-series index), cached by
/// runtime label identity. `Datetime64(i64)` is ns-backed, so this mirrors the
/// Int64 lookup but reads the `Datetime64` label variant. The value is
/// `Option`: `None` records "not all Datetime64" so the warm path stays O(1).
static INDEX_DATETIME_POS_LOOKUP_CACHE: OnceLock<Mutex<Datetime64PositionLookupCache>> =
OnceLock::new();
const INDEX_DATETIME_POS_LOOKUP_CACHE_MAX: usize = 64;
/// Build-or-fetch the cached first-occurrence ns->position table for a
/// Datetime64 index lineage. Returns `None` (and caches that verdict) when the
/// index is not entirely Datetime64. Caller has proven uniqueness, so first ==
/// only occurrence.
fn datetime64_position_lookup_cached(
identity: u64,
index_labels: &[IndexLabel],
) -> Option<SharedInt64PositionLookup> {
let cache = INDEX_DATETIME_POS_LOOKUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
if let Some(existing) = cache
.lock()
.expect("index datetime position lookup cache poisoned")
.get(&identity)
.cloned()
{
return existing;
}
let mut map: Int64PositionLookup = FxHashMap::default();
map.reserve(index_labels.len());
let mut all_datetime = true;
for (pos, label) in index_labels.iter().enumerate() {
match label {
IndexLabel::Datetime64(ns) => {
map.insert(*ns, pos);
}
_ => {
all_datetime = false;
break;
}
}
}
let result = if all_datetime {
Some(Arc::new(map))
} else {
None
};
let mut guard = cache
.lock()
.expect("index datetime position lookup cache poisoned");
if guard.len() >= INDEX_DATETIME_POS_LOOKUP_CACHE_MAX {
guard.clear();
}
guard.entry(identity).or_insert(result).clone()
}
/// Per-lineage first-occurrence ns->position table for a Timedelta64 index.
/// Exact sibling of `INDEX_DATETIME_POS_LOOKUP_CACHE`: `Timedelta64(i64)` is
/// also ns-backed, so the same i64->pos table serves `loc[[td]]` on a
/// TimedeltaIndex (the deferred mirror of the Datetime64 batch resolver).
static INDEX_TIMEDELTA_POS_LOOKUP_CACHE: OnceLock<Mutex<Timedelta64PositionLookupCache>> =
OnceLock::new();
const INDEX_TIMEDELTA_POS_LOOKUP_CACHE_MAX: usize = 64;
/// Build-or-fetch the cached first-occurrence ns->position table for a
/// Timedelta64 index lineage. Returns `None` (and caches that verdict) when the
/// index is not entirely Timedelta64. Caller has proven uniqueness, so first ==
/// only occurrence.
fn timedelta64_position_lookup_cached(
identity: u64,
index_labels: &[IndexLabel],
) -> Option<SharedInt64PositionLookup> {
let cache = INDEX_TIMEDELTA_POS_LOOKUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
if let Some(existing) = cache
.lock()
.expect("index timedelta position lookup cache poisoned")
.get(&identity)
.cloned()
{
return existing;
}
let mut map: Int64PositionLookup = FxHashMap::default();
map.reserve(index_labels.len());
let mut all_timedelta = true;
for (pos, label) in index_labels.iter().enumerate() {
match label {
IndexLabel::Timedelta64(ns) => {
map.insert(*ns, pos);
}
_ => {
all_timedelta = false;
break;
}
}
}
let result = if all_timedelta {
Some(Arc::new(map))
} else {
None
};
let mut guard = cache
.lock()
.expect("index timedelta position lookup cache poisoned");
if guard.len() >= INDEX_TIMEDELTA_POS_LOOKUP_CACHE_MAX {
guard.clear();
}
guard.entry(identity).or_insert(result).clone()
}
/// Shared contiguous-Utf8 label backing: a byte buffer + `n+1` offsets, row `i`
/// being `bytes[offsets[i]..offsets[i+1]]` (br-frankenpandas-nbspq).
type Utf8LabelBacking = (Arc<[u8]>, Arc<[usize]>);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Int64UnitRangeLabels {
start: i64,
len: usize,
}
impl Int64UnitRangeLabels {
fn new(start: i64, len: usize) -> Option<Self> {
if len > 0 {
let last_offset = i64::try_from(len.checked_sub(1)?).ok()?;
start.checked_add(last_offset)?;
}
Some(Self { start, len })
}
fn materialize(self) -> Vec<IndexLabel> {
let mut labels = Vec::with_capacity(self.len);
for offset in 0..self.len {
let offset = i64::try_from(offset).expect("validated Int64 unit range length");
labels.push(IndexLabel::Int64(
self.start
.checked_add(offset)
.expect("validated Int64 unit range end"),
));
}
labels
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Int64AffineLabels {
start: i64,
step: i64,
len: usize,
}
impl Int64AffineLabels {
fn new(start: i64, step: i64, len: usize) -> Option<Self> {
if len > 1 && step == 0 {
return None;
}
if len > 0 {
let last_index = i64::try_from(len.checked_sub(1)?).ok()?;
let span = step.checked_mul(last_index)?;
start.checked_add(span)?;
}
Some(Self { start, step, len })
}
fn materialize(self) -> Vec<IndexLabel> {
let mut labels = Vec::with_capacity(self.len);
let mut value = self.start;
for offset in 0..self.len {
labels.push(IndexLabel::Int64(value));
if offset + 1 < self.len {
value = value
.checked_add(self.step)
.expect("validated Int64 affine range end");
}
}
labels
}
fn materialize_datetime64(self) -> Vec<IndexLabel> {
let mut labels = Vec::with_capacity(self.len);
let mut value = self.start;
for offset in 0..self.len {
labels.push(IndexLabel::Datetime64(value));
if offset + 1 < self.len {
value = value
.checked_add(self.step)
.expect("validated Datetime64 affine range end");
}
}
labels
}
fn materialize_i64(self) -> Vec<i64> {
let mut labels = Vec::with_capacity(self.len);
let mut value = self.start;
for offset in 0..self.len {
labels.push(value);
if offset + 1 < self.len {
value = value
.checked_add(self.step)
.expect("validated Int64 affine range end");
}
}
labels
}
fn value_at(self, position: usize) -> i64 {
let offset = i64::try_from(position).expect("validated Int64 affine range length");
let delta = self
.step
.checked_mul(offset)
.expect("validated Int64 affine range end");
self.start
.checked_add(delta)
.expect("validated Int64 affine range end")
}
fn position(self, target: i64) -> Option<usize> {
if self.len == 0 {
return None;
}
if self.step == 0 {
return (self.len == 1 && target == self.start).then_some(0);
}
let offset = target.checked_sub(self.start)?;
if offset.checked_rem(self.step)? != 0 {
return None;
}
let pos = offset.checked_div(self.step)?;
let pos = usize::try_from(pos).ok()?;
(pos < self.len).then_some(pos)
}
fn equals_slice(self, labels: &[IndexLabel]) -> bool {
labels.len() == self.len
&& labels.iter().enumerate().all(|(offset, label)| {
let Ok(offset) = i64::try_from(offset) else {
return false;
};
let Some(delta) = self.step.checked_mul(offset) else {
return false;
};
matches!(
label,
IndexLabel::Int64(value)
if self.start.checked_add(delta).is_some_and(|expected| *value == expected)
)
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Int64TwoAffineLabels {
first: Int64AffineLabels,
second: Int64AffineLabels,
}
impl Int64TwoAffineLabels {
fn new(first: Int64AffineLabels, second: Int64AffineLabels) -> Option<Self> {
first.len.checked_add(second.len)?;
Some(Self { first, second })
}
fn len(self) -> usize {
self.first
.len
.checked_add(self.second.len)
.expect("validated two-run Int64 index length")
}
fn value_at(self, position: usize) -> i64 {
if position < self.first.len {
self.first.value_at(position)
} else {
self.second.value_at(position - self.first.len)
}
}
fn materialize(self) -> Vec<IndexLabel> {
let mut labels = Vec::with_capacity(self.len());
labels.extend(self.first.materialize());
labels.extend(self.second.materialize());
labels
}
fn materialize_i64(self) -> Vec<i64> {
let mut labels = Vec::with_capacity(self.len());
labels.extend(self.first.materialize_i64());
labels.extend(self.second.materialize_i64());
labels
}
}
#[derive(Debug, Clone)]
struct Int64StridedLabels {
values: Arc<Vec<i64>>,
start: usize,
step: usize,
len: usize,
}
impl Int64StridedLabels {
fn new(values: Arc<Vec<i64>>, start: usize, step: usize, len: usize) -> Option<Self> {
if len > 1 && step == 0 {
return None;
}
if len > 0 {
let last = start.checked_add(step.checked_mul(len.checked_sub(1)?)?)?;
if last >= values.len() {
return None;
}
}
Some(Self {
values,
start,
step,
len,
})
}
fn materialize(self) -> Vec<IndexLabel> {
let mut labels = Vec::with_capacity(self.len);
let mut pos = self.start;
for offset in 0..self.len {
labels.push(IndexLabel::Int64(self.values[pos]));
if offset + 1 < self.len {
pos = pos
.checked_add(self.step)
.expect("validated Int64 strided range end");
}
}
labels
}
fn materialize_i64(self) -> Vec<i64> {
let mut labels = Vec::with_capacity(self.len);
let mut pos = self.start;
for offset in 0..self.len {
labels.push(self.values[pos]);
if offset + 1 < self.len {
pos = pos
.checked_add(self.step)
.expect("validated Int64 strided range end");
}
}
labels
}
}
#[derive(Debug, Clone)]
struct MaterializedLabelSlice {
labels: Arc<Vec<IndexLabel>>,
start: usize,
len: usize,
}
impl MaterializedLabelSlice {
fn new(labels: Arc<Vec<IndexLabel>>, start: usize, len: usize) -> Option<Self> {
start.checked_add(len).filter(|end| *end <= labels.len())?;
Some(Self { labels, start, len })
}
fn as_slice(&self) -> &[IndexLabel] {
&self.labels[self.start..self.start + self.len]
}
}
struct IndexLabels {
/// Shared immutable label vector (br-frankenpandas-idxclone). Behind `Arc`
/// so cloning an `Index` is an O(1) refcount bump instead of an O(n)
/// `Vec<IndexLabel>` deep copy — the dominant cost of same-index binary ops
/// (`a + b` re-uses the operand index). Set once, never mutated, so sharing
/// is observationally identical to a private copy. The cell itself is
/// shared by clones too: a lazy backing's labels made by any clone (a
/// Series of a date_range resampled, sliced by label) serve them all,
/// where each clone made its own million again (br-frankenpandas-so0mr).
materialized: Arc<OnceLock<Arc<Vec<IndexLabel>>>>,
materialized_slice: Option<Arc<MaterializedLabelSlice>>,
int64_unit_range: Option<Int64UnitRangeLabels>,
int64_affine: Option<Int64AffineLabels>,
int64_two_affine: Option<Box<Int64TwoAffineLabels>>,
int64_strided: Option<Int64StridedLabels>,
datetime64_affine: Option<Int64AffineLabels>,
/// Lazy typed Int64 backing (br-frankenpandas-dxqpm). `Some(values)` once
/// computed means every label is `IndexLabel::Int64` and `values` is the
/// raw `i64` view; `None` once computed means the labels are not all
/// Int64. Pre-seeded by typed constructors so gathers/clones/drops of
/// Int64-labelled indexes stay on contiguous `i64` storage instead of the
/// 32 B enum representation.
int64_typed: OnceLock<Option<Arc<Vec<i64>>>>,
/// Lazy contiguous-Utf8 backing (br-frankenpandas-nbspq): `Some((bytes,
/// offsets))` means every label is `IndexLabel::Utf8(bytes[off[i]..off[i+1]])`
/// (valid UTF-8 by construction). Pre-seeded by `new_utf8_contiguous` so a
/// string-keyed result index (groupby keys, sort_values, set-ops) avoids the
/// per-label `String` alloc + `from_utf8` re-validation until something
/// actually needs the `Vec<IndexLabel>` view.
utf8_contiguous: Option<Utf8LabelBacking>,
}
impl IndexLabels {
fn new(labels: Vec<IndexLabel>) -> Self {
let materialized = OnceLock::new();
let _ = materialized.set(Arc::new(labels));
Self {
materialized: Arc::new(materialized),
materialized_slice: None,
int64_unit_range: None,
int64_affine: None,
int64_two_affine: None,
int64_strided: None,
datetime64_affine: None,
int64_typed: OnceLock::new(),
utf8_contiguous: None,
}
}
fn new_int64_unit_range(start: i64, len: usize) -> Option<Self> {
Some(Self {
materialized: Arc::default(),
materialized_slice: None,
int64_unit_range: Some(Int64UnitRangeLabels::new(start, len)?),
int64_affine: None,
int64_two_affine: None,
int64_strided: None,
datetime64_affine: None,
int64_typed: OnceLock::new(),
utf8_contiguous: None,
})
}
fn new_int64_affine(start: i64, step: i64, len: usize) -> Option<Self> {
if step == 1 {
return Self::new_int64_unit_range(start, len);
}
Some(Self {
materialized: Arc::default(),
materialized_slice: None,
int64_unit_range: None,
int64_affine: Some(Int64AffineLabels::new(start, step, len)?),
int64_two_affine: None,
int64_strided: None,
datetime64_affine: None,
int64_typed: OnceLock::new(),
utf8_contiguous: None,
})
}
fn new_int64_two_affine(first: Int64AffineLabels, second: Int64AffineLabels) -> Option<Self> {
Some(Self {
materialized: Arc::default(),
materialized_slice: None,
int64_unit_range: None,
int64_affine: None,
int64_two_affine: Some(Box::new(Int64TwoAffineLabels::new(first, second)?)),
int64_strided: None,
datetime64_affine: None,
int64_typed: OnceLock::new(),
utf8_contiguous: None,
})
}
fn new_int64_strided(
values: Arc<Vec<i64>>,
start: usize,
step: usize,
len: usize,
) -> Option<Self> {
Some(Self {
materialized: Arc::default(),
materialized_slice: None,
int64_unit_range: None,
int64_affine: None,
int64_two_affine: None,
int64_strided: Some(Int64StridedLabels::new(values, start, step, len)?),
datetime64_affine: None,
int64_typed: OnceLock::new(),
utf8_contiguous: None,
})
}
fn new_int64_values(values: Arc<Vec<i64>>) -> Self {
let int64_typed = OnceLock::new();
let _ = int64_typed.set(Some(values));
Self {
materialized: Arc::default(),
materialized_slice: None,
int64_unit_range: None,
int64_affine: None,
int64_two_affine: None,
int64_strided: None,
datetime64_affine: None,
int64_typed,
utf8_contiguous: None,
}
}
fn new_datetime64_affine(start: i64, step: i64, len: usize) -> Option<Self> {
Some(Self {
materialized: Arc::default(),
materialized_slice: None,
int64_unit_range: None,
int64_affine: None,
int64_two_affine: None,
int64_strided: None,
datetime64_affine: Some(Int64AffineLabels::new(start, step, len)?),
int64_typed: OnceLock::new(),
utf8_contiguous: None,
})
}
fn new_utf8_contiguous(bytes: Arc<[u8]>, offsets: Arc<[usize]>) -> Self {
debug_assert!(!offsets.is_empty());
debug_assert_eq!(*offsets.last().expect("non-empty"), bytes.len());
Self {
materialized: Arc::default(),
materialized_slice: None,
int64_unit_range: None,
int64_affine: None,
int64_two_affine: None,
int64_strided: None,
datetime64_affine: None,
int64_typed: OnceLock::new(),
utf8_contiguous: Some((bytes, offsets)),
}
}
fn as_slice(&self) -> &[IndexLabel] {
if let Some(slice) = &self.materialized_slice {
return slice.as_slice();
}
self.materialized
.get_or_init(|| {
if let Some(range) = self.int64_unit_range {
return Arc::new(range.materialize());
}
if let Some(range) = self.int64_affine {
return Arc::new(range.materialize());
}
if let Some(runs) = &self.int64_two_affine {
let runs = **runs;
return Arc::new(runs.materialize());
}
if let Some((bytes, offsets)) = &self.utf8_contiguous {
return Arc::new(
offsets
.windows(2)
.map(|w| {
IndexLabel::Utf8(
std::str::from_utf8(&bytes[w[0]..w[1]])
.expect("contiguous utf8 index buffer is valid")
.to_owned(),
)
})
.collect(),
);
}
if let Some(range) = self.datetime64_affine {
return Arc::new(range.materialize_datetime64());
}
if let Some(strided) = self.int64_strided.clone() {
return Arc::new(strided.materialize());
}
let values = self
.int64_typed
.get()
.and_then(Option::as_ref)
.expect("lazy index labels require a typed or range backing");
Arc::new(values.iter().copied().map(IndexLabel::Int64).collect())
})
.as_slice()
}
fn to_owned_labels(&self) -> Vec<IndexLabel> {
if let Some(slice) = &self.materialized_slice {
return slice.as_slice().to_vec();
}
if let Some(range) = self.int64_unit_range {
return range.materialize();
}
if let Some(range) = self.int64_affine {
return range.materialize();
}
if let Some(runs) = &self.int64_two_affine {
return runs.materialize();
}
if let Some(strided) = self.int64_strided.clone() {
return strided.materialize();
}
if let Some(range) = self.datetime64_affine {
return range.materialize_datetime64();
}
if let Some((bytes, offsets)) = &self.utf8_contiguous {
return offsets
.windows(2)
.map(|w| {
IndexLabel::Utf8(
std::str::from_utf8(&bytes[w[0]..w[1]])
.expect("contiguous utf8 index buffer is valid")
.to_owned(),
)
})
.collect();
}
if let Some(Some(values)) = self.int64_typed.get() {
return values.iter().copied().map(IndexLabel::Int64).collect();
}
self.as_slice().to_vec()
}
fn len(&self) -> usize {
if let Some(slice) = &self.materialized_slice {
return slice.len;
}
if let Some(range) = self.int64_unit_range {
return range.len;
}
if let Some(range) = self.int64_affine {
return range.len;
}
if let Some(runs) = &self.int64_two_affine {
let runs = **runs;
return runs.len();
}
if let Some(strided) = &self.int64_strided {
return strided.len;
}
if let Some(range) = self.datetime64_affine {
return range.len;
}
if let Some((_, offsets)) = &self.utf8_contiguous {
return offsets.len() - 1;
}
if let Some(labels) = self.materialized.get() {
return labels.len();
}
if let Some(Some(values)) = self.int64_typed.get() {
return values.len();
}
self.as_slice().len()
}
fn slice(&self, start: usize, len: usize) -> Self {
let total_len = self.len();
let start = start.min(total_len);
let end = start.saturating_add(len).min(total_len);
let len = end - start;
if let Some(range) = self.int64_unit_range {
let offset = i64::try_from(start).expect("start within index length");
if let Some(next_start) = range.start.checked_add(offset)
&& let Some(labels) = Self::new_int64_unit_range(next_start, len)
{
return labels;
}
}
if let Some(range) = self.int64_affine {
let offset = i64::try_from(start).expect("start within index length");
if let Some(delta) = range.step.checked_mul(offset)
&& let Some(next_start) = range.start.checked_add(delta)
&& let Some(labels) = Self::new_int64_affine(next_start, range.step, len)
{
return labels;
}
}
if let Some(runs) = &self.int64_two_affine {
let runs = **runs;
if len == 0 {
if let Some(labels) = Self::new_int64_affine(runs.first.start, runs.first.step, 0) {
return labels;
}
} else if start + len <= runs.first.len {
let offset = i64::try_from(start).expect("start within index length");
if let Some(delta) = runs.first.step.checked_mul(offset)
&& let Some(next_start) = runs.first.start.checked_add(delta)
&& let Some(labels) = Self::new_int64_affine(next_start, runs.first.step, len)
{
return labels;
}
} else if start >= runs.first.len {
let second_start = start - runs.first.len;
let offset = i64::try_from(second_start).expect("start within index length");
if let Some(delta) = runs.second.step.checked_mul(offset)
&& let Some(next_start) = runs.second.start.checked_add(delta)
&& let Some(labels) = Self::new_int64_affine(next_start, runs.second.step, len)
{
return labels;
}
}
}
if let Some(strided) = &self.int64_strided
&& let Some(offset) = strided.step.checked_mul(start)
&& let Some(next_start) = strided.start.checked_add(offset)
&& let Some(labels) =
Self::new_int64_strided(Arc::clone(&strided.values), next_start, strided.step, len)
{
return labels;
}
if let Some(Some(values)) = self.int64_typed.get()
&& let Some(labels) = Self::new_int64_strided(Arc::clone(values), start, 1, len)
{
return labels;
}
if let Some(range) = self.datetime64_affine {
let offset = i64::try_from(start).expect("start within index length");
if let Some(delta) = range.step.checked_mul(offset)
&& let Some(next_start) = range.start.checked_add(delta)
&& let Some(labels) = Self::new_datetime64_affine(next_start, range.step, len)
{
return labels;
}
}
if let Some(slice) = &self.materialized_slice
&& let Some(next_start) = slice.start.checked_add(start)
&& let Some(view) =
MaterializedLabelSlice::new(Arc::clone(&slice.labels), next_start, len)
{
return Self {
materialized: Arc::default(),
materialized_slice: Some(Arc::new(view)),
int64_unit_range: None,
int64_affine: None,
int64_two_affine: None,
int64_strided: None,
datetime64_affine: None,
int64_typed: OnceLock::new(),
utf8_contiguous: None,
};
}
if let Some(labels) = self.materialized.get()
&& let Some(view) = MaterializedLabelSlice::new(Arc::clone(labels), start, len)
{
return Self {
materialized: Arc::default(),
materialized_slice: Some(Arc::new(view)),
int64_unit_range: None,
int64_affine: None,
int64_two_affine: None,
int64_strided: None,
datetime64_affine: None,
int64_typed: OnceLock::new(),
utf8_contiguous: None,
};
}
Self::new(self.as_slice()[start..end].to_vec())
}
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Whether this is a Datetime64-backed index containing the NaT sentinel.
///
/// Pandas treats every DatetimeIndex containing NaT as non-monotonic in
/// either direction. Keep the affine witness lazy while checking its
/// reserved sentinel; eager and sliced DatetimeIndex storage is scanned
/// directly without materializing any unrelated typed backing.
fn has_datetime64_nat(&self) -> bool {
if let Some(range) = self.datetime64_affine {
return range.position(i64::MIN).is_some();
}
if let Some(slice) = &self.materialized_slice {
return slice
.as_slice()
.iter()
.any(|label| matches!(label, IndexLabel::Datetime64(value) if *value == i64::MIN));
}
self.materialized.get().is_some_and(|labels| {
labels
.iter()
.any(|label| matches!(label, IndexLabel::Datetime64(value) if *value == i64::MIN))
})
}
/// The labels when they are held - materialized, or a slice of held
/// ones - without materializing a lazy backing.
fn held(&self) -> Option<&[IndexLabel]> {
if let Some(slice) = &self.materialized_slice {
return Some(slice.as_slice());
}
self.materialized.get().map(|labels| labels.as_slice())
}
fn int64_unit_range(&self) -> Option<Int64UnitRangeLabels> {
self.int64_unit_range
}
fn int64_affine_range(&self) -> Option<Int64AffineLabels> {
self.int64_unit_range
.map(|range| Int64AffineLabels {
start: range.start,
step: 1,
len: range.len,
})
.or(self.int64_affine)
}
fn datetime64_affine_range(&self) -> Option<Int64AffineLabels> {
self.datetime64_affine
}
/// The raw `i64` view of an all-Int64 label vector, computing and caching
/// it on first request. `None` means at least one label is not Int64.
fn int64_view(&self) -> Option<Arc<Vec<i64>>> {
self.int64_typed
.get_or_init(|| {
if let Some(range) = self.int64_unit_range {
let mut values = Vec::with_capacity(range.len);
for offset in 0..range.len {
let offset =
i64::try_from(offset).expect("validated Int64 unit range length");
values.push(
range
.start
.checked_add(offset)
.expect("validated Int64 unit range end"),
);
}
return Some(Arc::new(values));
}
if let Some(range) = self.int64_affine {
return Some(Arc::new(range.materialize_i64()));
}
if let Some(runs) = &self.int64_two_affine {
let runs = **runs;
return Some(Arc::new(runs.materialize_i64()));
}
if let Some(strided) = self.int64_strided.clone() {
return Some(Arc::new(strided.materialize_i64()));
}
if let Some(slice) = &self.materialized_slice {
let labels = slice.as_slice();
let mut values = Vec::with_capacity(labels.len());
for label in labels {
match label {
IndexLabel::Int64(value) => values.push(*value),
_ => return None,
}
}
return Some(Arc::new(values));
}
let labels = self.materialized.get()?;
let mut values = Vec::with_capacity(labels.len());
for label in labels.iter() {
match label {
IndexLabel::Int64(value) => values.push(*value),
_ => return None,
}
}
Some(Arc::new(values))
})
.clone()
}
/// Resolve this label collection against a lazy affine Int64 source without
/// materializing either affine range into an `i64` vector. The source is
/// unique by construction, so each raw target value has at most one
/// position; non-Int64 labels are necessarily misses.
fn affine_int64_indexer(&self, source: Int64AffineLabels) -> Vec<Option<usize>> {
let mut out = Vec::with_capacity(self.len());
let mut push_affine = |range: Int64AffineLabels| {
for position in 0..range.len {
out.push(source.position(range.value_at(position)));
}
};
if let Some(range) = self.int64_affine_range() {
push_affine(range);
return out;
}
if let Some(runs) = &self.int64_two_affine {
push_affine(runs.first);
push_affine(runs.second);
return out;
}
if let Some(strided) = &self.int64_strided {
for position in 0..strided.len {
let offset = strided
.step
.checked_mul(position)
.expect("validated Int64 strided range");
let index = strided
.start
.checked_add(offset)
.expect("validated Int64 strided range");
out.push(source.position(strided.values[index]));
}
return out;
}
if let Some(Some(values)) = self.int64_typed.get() {
out.extend(values.iter().map(|&value| source.position(value)));
return out;
}
// An integral float target is the int it equals (l5sed).
out.extend(
self.as_slice()
.iter()
.map(|label| label.exact_int().and_then(|value| source.position(value))),
);
out
}
/// The cached `i64` view if it has already been computed (never computes).
/// Outer `None` = not yet computed; `Some(None)` = known non-Int64.
fn cached_int64_view(&self) -> Option<Option<Arc<Vec<i64>>>> {
self.int64_typed.get().cloned()
}
fn has_lazy_int64_backing(&self) -> bool {
self.int64_unit_range.is_some()
|| self.int64_affine.is_some()
|| self.int64_two_affine.is_some()
|| self.int64_strided.is_some()
|| matches!(self.int64_typed.get(), Some(Some(_)))
}
fn take_i64_values(&self, indices: &[usize]) -> Option<Vec<i64>> {
let mut out = Vec::with_capacity(indices.len());
if let Some(range) = self.int64_unit_range {
for &idx in indices {
if idx >= range.len {
return None;
}
let offset = i64::try_from(idx).ok()?;
out.push(range.start.checked_add(offset)?);
}
return Some(out);
}
if let Some(range) = self.int64_affine {
for &idx in indices {
if idx >= range.len {
return None;
}
let offset = i64::try_from(idx).ok()?;
let delta = range.step.checked_mul(offset)?;
out.push(range.start.checked_add(delta)?);
}
return Some(out);
}
if let Some(runs) = &self.int64_two_affine {
let runs = **runs;
for &idx in indices {
if idx >= runs.len() {
return None;
}
out.push(runs.value_at(idx));
}
return Some(out);
}
if let Some(strided) = &self.int64_strided {
for &idx in indices {
if idx >= strided.len {
return None;
}
let offset = strided.step.checked_mul(idx)?;
let pos = strided.start.checked_add(offset)?;
out.push(*strided.values.get(pos)?);
}
return Some(out);
}
if let Some(Some(values)) = self.int64_typed.get() {
for &idx in indices {
if idx >= values.len() {
return None;
}
out.push(*values.get(idx)?);
}
return Some(out);
}
None
}
}
impl Clone for IndexLabels {
fn clone(&self) -> Self {
let int64_typed = OnceLock::new();
if let Some(view) = self.int64_typed.get() {
let _ = int64_typed.set(view.clone());
}
Self {
// One cell for every clone: labels made by any serve all.
materialized: Arc::clone(&self.materialized),
materialized_slice: self.materialized_slice.clone(),
int64_unit_range: self.int64_unit_range,
int64_affine: self.int64_affine,
int64_two_affine: self.int64_two_affine.clone(),
int64_strided: self.int64_strided.clone(),
datetime64_affine: self.datetime64_affine,
int64_typed,
utf8_contiguous: self.utf8_contiguous.clone(),
}
}
}
impl Default for IndexLabels {
fn default() -> Self {
Self::new(Vec::new())
}
}
impl fmt::Debug for IndexLabels {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.as_slice().fmt(f)
}
}
impl PartialEq for IndexLabels {
fn eq(&self, other: &Self) -> bool {
match (self.int64_affine_range(), other.int64_affine_range()) {
(Some(left), Some(right)) => left == right,
(Some(range), None) => range.equals_slice(other.as_slice()),
(None, Some(range)) => range.equals_slice(self.as_slice()),
(None, None) => self.as_slice() == other.as_slice(),
}
}
}
impl Eq for IndexLabels {}
/// Whether held datetime labels never descend (`INCREASING`) or never
/// ascend, in one pass comparing each stamp inline; NaT (i64::MIN) anywhere
/// answers false, as pandas' monotonic flags. None at the first label that
/// is not a datetime before any answer, for the generic order to decide.
/// The flags scanned the labels for NaT, then compared each pair through
/// IndexLabel::cmp, a call per pair: a fifth of a one-shot resample, which
/// asks at construction (br-frankenpandas-pirog).
fn held_datetimes_monotonic<const INCREASING: bool>(labels: &[IndexLabel]) -> Option<bool> {
let mut previous = if INCREASING { i64::MIN } else { i64::MAX };
for label in labels {
let IndexLabel::Datetime64(stamp) = *label else {
return None;
};
let reversed = if INCREASING {
stamp < previous
} else {
stamp > previous
};
if stamp == i64::MIN || reversed {
return Some(false);
}
previous = stamp;
}
Some(true)
}
impl std::ops::Deref for IndexLabels {
type Target = [IndexLabel];
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl<'a> IntoIterator for &'a IndexLabels {
type Item = &'a IndexLabel;
type IntoIter = std::slice::Iter<'a, IndexLabel>;
fn into_iter(self) -> Self::IntoIter {
self.as_slice().iter()
}
}
impl Serialize for IndexLabels {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_slice().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for IndexLabels {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Vec::<IndexLabel>::deserialize(deserializer).map(Self::new)
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Index {
#[serde(default)]
labels: IndexLabels,
/// Optional name for the index (matches pandas `Index.name`), typed:
/// `set_index(0)` names it the integer 0 (fvsao.64).
#[serde(default, skip_serializing_if = "Option::is_none")]
name: Option<LabelName>,
/// Runtime-only immutable identity for this label vector lineage.
#[serde(skip, default = "next_index_label_identity")]
label_identity: u64,
#[serde(skip)]
duplicate_cache: OnceLock<bool>,
/// AG-13: Cached sort order for adaptive backend selection.
#[serde(skip)]
sort_order_cache: OnceLock<SortOrder>,
/// The monotonic flags (increasing, decreasing) once asked, shared by
/// clones as the labels are: the labels never change, and pandas keeps
/// them on its engine - a repeated `is_monotonic_increasing` rescanned
/// the labels (0.12 ms over 200k stamps against pandas' 0.2 us), and a
/// resampler asked a clone each time (br-frankenpandas-pirog).
#[serde(skip)]
monotonic_cache: Arc<[OnceLock<bool>; 2]>,
/// Runtime-only cache for labels-derived AACE semantic fingerprints.
#[serde(skip)]
semantic_fingerprint_cache: OnceLock<String>,
/// The levels of the row `MultiIndex` whose flattened labels these are (a
/// multi-key groupby result, a column of a frame indexed by several
/// columns). The labels stay the flat keys every kernel handles; the levels
/// ride with them. Only [`Self::with_row_multiindex`] attaches them and only
/// `take`/`slice` carry them to new labels, so any other operation that
/// builds labels returns a flat index rather than mislabelled levels
/// (br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.9).
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "row_multiindex_serde"
)]
row_multiindex: Option<Arc<MultiIndex>>,
/// The time zone of datetime labels (pandas `DatetimeIndex.tz`): the
/// labels stay UTC nanoseconds and the zone is the wall clock they show.
/// Only [`Self::with_tz`] attaches it; [`Self::propagate_name`] carries it
/// to an index built from these labels while that index still holds
/// datetimes (take, slice, sort, unique, ...).
#[serde(default, skip_serializing_if = "Option::is_none")]
tz: Option<String>,
/// pandas' `DatetimeIndex.freq` as its freqstr ('D', '2D', 'W-SUN',
/// 'ME', '-1D'). Only [`Self::with_freq`] sets it; it survives a clone,
/// [`Self::slice`] and a [`Self::take`] of consecutive ascending
/// positions (pandas keeps it through a slice and a mask that selects a
/// run), and every other operation that builds labels drops it. Equality
/// ignores it, as pandas' `equals` does.
#[serde(default, skip_serializing_if = "Option::is_none")]
freq: Option<String>,
/// The `range(start, stop, step)` these labels are when they are a
/// pandas RangeIndex - a default index (a Series or DataFrame built
/// without one, reset_index, a matrix) or a slice of one - rather than
/// an Index that happens to hold 0..n. The stop is pandas' own (a
/// strided slice of `range(4)` is `range(1, 4, 2)`, an empty one
/// `range(3, 1)`). Only the range constructors ([`Self::from_range`],
/// [`Self::with_range_span`]) set it; a clone and a
/// slice keep it; a take, a mask or any rebuild of the labels drops it,
/// as pandas turns those into an Index. Equality ignores it.
#[serde(default, skip_serializing_if = "Option::is_none")]
range: Option<(i64, i64, i64)>,
/// pandas' dtype where the labels alone would read another (see
/// [`DeclaredDtype`]): object over numbers, an empty index's source
/// dtype, numpy's int32. Only [`Self::with_declared_dtype`] sets it;
/// [`Self::propagate_name`] carries it to an index built from these
/// labels. Equality ignores it, as pandas' `equals` does.
#[serde(default, skip_serializing_if = "Option::is_none")]
declared: Option<DeclaredDtype>,
/// pandas' `CategoricalIndex` metadata (see [`IndexCategories`]) when
/// these labels are one: a Series' or frame's index can be categorical
/// (it was a plain Index; br-frankenpandas-cld41). Only
/// [`Self::with_categories`] sets it; [`Self::propagate_name`] carries
/// it while every label is still one of the categories. Runtime
/// metadata, as the label identity; equality ignores it.
#[serde(skip)]
categories: Option<Arc<IndexCategories>>,
}
/// The categories a categorical [`Index`]'s labels are drawn from, in
/// their order, and whether that order ranks them - pandas'
/// `CategoricalIndex.categories` / `.ordered`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexCategories {
pub categories: Vec<IndexLabel>,
pub ordered: bool,
}
/// A dtype an [`Index`] is declared with where its labels alone read
/// another: pandas' `Index([1, 2], dtype=object)` holds the ints 1 and 2
/// under the object dtype (they became the strings '1' and '2';
/// br-frankenpandas-i20vm); an empty index keeps the dtype it was taken
/// from (`iloc[:0]` of an int64 index is int64, it read as object; dwyud);
/// a DatetimeIndex field (`.year`) is numpy's int32 (it was int64; pqjzo).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DeclaredDtype {
Object,
Int64,
Int32,
Float64,
Bool,
Datetime64,
Timedelta64,
}
impl DeclaredDtype {
/// pandas' name of the dtype.
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Object => "object",
Self::Int64 => "int64",
Self::Int32 => "int32",
Self::Float64 => "float64",
Self::Bool => "bool",
Self::Datetime64 => "datetime64[ns]",
Self::Timedelta64 => "timedelta64[ns]",
}
}
/// The declared dtype pandas' name reads as, None for another.
#[must_use]
pub fn of_name(name: &str) -> Option<Self> {
Some(match name {
"object" => Self::Object,
"int64" => Self::Int64,
"int32" => Self::Int32,
"float64" => Self::Float64,
"bool" => Self::Bool,
"datetime64[ns]" => Self::Datetime64,
"timedelta64[ns]" => Self::Timedelta64,
_ => return None,
})
}
}
/// The derived layout, with the row `MultiIndex` levels listed only when an
/// index carries them: a flat index prints exactly as before they existed.
impl fmt::Debug for Index {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut out = f.debug_struct("Index");
out.field("labels", &self.labels)
.field("name", &self.name)
.field("label_identity", &self.label_identity)
.field("duplicate_cache", &self.duplicate_cache)
.field("sort_order_cache", &self.sort_order_cache)
.field(
"semantic_fingerprint_cache",
&self.semantic_fingerprint_cache,
);
if let Some(levels) = &self.row_multiindex {
out.field("row_multiindex", levels);
}
if let Some(tz) = &self.tz {
out.field("tz", tz);
}
if let Some(freq) = &self.freq {
out.field("freq", freq);
}
if let Some(range) = &self.range {
out.field("range", range);
}
if let Some(declared) = &self.declared {
out.field("declared", declared);
}
if let Some(categories) = &self.categories {
out.field("categories", categories);
}
out.finish()
}
}
/// Serde for the shared `Arc` behind [`Index`]'s row `MultiIndex` levels:
/// serialized as the plain `MultiIndex` (the workspace builds serde without
/// its `rc` feature).
mod row_multiindex_serde {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::{Arc, MultiIndex};
#[allow(
clippy::ref_option,
reason = "serde's `with` contract passes the field by reference"
)]
pub fn serialize<S: Serializer>(
levels: &Option<Arc<MultiIndex>>,
serializer: S,
) -> Result<S::Ok, S::Error> {
levels.as_deref().serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Arc<MultiIndex>>, D::Error> {
Ok(Option::<MultiIndex>::deserialize(deserializer)?.map(Arc::new))
}
}
/// Equal labels in the same zone: pandas' `equals` is False between an aware
/// index and a naive one, or two zones, over the same instants.
impl PartialEq for Index {
fn eq(&self, other: &Self) -> bool {
self.tz == other.tz && self.labels_equal(other)
}
}
impl Eq for Index {}
fn detect_duplicates(labels: &[IndexLabel]) -> bool {
let mut seen = FxHashMap::<&IndexLabel, ()>::default();
for label in labels {
if seen.insert(label, ()).is_some() {
return true;
}
}
false
}
fn ordered_label_identity_pair(left: u64, right: u64) -> (u64, u64) {
if left <= right {
(left, right)
} else {
(right, left)
}
}
fn fixed_width_label_memory_usage(len: usize, width: usize) -> usize {
len.saturating_mul(width)
}
fn repeat_output_capacity(len: usize, repeats: usize) -> usize {
len.checked_mul(repeats)
.expect("index repeat output length overflow")
}
fn combined_output_capacity(left: usize, right: usize) -> usize {
left.checked_add(right)
.expect("index combined output length overflow")
}
fn int64_drop_values(labels_to_drop: &[IndexLabel]) -> Vec<i64> {
labels_to_drop
.iter()
.filter_map(|label| match label {
IndexLabel::Int64(value) => Some(*value),
_ => None,
})
.collect()
}
fn is_non_decreasing_i64(values: &[i64]) -> bool {
values.windows(2).all(|window| window[0] <= window[1])
}
fn drop_sorted_i64_values(values: &[i64], mut drop_values: Vec<i64>) -> Vec<i64> {
drop_values.sort_unstable();
drop_values.dedup();
let mut kept = Vec::with_capacity(values.len());
let mut drop_index = 0usize;
for &value in values {
while drop_index < drop_values.len() && drop_values[drop_index] < value {
drop_index += 1;
}
if drop_index < drop_values.len() && drop_values[drop_index] == value {
continue;
}
kept.push(value);
}
kept
}
fn insert_output_capacity(len: usize) -> usize {
len.checked_add(1)
.expect("index insert output length overflow")
}
fn aggregate_output_capacity(lengths: impl IntoIterator<Item = usize>) -> usize {
lengths
.into_iter()
.try_fold(0usize, |total, len| total.checked_add(len))
.expect("index aggregate output length overflow")
}
fn checked_cartesian_product_len(
lengths: impl IntoIterator<Item = usize>,
) -> Result<usize, IndexError> {
lengths.into_iter().try_fold(1usize, |total, len| {
total.checked_mul(len).ok_or_else(|| {
IndexError::InvalidArgument("MultiIndex product cardinality overflow".to_owned())
})
})
}
fn saturating_usize_sum(values: impl IntoIterator<Item = usize>) -> usize {
values.into_iter().fold(0usize, usize::saturating_add)
}
impl Index {
#[must_use]
pub fn new(labels: Vec<IndexLabel>) -> Self {
Self {
labels: IndexLabels::new(labels),
name: None,
label_identity: next_index_label_identity(),
duplicate_cache: OnceLock::new(),
sort_order_cache: OnceLock::new(),
monotonic_cache: Default::default(),
semantic_fingerprint_cache: OnceLock::new(),
row_multiindex: None,
tz: None,
freq: None,
range: None,
declared: None,
categories: None,
}
}
fn labels_equal(&self, other: &Self) -> bool {
if self.label_identity == other.label_identity {
return true;
}
let key = ordered_label_identity_pair(self.label_identity, other.label_identity);
let cache = INDEX_LABEL_EQUALITY_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
if let Some(equal) = cache
.lock()
.expect("index label equality cache poisoned")
.get(&key)
.copied()
{
return equal;
}
let equal = self.labels == other.labels;
let mut guard = cache.lock().expect("index label equality cache poisoned");
if guard.len() >= INDEX_LABEL_EQUALITY_CACHE_MAX {
guard.clear();
}
guard.insert(key, equal);
equal
}
/// Construct an index whose caller has already proven all labels unique.
///
/// This preserves the public `Index::new` surface while letting alignment
/// builders carry their uniqueness proof into the runtime duplicate cache.
#[must_use]
#[doc(hidden)]
pub fn new_known_unique(labels: Vec<IndexLabel>) -> Self {
debug_assert!(!detect_duplicates(&labels));
let index = Self::new(labels);
let _ = index.duplicate_cache.set(false);
index
}
/// Construct an index whose labels are the dense unit range
/// `start..start+len`, without allocating the label vector until a caller
/// asks for label materialization.
#[must_use]
#[doc(hidden)]
pub fn new_known_unique_int64_unit_range(start: i64, len: usize) -> Self {
let labels = IndexLabels::new_int64_unit_range(start, len)
.expect("validated Int64 unit range bounds");
let index = Self {
labels,
name: None,
label_identity: next_index_label_identity(),
duplicate_cache: OnceLock::new(),
sort_order_cache: OnceLock::new(),
monotonic_cache: Default::default(),
semantic_fingerprint_cache: OnceLock::new(),
row_multiindex: None,
tz: None,
freq: None,
range: None,
declared: None,
categories: None,
};
let _ = index.duplicate_cache.set(false);
let _ = index.sort_order_cache.set(SortOrder::AscendingInt64);
index
}
/// pandas' default index over `len` rows: the RangeIndex `range(0, len)`
/// a concat with `ignore_index`, a merge or a reader builds (they came
/// back as a plain Index of 0..len).
#[must_use]
pub fn default_range(len: usize) -> Self {
let span = i64::try_from(len).ok().map(|stop| (0, stop, 1));
Self::new_known_unique_int64_unit_range(0, len).with_range_span(span)
}
/// Construct an index whose labels are the affine Int64 sequence
/// `start + i * step`, without allocating the label vector until a caller
/// asks for label materialization.
#[must_use]
#[doc(hidden)]
pub fn new_known_unique_int64_affine_range(start: i64, step: i64, len: usize) -> Option<Self> {
let labels = IndexLabels::new_int64_affine(start, step, len)?;
let index = Self {
labels,
name: None,
label_identity: next_index_label_identity(),
duplicate_cache: OnceLock::new(),
sort_order_cache: OnceLock::new(),
monotonic_cache: Default::default(),
semantic_fingerprint_cache: OnceLock::new(),
row_multiindex: None,
tz: None,
freq: None,
range: None,
declared: None,
categories: None,
};
let _ = index.duplicate_cache.set(false);
if len <= 1 || step > 0 {
let _ = index.sort_order_cache.set(SortOrder::AscendingInt64);
}
Some(index)
}
fn new_int64_two_affine_runs(
first: Int64AffineLabels,
second: Int64AffineLabels,
) -> Option<Self> {
let labels = IndexLabels::new_int64_two_affine(first, second)?;
Some(Self {
labels,
name: None,
label_identity: next_index_label_identity(),
duplicate_cache: OnceLock::new(),
sort_order_cache: OnceLock::new(),
monotonic_cache: Default::default(),
semantic_fingerprint_cache: OnceLock::new(),
row_multiindex: None,
tz: None,
freq: None,
range: None,
declared: None,
categories: None,
})
}
fn new_known_unique_int64_two_affine_runs(
first: Int64AffineLabels,
second: Int64AffineLabels,
) -> Option<Self> {
let index = Self::new_int64_two_affine_runs(first, second)?;
let _ = index.duplicate_cache.set(false);
Some(index)
}
#[must_use]
pub fn from_i64(values: Vec<i64>) -> Self {
Self::from_i64_values(values)
}
/// Construct an index over Int64 labels backed by a contiguous `Vec<i64>`
/// (br-frankenpandas-dxqpm). Label materialization into `IndexLabel`s is
/// deferred until a caller asks for `labels()`; clones of the index share
/// the typed backing instead of deep-copying the enum vector.
#[must_use]
#[doc(hidden)]
pub fn from_i64_values(values: Vec<i64>) -> Self {
Self {
labels: IndexLabels::new_int64_values(Arc::new(values)),
name: None,
label_identity: next_index_label_identity(),
duplicate_cache: OnceLock::new(),
sort_order_cache: OnceLock::new(),
monotonic_cache: Default::default(),
semantic_fingerprint_cache: OnceLock::new(),
row_multiindex: None,
tz: None,
freq: None,
range: None,
declared: None,
categories: None,
}
}
/// Construct an Int64-labelled index as a strided view over an existing
/// typed backing. Unlike affine ranges, the source values may be duplicated
/// or unsorted, so uniqueness and sort caches are intentionally not seeded.
#[must_use]
#[doc(hidden)]
pub fn from_i64_strided_values(
values: Arc<Vec<i64>>,
start: usize,
step: usize,
len: usize,
) -> Option<Self> {
Some(Self {
labels: IndexLabels::new_int64_strided(values, start, step, len)?,
name: None,
label_identity: next_index_label_identity(),
duplicate_cache: OnceLock::new(),
sort_order_cache: OnceLock::new(),
monotonic_cache: Default::default(),
semantic_fingerprint_cache: OnceLock::new(),
row_multiindex: None,
tz: None,
freq: None,
range: None,
declared: None,
categories: None,
})
}
/// Construct an index over Utf8 labels backed by a contiguous byte buffer +
/// offsets (br-frankenpandas-nbspq). Label materialization into
/// `IndexLabel::Utf8` is deferred until `labels()` is asked for; clones share
/// the `Arc` backing. Caller guarantees `bytes` is valid UTF-8 and
/// `offsets` holds `n+1` ascending entries ending at `bytes.len()`.
#[must_use]
#[doc(hidden)]
pub fn from_utf8_contiguous(bytes: Arc<[u8]>, offsets: Arc<[usize]>) -> Self {
Self {
labels: IndexLabels::new_utf8_contiguous(bytes, offsets),
name: None,
label_identity: next_index_label_identity(),
duplicate_cache: OnceLock::new(),
sort_order_cache: OnceLock::new(),
monotonic_cache: Default::default(),
semantic_fingerprint_cache: OnceLock::new(),
row_multiindex: None,
tz: None,
freq: None,
range: None,
declared: None,
categories: None,
}
}
/// Raw `i64` view of an all-Int64 label vector, computing and caching it
/// on first request. `None` means at least one label is not Int64.
#[must_use]
#[doc(hidden)]
pub fn int64_label_values(&self) -> Option<Arc<Vec<i64>>> {
self.labels.int64_view()
}
/// The cached `i64` label view if already computed (never computes).
/// Outer `None` = not yet computed; `Some(None)` = known non-Int64.
#[must_use]
#[doc(hidden)]
pub fn cached_int64_label_values(&self) -> Option<Option<Arc<Vec<i64>>>> {
self.labels.cached_int64_view()
}
/// Whether the labels are ints held by a typed backing (a range, an
/// int64 buffer): every one an Int64, none missing - known without
/// materializing them. False says nothing about the labels.
#[must_use]
#[doc(hidden)]
pub fn has_int64_backing(&self) -> bool {
self.labels.has_lazy_int64_backing()
}
/// The kinds of label this index holds, worked out once per label
/// identity: typed ints and a datetime range answer without a scan, any
/// other labels after one pass, kept as the equality of two indexes is
/// (br-frankenpandas-nmna9: every `.index` rescanned a million labels to
/// pick its class, and DatetimeIndex::from_index again to check it).
#[must_use]
pub fn label_kinds(&self) -> LabelKinds {
if self.labels.is_empty() {
return LabelKinds::default();
}
if self.labels.has_lazy_int64_backing() {
return LabelKinds::INT64;
}
if self.labels.datetime64_affine_range().is_some() {
return LabelKinds::DATETIME64;
}
let cache = INDEX_LABEL_KINDS_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
if let Some(kinds) = cache
.lock()
.expect("index label kinds cache poisoned")
.get(&self.label_identity)
.copied()
{
return kinds;
}
let kinds = self
.labels
.iter()
.fold(LabelKinds::default(), |kinds, label| {
kinds.union(LabelKinds::of(label))
});
self.remember_label_kinds(kinds);
kinds
}
/// Keeps `kinds` as the label kinds of this label identity, for
/// [`Self::label_kinds`]: its own pass, or another that read every label
/// (a datetime ascent, br-frankenpandas-pirog).
fn remember_label_kinds(&self, kinds: LabelKinds) {
let cache = INDEX_LABEL_KINDS_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
let mut guard = cache.lock().expect("index label kinds cache poisoned");
if guard.len() >= INDEX_LABEL_KINDS_CACHE_MAX {
guard.clear();
}
guard.insert(self.label_identity, kinds);
}
#[must_use]
pub fn from_utf8(values: Vec<String>) -> Self {
Self::new(values.into_iter().map(IndexLabel::from).collect())
}
#[must_use]
pub fn from_timedelta64(nanos: Vec<i64>) -> Self {
Self::new(nanos.into_iter().map(IndexLabel::Timedelta64).collect())
.declared_if_empty(DeclaredDtype::Timedelta64)
}
#[must_use]
#[doc(hidden)]
pub fn from_datetime64_affine_range(start: i64, step: i64, len: usize) -> Option<Self> {
let labels = IndexLabels::new_datetime64_affine(start, step, len)?;
let index = Self {
labels,
name: None,
label_identity: next_index_label_identity(),
duplicate_cache: OnceLock::new(),
sort_order_cache: OnceLock::new(),
monotonic_cache: Default::default(),
semantic_fingerprint_cache: OnceLock::new(),
row_multiindex: None,
tz: None,
freq: None,
range: None,
declared: None,
categories: None,
};
let _ = index.duplicate_cache.set(false);
if len <= 1 || step > 0 {
let _ = index.sort_order_cache.set(SortOrder::AscendingDatetime64);
}
Some(index.declared_if_empty(DeclaredDtype::Datetime64))
}
#[must_use]
pub fn from_datetime64(nanos: Vec<i64>) -> Self {
Self::new(nanos.into_iter().map(IndexLabel::Datetime64).collect())
.declared_if_empty(DeclaredDtype::Datetime64)
}
/// No labels show a type, so an empty index built as `dtype` declares
/// it (an empty date_range under a Series was an object index;
/// br-frankenpandas-ce86r).
fn declared_if_empty(self, dtype: DeclaredDtype) -> Self {
if self.is_empty() {
self.with_declared_dtype(Some(dtype))
} else {
self
}
}
/// The `(first, step, len)` of a date_range's lazy datetime labels -
/// label `k` is `Datetime64(first + k * step)` - None for any other
/// labels (br-frankenpandas-so0mr).
#[must_use]
#[doc(hidden)]
pub fn datetime64_affine_labels(&self) -> Option<(i64, i64, usize)> {
self.labels
.datetime64_affine_range()
.map(|range| (range.start, range.step, range.len))
}
#[must_use]
pub fn len(&self) -> usize {
self.labels.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.labels.is_empty()
}
#[must_use]
pub fn labels(&self) -> &[IndexLabel] {
self.labels.as_slice()
}
#[must_use]
#[doc(hidden)]
pub fn int64_unit_range_labels(&self) -> Option<(i64, usize)> {
self.labels
.int64_unit_range()
.map(|range| (range.start, range.len))
}
#[must_use]
pub fn semantic_labels_fingerprint_with<F>(&self, compute: F) -> String
where
F: FnOnce(&[IndexLabel]) -> String,
{
self.semantic_fingerprint_cache
.get_or_init(|| compute(self.labels()))
.clone()
}
/// Return the index name (matches `pd.Index.name`): its text, and its
/// typed label when it is not a string ([`LabelName`]).
#[must_use]
pub fn name(&self) -> Option<&LabelName> {
self.name.as_ref()
}
/// Return a new index with the given name (matches `pd.Index.set_names`).
/// A [`LabelName`] keeps its typed label; text is a string name.
#[must_use]
pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
let mut idx = self.clone();
idx.name = name.map(Into::into);
idx
}
/// Alias for `set_names` — set the index name, returning a new `Index`.
#[must_use]
pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
self.set_names(Some(name))
}
/// Return a list of index names.
///
/// Matches `pd.Index.names`. For a flat (non-MultiIndex) index this returns
/// a single-element list with the current name (or `None`).
#[must_use]
pub fn names(&self) -> Vec<Option<String>> {
vec![self.name.clone().map(String::from)]
}
/// Set names from a list.
///
/// Matches `pd.Index.set_names([name])`. For flat index only the first
/// element is used. Panics if the list is empty.
#[must_use]
pub fn set_names_list(&self, names: &[Option<&str>]) -> Self {
assert!(
!names.is_empty(),
"set_names_list requires at least one name"
);
self.set_names(names[0])
}
/// Return the index as-is (flat index identity).
///
/// Matches `pd.Index.to_flat_index()`. For a non-MultiIndex this is a
/// no-op that returns a clone. For a MultiIndex it would convert tuples
/// to flat labels; attached row `MultiIndex` levels are dropped, leaving
/// the flat labels alone.
#[must_use]
pub fn to_flat_index(&self) -> Self {
let mut flat = self.clone();
flat.row_multiindex = None;
flat
}
/// Return a new index named `name` (`None` clears it); a
/// [`LabelName`] keeps its typed label.
#[must_use]
pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
self.set_names(name)
}
/// An index of `labels` taken from this one (a subset, a reordering, a
/// repeat): this index's name, and its zone while the labels are all
/// datetimes. `Index::new(labels)` plus the name dropped the zone, so a
/// tz-aware index came back as naive UTC labels (fvsao.60).
#[must_use]
pub fn relabeled(&self, labels: Vec<IndexLabel>) -> Self {
self.propagate_name(Self::new(labels))
}
/// Internal: propagate this index's name onto a newly created index.
fn propagate_name(&self, mut other: Self) -> Self {
other.name.clone_from(&self.name);
if self.tz.is_some() && other.holds_only_datetimes() {
other.tz.clone_from(&self.tz);
}
if let Some(categories) = &self.categories
&& other.labels_within(categories)
{
other.categories = Some(Arc::clone(categories));
}
other.with_dtype_of(self)
}
/// Whether every label (a missing one aside) is one of `categories`.
fn labels_within(&self, categories: &IndexCategories) -> bool {
let known: std::collections::HashSet<&IndexLabel> = categories.categories.iter().collect();
self.labels()
.iter()
.all(|label| label.is_missing() || known.contains(label))
}
/// pandas' `CategoricalIndex` metadata of these labels, None for an
/// index that is not categorical.
#[must_use]
pub fn categories(&self) -> Option<&IndexCategories> {
self.categories.as_deref()
}
/// These labels as a categorical index drawn from `categories` (None:
/// not categorical). A label outside the categories is an error, as a
/// CategoricalIndex cannot hold one.
pub fn with_categories(
mut self,
categories: Option<IndexCategories>,
) -> Result<Self, IndexError> {
if let Some(categories) = &categories
&& !self.labels_within(categories)
{
return Err(IndexError::InvalidArgument(
"a categorical index's labels must be among its categories".to_owned(),
));
}
self.categories = categories.map(Arc::new);
Ok(self)
}
/// These labels - selected, sliced or computed from `source`'s - under
/// the dtype pandas gives them: `source`'s declared object dtype (it
/// holds any labels), its int32 while they are ints, and for no label
/// at all `source`'s dtype, as pandas' empty slice or selection keeps it
/// (br-frankenpandas-i20vm / pqjzo / dwyud). A dtype these labels are
/// already declared with stays.
#[must_use]
pub fn with_dtype_of(mut self, source: &Self) -> Self {
if self.declared.is_none() {
self.declared = match source.declared {
Some(DeclaredDtype::Object) => Some(DeclaredDtype::Object),
Some(DeclaredDtype::Int32) if self.is_integer() => Some(DeclaredDtype::Int32),
declared if self.is_empty() => {
declared.or_else(|| DeclaredDtype::of_name(source.dtype()))
}
_ => None,
};
}
self
}
/// These labels under `declared` (see [`DeclaredDtype`]); None their
/// own dtype.
#[must_use]
pub fn with_declared_dtype(mut self, declared: Option<DeclaredDtype>) -> Self {
self.declared = declared;
self
}
/// The dtype these labels are declared with, if any.
#[must_use]
pub fn declared_dtype(&self) -> Option<DeclaredDtype> {
self.declared
}
/// Whether every label is a datetime (NaT included) - what a time zone
/// can describe.
fn holds_only_datetimes(&self) -> bool {
// A date_range's lazy range is datetimes without its labels made
// (br-frankenpandas-so0mr).
if self.labels.datetime64_affine_range().is_some() {
return true;
}
self.labels().iter().all(|label| {
matches!(
label,
IndexLabel::Datetime64(_) | IndexLabel::Null(fp_types::NullKind::NaT)
)
})
}
/// The time zone of these datetime labels (pandas `DatetimeIndex.tz`),
/// None for a naive index.
#[must_use]
pub fn tz(&self) -> Option<&str> {
self.tz.as_deref()
}
/// These labels shown in `tz` (None: naive). The labels are UTC
/// nanoseconds either way; a zone attaches only to an index of datetimes.
pub fn with_tz(mut self, tz: Option<&str>) -> Result<Self, IndexError> {
if let Some(zone) = tz {
fp_types::tz_validate(zone)?;
if !self.holds_only_datetimes() {
return Err(IndexError::InvalidArgument(format!(
"a time zone ('{zone}') describes datetime labels only"
)));
}
}
self.tz = tz.map(str::to_owned);
Ok(self)
}
/// pandas' `DatetimeIndex.freq` of these labels as its freqstr, None
/// when none is set (see the field).
#[must_use]
pub fn freq(&self) -> Option<&str> {
self.freq.as_deref()
}
/// These labels with `freq` (a pandas freqstr) set or cleared. The
/// caller vouches that the labels follow it.
#[must_use]
pub fn with_freq(mut self, freq: Option<String>) -> Self {
self.freq = freq;
self
}
/// The `range(start, stop, step)` these labels are as a pandas
/// RangeIndex (see the field), while the labels still hold exactly that
/// range (its length, first and last label).
#[must_use]
pub fn range_span(&self) -> Option<(i64, i64, i64)> {
let (start, stop, step) = self.range?;
let len = RangeIndex::new(start, stop, step).ok()?.len();
if len != self.len() {
return None;
}
if len == 0 {
return Some((start, stop, step));
}
let last =
i64::try_from(i128::from(start) + i128::from(step) * i128::try_from(len - 1).ok()?)
.ok()?;
let holds = if let Some(affine) = self.labels.int64_affine_range() {
affine.start == start && (len == 1 || affine.step == step)
} else {
let labels = self.labels();
labels.first() == Some(&IndexLabel::Int64(start))
&& labels.last() == Some(&IndexLabel::Int64(last))
};
holds.then_some((start, stop, step))
}
/// These labels marked as the pandas RangeIndex `span` (or unmarked);
/// [`Self::range_span`] answers only while the labels hold it.
#[must_use]
pub fn with_range_span(mut self, span: Option<(i64, i64, i64)>) -> Self {
self.range = span;
self
}
/// In place, [`Self::with_range_span`].
pub fn set_range_span(&mut self, span: Option<(i64, i64, i64)>) {
self.range = span;
}
/// The `range(start, stop, step)` Int64 labels in one constant nonzero
/// step (or none) are, the stop one step past the last label.
#[must_use]
pub fn int64_range_span(&self) -> Option<(i64, i64, i64)> {
let (start, step) = self.int64_range_step()?;
let stop = step.checked_mul(i64::try_from(self.len()).ok()?)?;
Some((start, start.checked_add(stop)?, step))
}
/// The RangeIndex that positions `start..stop` by `step` (as Python's
/// `slice.indices(len)` resolves a slice) of this RangeIndex are, as
/// Python slices a range: `range(4)[1::2]` is `range(1, 4, 2)`.
#[must_use]
pub fn sliced_range_span(&self, start: i64, stop: i64, step: i64) -> Option<(i64, i64, i64)> {
let (first, _, by) = self.range_span()?;
Some((
first.checked_add(start.checked_mul(by)?)?,
first.checked_add(stop.checked_mul(by)?)?,
by.checked_mul(step)?,
))
}
/// The (start, step) of Int64 labels in one constant nonzero step, as a
/// RangeIndex holds them ((0, 1) for no labels, the label and 1 for one).
#[must_use]
pub fn int64_range_step(&self) -> Option<(i64, i64)> {
// A lazy affine backing answers without materializing its labels.
if let Some(affine) = self.labels.int64_affine_range() {
let step = if affine.len > 1 { affine.step } else { 1 };
return (step != 0).then_some((affine.start, step));
}
let labels = self.labels();
let value = |label: &IndexLabel| match label {
IndexLabel::Int64(value) => Some(*value),
_ => None,
};
let Some(first) = labels.first() else {
return Some((0, 1));
};
let start = value(first)?;
let Some(second) = labels.get(1) else {
return Some((start, 1));
};
let step = value(second)?.checked_sub(start)?;
if step == 0 {
return None;
}
let mut expected = start;
for label in labels {
if value(label)? != expected {
return None;
}
expected = expected.checked_add(step).unwrap_or(expected);
}
Some((start, step))
}
/// Internal: if both indexes share the same name, return it; otherwise None.
/// Matches pandas behavior for binary set operations.
fn shared_name(&self, other: &Self) -> Option<LabelName> {
if self.name == other.name {
self.name.clone()
} else {
None
}
}
#[must_use]
pub fn has_duplicates(&self) -> bool {
if self.labels.int64_affine_range().is_some() {
return false;
}
*self.duplicate_cache.get_or_init(|| {
// Every `SortOrder::Ascending*` variant is STRICTLY ascending
// (`detect_sort_order` rejects equal neighbours with `a < b`), so a
// recognized sort order proves uniqueness with zero hashing
// (br-frankenpandas-idxdup). `sort_order()` is a single linear pass
// (itself cached and reused by the binary-search backends), far
// cheaper than the FxHashMap insert-per-label below; only genuinely
// unsorted indexes fall through to it.
if !matches!(self.sort_order(), SortOrder::Unsorted) {
return false;
}
// Typed all-Int64 fast path: inline `i64` duplicate detection with
// early exit instead of the pointer-keyed `FxHashMap<&IndexLabel>`.
if let Some(vals) = self.labels.int64_view() {
return Self::has_duplicates_i64(&vals);
}
detect_duplicates(self.labels())
})
}
/// Whether all index labels are unique.
///
/// Matches `pd.Index.is_unique`.
#[must_use]
pub fn is_unique(&self) -> bool {
!self.has_duplicates()
}
/// Get the position (integer location) of a label.
///
/// ⚠️ ONE position. `pd.Index.get_loc` returns THREE different types depending
/// on the index, and this collapses all of them to the first-or-some match.
/// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
/// ```text
/// Index([10,20,30]).get_loc(20) -> 1 int
/// Index([10,20,20,30]).get_loc(20) -> slice(1, 3) the whole run
/// Index([20,10,20]).get_loc(20) -> array([True,False,True]) a mask
/// Index([10,20]).get_loc(99) -> KeyError
/// ```
/// So on a duplicate-bearing index this answers a strictly weaker question than
/// pandas does. Use [`Self::get_loc_all`] when the index may hold duplicates;
/// it returns the position SET, which is what all three pandas shapes encode.
///
/// ⚠️ And on a SORTED duplicate run this is not even guaranteed to be the FIRST
/// match: `position` reaches `binary_search`, which may land on any element of
/// the run.
#[must_use]
pub fn get_loc(&self, label: &IndexLabel) -> Option<usize> {
self.position(label)
}
/// Every position at which `label` occurs, in index order.
///
/// The duplicate-safe counterpart to [`Self::get_loc`]. pandas expresses this
/// answer in three different return types — an int, a slice over the run, or a
/// boolean mask — and all three encode the same position SET, which is what this
/// returns. MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
/// ```text
/// [10,20,30] key 20 -> [1] (pandas: 1)
/// [10,20,20,30] key 20 -> [1, 2] (pandas: slice(1, 3))
/// [20,10,20] key 20 -> [0, 2] (pandas: [True, False, True])
/// [10,20] key 99 -> [] (pandas: KeyError)
/// [1.0,NaN,2.0,NaN] key NaN -> [1, 3] (pandas: [False,True,False,True])
/// ```
/// A MISSING key is an empty Vec rather than an error, matching this crate's
/// `Option`-returning `get_loc` rather than pandas' `KeyError`.
///
/// NaN matches NaN because `OrderedF64` compares on a canonical bit pattern, so
/// a NaN label is findable — as it is in pandas — even though `f64::NAN != f64::NAN`.
///
/// ⚠️ O(n) BY CONSTRUCTION, and deliberately not routed through `position`'s
/// optimized lookups: the affine-range, binary-search and cached-hash paths all
/// answer with a SINGLE position and cannot enumerate a duplicate run. A faster
/// implementation would need a label -> positions multimap, which nothing here
/// builds today.
#[must_use]
pub fn get_loc_all(&self, label: &IndexLabel) -> Vec<usize> {
self.labels()
.iter()
.enumerate()
.filter(|(_, candidate)| *candidate == label)
.map(|(position, _)| position)
.collect()
}
/// AG-13: Lazily detect and cache the sort order of this index.
#[must_use]
fn sort_order(&self) -> SortOrder {
if self
.labels
.int64_affine_range()
.is_some_and(|range| range.len <= 1 || range.step > 0)
{
return SortOrder::AscendingInt64;
}
*self.sort_order_cache.get_or_init(|| {
if let Some(values) = self.labels.int64_view() {
if values.len() <= 1 || values.windows(2).all(|pair| pair[0] < pair[1]) {
SortOrder::AscendingInt64
} else {
SortOrder::Unsorted
}
} else if let Some(range) = self.labels.datetime64_affine_range() {
if range.len <= 1 || range.step > 0 {
SortOrder::AscendingDatetime64
} else {
SortOrder::Unsorted
}
} else {
detect_sort_order(self.labels())
}
})
}
/// Returns `true` if this index is sorted (strictly ascending, no duplicates).
#[must_use]
pub fn is_sorted(&self) -> bool {
!matches!(self.sort_order(), SortOrder::Unsorted)
}
/// AG-13: Adaptive position lookup.
///
/// For sorted `Int64` or `Utf8` indexes, uses binary search (O(log n)).
/// For unsorted indexes, falls back to linear scan (O(n)).
#[must_use]
pub fn position(&self, needle: &IndexLabel) -> Option<usize> {
// An integral float key is the int it equals: the int paths below
// match Int64 keys, and every other path compares by value
// (br-frankenpandas-l5sed).
let as_int;
let needle = match (needle, needle.exact_int()) {
(IndexLabel::Float64(_), Some(int)) => {
as_int = IndexLabel::Int64(int);
&as_int
}
_ => needle,
};
if let (Some(range), IndexLabel::Int64(target)) = (self.labels.int64_affine_range(), needle)
{
return range.position(*target);
}
if let (Some(range), IndexLabel::Datetime64(target)) =
(self.labels.datetime64_affine_range(), needle)
{
return range.position(*target);
}
if self.labels.has_lazy_int64_backing() {
let IndexLabel::Int64(target) = needle else {
return None;
};
let values = self.labels.int64_view()?;
return if matches!(self.sort_order(), SortOrder::AscendingInt64) {
values.binary_search(target).ok()
} else {
int64_position_lookup_cached(self.label_identity, &values)
.get(target)
.copied()
};
}
match self.sort_order() {
SortOrder::AscendingInt64 => {
if let IndexLabel::Int64(target) = needle {
self.labels
.binary_search_by(|label| {
if let IndexLabel::Int64(v) = label {
v.cmp(target)
} else {
std::cmp::Ordering::Less
}
})
.ok()
} else {
None // Type mismatch: no Int64 label can match a Utf8 needle
}
}
SortOrder::AscendingUtf8 => {
if let IndexLabel::Utf8(target) = needle {
self.labels
.binary_search_by(|label| {
if let IndexLabel::Utf8(v) = label {
v.as_str().cmp(target.as_str())
} else {
std::cmp::Ordering::Less
}
})
.ok()
} else {
None
}
}
SortOrder::AscendingTimedelta64 => {
if let IndexLabel::Timedelta64(target) = needle {
self.labels
.binary_search_by(|label| {
if let IndexLabel::Timedelta64(v) = label {
v.cmp(target)
} else {
std::cmp::Ordering::Less
}
})
.ok()
} else {
None
}
}
SortOrder::AscendingDatetime64 => {
if let IndexLabel::Datetime64(target) = needle {
self.labels
.binary_search_by(|label| {
if let IndexLabel::Datetime64(v) = label {
v.cmp(target)
} else {
std::cmp::Ordering::Less
}
})
.ok()
} else {
None
}
}
SortOrder::Unsorted => self.labels.iter().position(|label| label == needle),
}
}
#[must_use]
pub fn position_map_first(&self) -> HashMap<IndexLabel, usize> {
let mut positions = HashMap::with_capacity(self.labels.len());
for (idx, label) in self.labels.iter().enumerate() {
positions.entry(label.clone()).or_insert(idx);
}
positions
}
fn position_map_first_ref(&self) -> FxHashMap<&IndexLabel, usize> {
let mut positions =
FxHashMap::with_capacity_and_hasher(self.labels.len(), Default::default());
for (idx, label) in self.labels.iter().enumerate() {
positions.entry(label).or_insert(idx);
}
positions
}
/// First-occurrence position of every `target` value within `haystack`,
/// over raw `i64` keys. Bit-identical to the `FxHashMap<&IndexLabel>` probe
/// (`position_map_first_ref` + `map.get`) for all-Int64 indexes — same
/// first-occurrence semantics — but the keys are INLINE `i64` rather than
/// pointers into the 32-byte `IndexLabel` enum vector, so each probe costs
/// one cache miss instead of two (hashtable slot + pointer-chase into the
/// label vector). A bounded value span uses a hash-free direct-address
/// table; otherwise an inline-key `FxHashMap<i64, usize>`.
fn get_indexer_i64(haystack: &[i64], target: &[i64]) -> Vec<Option<usize>> {
// Dense direct-address gate (mirrors the groupby/value-counts dense
// histogram cap): bounded span, ≤ 2^26 slots and ≤ 16× the key count.
if !haystack.is_empty() {
let mut min = haystack[0];
let mut max = haystack[0];
for &v in haystack {
if v < min {
min = v;
} else if v > max {
max = v;
}
}
let span = (max as i128 - min as i128 + 1) as u128;
if span <= (1u128 << 26) && span <= (haystack.len() as u128).saturating_mul(16) {
let span = span as usize;
let mut table = vec![usize::MAX; span];
for (idx, &v) in haystack.iter().enumerate() {
let slot = (v as i128 - min as i128) as usize;
if table[slot] == usize::MAX {
table[slot] = idx;
}
}
return target
.iter()
.map(|&v| {
if v < min || v > max {
return None;
}
let slot = (v as i128 - min as i128) as usize;
let pos = table[slot];
(pos != usize::MAX).then_some(pos)
})
.collect();
}
}
let mut map: FxHashMap<i64, usize> =
FxHashMap::with_capacity_and_hasher(haystack.len(), Default::default());
for (idx, &v) in haystack.iter().enumerate() {
map.entry(v).or_insert(idx);
}
target.iter().map(|&v| map.get(&v).copied()).collect()
}
fn get_indexer_non_unique_sorted_dense_i64(
source: &[i64],
targets: &[i64],
) -> Option<(Vec<isize>, Vec<usize>)> {
if !is_non_decreasing_i64(source) {
return None;
}
let (min, span) = Self::i64_dense_span(source)?;
let mut starts = vec![usize::MAX; span];
let mut ends = vec![0usize; span];
for (position, &label) in source.iter().enumerate() {
let slot = (label as i128 - min as i128) as usize;
if starts[slot] == usize::MAX {
starts[slot] = position;
}
ends[slot] = position + 1;
}
let mut indexer = Vec::with_capacity(targets.len());
let mut missing = Vec::new();
let span = span as i128;
for (target_position, &label) in targets.iter().enumerate() {
let offset = label as i128 - min as i128;
if offset < 0 || offset >= span {
indexer.push(-1);
missing.push(target_position);
continue;
}
let slot = offset as usize;
let start = starts[slot];
if start == usize::MAX {
indexer.push(-1);
missing.push(target_position);
continue;
}
indexer.extend(
(start..ends[slot]).map(|position| isize::try_from(position).unwrap_or(isize::MAX)),
);
}
Some((indexer, missing))
}
/// `(min, span)` of an `i64` slice when the span is dense enough for a
/// direct-address bitset (≤ 2^26 slots and ≤ 16× the element count),
/// else `None` (caller uses an inline-key hash set).
fn i64_dense_span(vals: &[i64]) -> Option<(i64, usize)> {
let first = *vals.first()?;
let mut min = first;
let mut max = first;
for &v in vals {
if v < min {
min = v;
} else if v > max {
max = v;
}
}
let span = (max as i128 - min as i128 + 1) as u128;
if span <= (1u128 << 26) && span <= (vals.len() as u128).saturating_mul(16) {
Some((min, span as usize))
} else {
None
}
}
/// Self-ordered, first-occurrence-deduplicated membership filter over raw
/// `i64` keys: keep each `a` value whose presence in `b` equals
/// `keep_present` (`true` ⇒ intersection, `false` ⇒ difference). Bit-
/// identical to the `FxHashMap<&IndexLabel>` filter
/// (`other.position_map_first_ref()` membership + a `seen` dedup) for
/// all-Int64 indexes, but membership and dedup use INLINE `i64` keys —
/// a dense bitset when the value span is bounded (the membership test then
/// fits in L2: 1 bit/slot vs the 16-byte pointer-keyed map entry that also
/// chases into the 32-byte enum vector), else an inline-key `FxHashSet<i64>`.
/// Extract the raw ns vector when EVERY label is the requested temporal
/// variant (`Datetime64` when `datetime`, else `Timedelta64`); `None` on the
/// first mismatch OR an empty input (so a degenerate empty set-op keeps the
/// generic fallback's dtype). Lets the temporal index reuse the i64 kernels
/// (`membership_filter_i64` / `union_i64`) — Datetime64/Timedelta64 are
/// ns-backed but `int64_view()` only matches `IndexLabel::Int64`, so without
/// this they fall to the pointer-key `FxHashMap<&IndexLabel>` path.
fn all_temporal_ns(labels: &[IndexLabel], datetime: bool) -> Option<Vec<i64>> {
if labels.is_empty() {
return None;
}
let mut out = Vec::with_capacity(labels.len());
for label in labels {
match (datetime, label) {
(true, IndexLabel::Datetime64(ns)) | (false, IndexLabel::Timedelta64(ns)) => {
out.push(*ns);
}
_ => return None,
}
}
Some(out)
}
/// Like [`Self::all_temporal_ns`] but returns `None` if ANY label is NaT (the
/// temporal missing sentinel). The dedup family (nunique / unique /
/// duplicated / drop_duplicates) has per-op NaT semantics (dropna-exclude vs
/// keep-one vs treat-as-value) that the generic fallback already encodes, so
/// a NaT-bearing temporal index bails to it; a no-NaT index reuses the i64
/// kernels, where a present timestamp behaves exactly like any other i64.
fn temporal_ns_present(&self, datetime: bool) -> Option<Vec<i64>> {
let labels = self.labels();
if labels.is_empty() {
return None;
}
let mut out = Vec::with_capacity(labels.len());
for label in labels {
match (datetime, label) {
(true, IndexLabel::Datetime64(ns)) | (false, IndexLabel::Timedelta64(ns)) => {
if label.is_missing() {
return None;
}
out.push(*ns);
}
_ => return None,
}
}
Some(out)
}
fn membership_filter_i64(a: &[i64], b: &[i64], keep_present: bool) -> Vec<i64> {
let mut out: Vec<i64> = Vec::new();
if a.is_empty() {
return out;
}
// `b` empty ⇒ nothing is present: intersection is empty, difference is
// all of `a` (deduplicated, self order).
if b.is_empty() && keep_present {
return out;
}
// Membership of `b`.
let b_dense = Self::i64_dense_span(b);
let (mut b_bits, mut b_hash) = (Vec::<u64>::new(), FxHashSet::<i64>::default());
if let Some((bmin, bspan)) = b_dense {
b_bits = vec![0u64; bspan.div_ceil(64)];
for &v in b {
let s = (v - bmin) as usize;
b_bits[s >> 6] |= 1u64 << (s & 63);
}
} else {
b_hash.reserve(b.len());
for &v in b {
b_hash.insert(v);
}
}
// First-occurrence dedup over the kept `a` values.
let a_dense = Self::i64_dense_span(a);
let mut seen_bits = Vec::<u64>::new();
let mut seen_hash = FxHashSet::<i64>::default();
if let Some((_, aspan)) = a_dense {
seen_bits = vec![0u64; aspan.div_ceil(64)];
}
for &v in a {
let in_b = match b_dense {
Some((bmin, bspan)) => {
let off = v as i128 - bmin as i128;
off >= 0 && (off as u128) < bspan as u128 && {
let s = off as usize;
(b_bits[s >> 6] >> (s & 63)) & 1 == 1
}
}
None => b_hash.contains(&v),
};
if in_b != keep_present {
continue;
}
let fresh = match a_dense {
Some((amin, _)) => {
let s = (v - amin) as usize;
let (w, bit) = (s >> 6, 1u64 << (s & 63));
let f = seen_bits[w] & bit == 0;
if f {
seen_bits[w] |= bit;
}
f
}
None => seen_hash.insert(v),
};
if fresh {
out.push(v);
}
}
out
}
/// Multiset union over raw `i64` keys, matching `Index.union(sort=False)`:
/// labels keep their first-seen order across `a` then `b`, while each label
/// is emitted the maximum of its multiplicities in either input.
fn union_i64(a: &[i64], b: &[i64]) -> Vec<i64> {
// pandas preserves the left index's physical order when the right
// operand is unique. Grouping the left counts by first-seen key would
// turn `[3, 1, 3, 2].union([2, 4, 1], sort=False)` into
// `[3, 3, 1, 2, 4]` instead of pandas' `[3, 1, 3, 2, 4]`.
if !Self::has_duplicates_i64(b) {
let mut out = a.to_vec();
let mut seen = FxHashSet::<i64>::default();
seen.reserve(combined_output_capacity(a.len(), b.len()));
seen.extend(a.iter().copied());
for &value in b {
if seen.insert(value) {
out.push(value);
}
}
return out;
}
let mut counts = FxHashMap::<i64, (usize, usize)>::default();
counts.reserve(combined_output_capacity(a.len(), b.len()));
let mut order = Vec::with_capacity(combined_output_capacity(a.len(), b.len()));
for &value in a {
let entry = counts.entry(value).or_insert((0, 0));
if entry.0 == 0 && entry.1 == 0 {
order.push(value);
}
entry.0 += 1;
}
for &value in b {
let entry = counts.entry(value).or_insert((0, 0));
if entry.0 == 0 && entry.1 == 0 {
order.push(value);
}
entry.1 += 1;
}
let mut out = Vec::with_capacity(combined_output_capacity(a.len(), b.len()));
for value in order {
let (left_count, right_count) = counts[&value];
out.extend(std::iter::repeat_n(value, left_count.max(right_count)));
}
out
}
/// Membership of each `haystack` value within `needles`, over raw `i64`
/// keys (dense bitset when the needle span is bounded, else inline-key
/// `FxHashSet<i64>`). Bit-identical to the `FxHashMap<&IndexLabel>`
/// `set.contains_key` probe for all-Int64 inputs.
fn isin_i64(haystack: &[i64], needles: &[i64]) -> Vec<bool> {
if needles.is_empty() {
return vec![false; haystack.len()];
}
match Self::i64_dense_span(needles) {
Some((min, span)) => {
let mut bits = vec![0u64; span.div_ceil(64)];
for &v in needles {
let s = (v - min) as usize;
bits[s >> 6] |= 1u64 << (s & 63);
}
haystack
.iter()
.map(|&v| {
let off = v as i128 - min as i128;
off >= 0
&& (off as u128) < span as u128
&& (bits[(off as usize) >> 6] >> ((off as usize) & 63)) & 1 == 1
})
.collect()
}
None => {
let set: FxHashSet<i64> = needles.iter().copied().collect();
haystack.iter().map(|&v| set.contains(&v)).collect()
}
}
}
/// Factorize raw `i64` keys: first-occurrence integer codes + the unique
/// values in first-occurrence order. Bit-identical to the
/// `FxHashMap<IndexLabel, isize>` path for all-Int64 indexes (which never
/// have a missing label, so no `-1` codes), with inline `i64` keys — a dense
/// direct-address code table when the value span is bounded, else an
/// inline-key `FxHashMap<i64, isize>`.
fn factorize_i64(vals: &[i64]) -> (Vec<isize>, Vec<i64>) {
let mut codes = Vec::with_capacity(vals.len());
let mut uniques = Vec::<i64>::new();
match Self::i64_dense_span(vals) {
Some((min, span)) => {
// `-1` marks an unseen slot; assigned codes are always `>= 0`.
let mut table = vec![-1isize; span];
for &v in vals {
let s = (v - min) as usize;
let mut code = table[s];
if code == -1 {
code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
table[s] = code;
uniques.push(v);
}
codes.push(code);
}
}
None => {
let mut positions: FxHashMap<i64, isize> =
FxHashMap::with_capacity_and_hasher(vals.len(), Default::default());
for &v in vals {
if let Some(&code) = positions.get(&v) {
codes.push(code);
} else {
let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
positions.insert(v, code);
uniques.push(v);
codes.push(code);
}
}
}
}
(codes, uniques)
}
/// Stable ascending argsort over raw Int64 labels. Equivalent to sorting
/// positions by `IndexLabel::Int64(value).cmp(...)`, but avoids enum
/// materialization/comparison for indexes that already carry typed Int64
/// backing. `sort_by_key` is stable, so duplicate labels keep their
/// original order just like the generic `IndexLabel` comparator path.
fn argsort_i64(vals: &[i64]) -> Vec<usize> {
let mut indices: Vec<usize> = (0..vals.len()).collect();
indices.sort_by_key(|&idx| vals[idx]);
indices
}
fn argsort_int64_affine(range: Int64AffineLabels) -> Vec<usize> {
if range.len <= 1 || range.step > 0 {
(0..range.len).collect()
} else {
(0..range.len).rev().collect()
}
}
/// Whether `vals` contains any duplicate, over raw `i64` keys with an
/// early exit. Bit-identical to `detect_duplicates` for all-Int64 indexes,
/// with inline keys (dense bitset when bounded, else `FxHashSet<i64>`).
fn has_duplicates_i64(vals: &[i64]) -> bool {
match Self::i64_dense_span(vals) {
Some((min, span)) => {
let mut bits = vec![0u64; span.div_ceil(64)];
for &v in vals {
let s = (v - min) as usize;
let (w, bit) = (s >> 6, 1u64 << (s & 63));
if bits[w] & bit != 0 {
return true;
}
bits[w] |= bit;
}
false
}
None => {
let mut seen: FxHashSet<i64> =
FxHashSet::with_capacity_and_hasher(vals.len(), Default::default());
for &v in vals {
if !seen.insert(v) {
return true;
}
}
false
}
}
}
/// First-occurrence-deduplicated unique values over raw `i64` keys, in
/// input order. Bit-identical to the `FxHashMap<&IndexLabel>` first-seen
/// filter for all-Int64 indexes, with inline `i64` dedup keys (dense bitset
/// when bounded, else `FxHashSet<i64>`).
fn unique_i64(vals: &[i64]) -> Vec<i64> {
let mut out: Vec<i64> = Vec::new();
let dense = Self::i64_dense_span(vals);
let mut seen_bits = Vec::<u64>::new();
let mut seen_hash = FxHashSet::<i64>::default();
if let Some((_, span)) = dense {
seen_bits = vec![0u64; span.div_ceil(64)];
} else {
seen_hash.reserve(vals.len());
}
for &v in vals {
let fresh = match dense {
Some((min, _)) => {
let s = (v - min) as usize;
let (w, bit) = (s >> 6, 1u64 << (s & 63));
let f = seen_bits[w] & bit == 0;
if f {
seen_bits[w] |= bit;
}
f
}
None => seen_hash.insert(v),
};
if fresh {
out.push(v);
}
}
out
}
/// Count distinct raw `i64` labels without constructing owned
/// `IndexLabel::Int64` uniques. Int64 labels are never missing, so this is
/// valid for both `dropna` modes.
fn nunique_i64(vals: &[i64]) -> usize {
let dense = Self::i64_dense_span(vals);
match dense {
Some((min, span)) => {
let mut seen_bits = vec![0u64; span.div_ceil(64)];
let mut count = 0usize;
for &v in vals {
let s = (v - min) as usize;
let (w, bit) = (s >> 6, 1u64 << (s & 63));
if seen_bits[w] & bit == 0 {
seen_bits[w] |= bit;
count += 1;
}
}
count
}
None => {
let mut seen =
FxHashSet::<i64>::with_capacity_and_hasher(vals.len(), Default::default());
for &v in vals {
seen.insert(v);
}
seen.len()
}
}
}
/// `duplicated` mask over raw `i64` keys — bit-identical to the
/// `FxHashMap<&IndexLabel>` path for all-Int64 indexes, with inline `i64`
/// keys (dense bitsets when the value span is bounded, else hash sets).
/// Every label's canonical float bits spread
/// ([`fp_types::spread_float_bits`]) as an i64 key when every label is a
/// Float64: bijective, so equal keys are exactly equal labels (-0.0 as
/// 0.0, NaN as NaN), for the i64 duplicate masks. None for any other
/// label (br-frankenpandas-bss5q.3).
fn float_label_keys(&self) -> Option<Vec<i64>> {
self.labels
.iter()
.map(|label| match label {
IndexLabel::Float64(value) => {
Some(fp_types::spread_float_bits(value.canonical_bits()) as i64)
}
_ => None,
})
.collect()
}
fn duplicated_i64(vals: &[i64], keep: DuplicateKeep) -> Vec<bool> {
let n = vals.len();
let mut result = vec![false; n];
let dense = Self::i64_dense_span(vals);
match keep {
DuplicateKeep::First | DuplicateKeep::Last => {
let mut seen_bits = Vec::<u64>::new();
let mut seen_hash = FxHashSet::<i64>::default();
if let Some((_, span)) = dense {
seen_bits = vec![0u64; span.div_ceil(64)];
} else {
seen_hash.reserve(n);
}
let mut mark = |i: usize| {
let v = vals[i];
let fresh = match dense {
Some((min, _)) => {
let s = (v - min) as usize;
let (w, bit) = (s >> 6, 1u64 << (s & 63));
let f = seen_bits[w] & bit == 0;
if f {
seen_bits[w] |= bit;
}
f
}
None => seen_hash.insert(v),
};
if !fresh {
result[i] = true;
}
};
if matches!(keep, DuplicateKeep::First) {
for i in 0..n {
mark(i);
}
} else {
for i in (0..n).rev() {
mark(i);
}
}
}
DuplicateKeep::None => {
// Two-bitset (seen / seen-again) ⇒ `result[i] = count > 1`.
match dense {
Some((min, span)) => {
let words = span.div_ceil(64);
let mut seen = vec![0u64; words];
let mut dup = vec![0u64; words];
for &v in vals {
let s = (v - min) as usize;
let (w, bit) = (s >> 6, 1u64 << (s & 63));
if seen[w] & bit == 0 {
seen[w] |= bit;
} else {
dup[w] |= bit;
}
}
for (i, &v) in vals.iter().enumerate() {
let s = (v - min) as usize;
result[i] = (dup[s >> 6] >> (s & 63)) & 1 == 1;
}
}
None => {
let mut counts: FxHashMap<i64, u32> =
FxHashMap::with_capacity_and_hasher(n, Default::default());
for &v in vals {
*counts.entry(v).or_insert(0) += 1;
}
for (i, &v) in vals.iter().enumerate() {
result[i] = counts[&v] > 1;
}
}
}
}
}
result
}
// ── Pandas Index Model: lookup and membership ──────────────────────
#[must_use]
pub fn contains(&self, label: &IndexLabel) -> bool {
self.position(label).is_some()
}
#[must_use]
pub fn get_indexer(&self, target: &Index) -> Vec<Option<usize>> {
// An affine Int64 source can answer every lookup from its arithmetic
// witness. Keep the target typed as well: materializing the source to
// an `Arc<Vec<i64>>` solely to reject a miss-heavy target made this
// otherwise O(m) operation pay an avoidable O(n) allocation and scan.
if let Some(source) = self.labels.int64_affine_range() {
return target.labels.affine_int64_indexer(source);
}
// When `self` is strictly ascending (any SortOrder::Ascending* ⟹
// globally IndexLabel::Ord-sorted and unique) we can resolve target
// positions without building the O(n) FxHashMap of `self`
// (br-frankenpandas-idxdup):
// * target also sorted ⇒ one two-pointer merge, O(n+m), no hashing;
// * target unsorted ⇒ binary-search each label, O(m log n).
// Both yield the same first-occurrence position the hash path returns
// (uniqueness makes "first" the only one); unsorted `self` keeps the
// hash path so a per-label scan never degrades to O(n·m).
if !matches!(self.sort_order(), SortOrder::Unsorted) {
if let (Some(labels), Some(targets)) =
(self.labels.int64_view(), target.labels.int64_view())
{
if !matches!(target.sort_order(), SortOrder::Unsorted) {
let mut out = Vec::with_capacity(targets.len());
let mut i = 0usize;
for &target in targets.iter() {
while i < labels.len() && labels[i] < target {
i += 1;
}
if i < labels.len() && labels[i] == target {
out.push(Some(i));
} else {
out.push(None);
}
}
return out;
}
return targets
.iter()
.map(|target| labels.binary_search(target).ok())
.collect();
}
let labels = self.labels();
let targets = target.labels();
if !matches!(target.sort_order(), SortOrder::Unsorted) {
let mut out = Vec::with_capacity(targets.len());
let mut i = 0usize;
for label in targets {
while i < labels.len() && labels[i] < *label {
i += 1;
}
if i < labels.len() && labels[i] == *label {
out.push(Some(i));
} else {
out.push(None);
}
}
return out;
}
return targets.iter().map(|label| self.position(label)).collect();
}
// Typed all-Int64 fast path: probe over raw `i64` keys (inline, one
// cache miss per lookup) instead of the `FxHashMap<&IndexLabel>` whose
// pointer keys force a second cache miss chasing into the 32-byte enum
// label vector — the dominant cost of unsorted Int64 get_indexer
// (~14× slower than pandas' inline-key khash). Bit-identical: same
// first-occurrence position per target label.
if let (Some(self_i64), Some(target_i64)) =
(self.labels.int64_view(), target.labels.int64_view())
{
// Unsorted UNIQUE Int64 self: reuse the identity-cached i64->pos
// map so repeated reindex/align/join don't rebuild it every call
// (pandas caches its int64 engine). Bit-identical first-occurrence;
// a duplicate self returns None and keeps the per-call builder.
if let Some(resolved) = self.unsorted_unique_int64_positions(target.labels()) {
return resolved;
}
return Self::get_indexer_i64(&self_i64, &target_i64);
}
// Unsorted UNIQUE non-Int64 self: route through the identity-cached
// position lookups (the loc batch resolvers) so repeated
// reindex/align/join against the same index don't rebuild the
// pointer-key `FxHashMap<&IndexLabel, usize>` each call — pandas caches
// its index engine for exactly this repeated-alignment pattern.
// Bit-identical: get_indexer self is unique, so first-occurrence ==
// only-occurrence == `position_map_first_ref().get()`; a duplicate or
// non-Utf8/non-Datetime self returns `None` from the resolvers and
// falls through to the unchanged map path.
if let Some(resolved) = self.unique_utf8_positions(target.labels()) {
return resolved;
}
if let Some(resolved) = self.unique_datetime64_positions(target.labels()) {
return resolved;
}
if let Some(resolved) = self.unique_timedelta64_positions(target.labels()) {
return resolved;
}
let map = self.position_map_first_ref();
target
.labels
.iter()
.map(|label| map.get(label).copied())
.collect()
}
/// Resolve a list-like label selector against a strictly ascending all-Int64
/// index without building the duplicate-expansion map.
///
/// `SortOrder::AscendingInt64` is strict, so the index is unique and each
/// requested label can yield at most one position. Missing requested
/// labels, or ones equal to no int (an integral Float64 is its int), are
/// represented as `None`; callers preserve their own
/// fail-closed error surface. Returns `None` only when this index is not a
/// sorted unique Int64 index and the duplicate-aware fallback must run.
#[must_use]
#[doc(hidden)]
pub fn sorted_unique_int64_positions(
&self,
labels: &[IndexLabel],
) -> Option<Vec<Option<usize>>> {
if !matches!(self.sort_order(), SortOrder::AscendingInt64) {
return None;
}
let values = self.labels.int64_view()?;
// An integral Float64 selector is the int it equals (l5sed).
Some(
labels
.iter()
.map(|label| {
label
.exact_int()
.and_then(|value| values.binary_search(&value).ok())
})
.collect(),
)
}
/// Resolve a list-like selector against an UNSORTED unique all-Int64 index
/// using a first-occurrence `i64 -> position` hashtable cached by the
/// index's runtime label identity, instead of rebuilding the per-call
/// pointer-key `FxHashMap<&IndexLabel, Vec<usize>>` over the whole index.
///
/// Returns `None` (so the caller keeps its duplicate-aware fallback) when
/// the index is strictly-ascending Int64 (use
/// [`Self::sorted_unique_int64_positions`]), has duplicate labels (pandas
/// returns every match, which needs the multimap), or is not all-Int64.
/// The index is unique here, so each requested label yields at most one
/// position; missing selectors, or ones equal to no int (an integral
/// Float64 is its int), map to `None` and callers preserve their own
/// fail-closed error surface.
/// Each of `targets`' position in these unique int labels (a typed
/// backing's), through the lookup kept per label identity - built once
/// for this index, as pandas keeps its engine - None for labels that are
/// not unique ints held typed (br-frankenpandas-mcq15).
#[must_use]
#[doc(hidden)]
pub fn unique_int64_positions_of(&self, targets: &[i64]) -> Option<Vec<Option<usize>>> {
if !self.labels.has_lazy_int64_backing() || self.has_duplicates() {
return None;
}
let values = self.labels.int64_view()?;
let lookup = int64_position_lookup_cached(self.label_identity, &values);
Some(
targets
.iter()
.map(|value| lookup.get(value).copied())
.collect(),
)
}
#[must_use]
#[doc(hidden)]
pub fn unsorted_unique_int64_positions(
&self,
labels: &[IndexLabel],
) -> Option<Vec<Option<usize>>> {
if matches!(self.sort_order(), SortOrder::AscendingInt64) {
return None;
}
if self.has_duplicates() {
return None;
}
let values = self.labels.int64_view()?;
let lookup = int64_position_lookup_cached(self.label_identity, &values);
// An integral Float64 selector is the int it equals (l5sed).
Some(
labels
.iter()
.map(|label| {
label
.exact_int()
.and_then(|value| lookup.get(&value).copied())
})
.collect(),
)
}
/// Resolve a list-like selector against a unique all-Utf8 index using a
/// first-occurrence `String -> position` hashtable cached by the index's
/// runtime label identity, instead of rebuilding the per-call pointer-key
/// `FxHashMap<&IndexLabel, Vec<usize>>` over the whole index.
///
/// Returns `None` (caller keeps its duplicate-aware fallback) when the index
/// has duplicate labels (pandas returns every match) or is not entirely
/// Utf8. The index is unique here, so each requested label yields at most
/// one position; missing or non-Utf8 selectors map to `None` and callers
/// preserve their own fail-closed error surface.
#[must_use]
#[doc(hidden)]
pub fn unique_utf8_positions(&self, labels: &[IndexLabel]) -> Option<Vec<Option<usize>>> {
if self.has_duplicates() {
return None;
}
let lookup = utf8_position_lookup_cached(self.label_identity, self.labels())?;
Some(
labels
.iter()
.map(|label| match label {
IndexLabel::Utf8(value) => lookup.get(value.as_str()).copied(),
_ => None,
})
.collect(),
)
}
/// Resolve a list-like selector against a unique all-Datetime64 index using
/// a first-occurrence ns->position hashtable cached by the index's runtime
/// label identity, instead of rebuilding the per-call pointer-key
/// `FxHashMap<&IndexLabel, Vec<usize>>`. This is the time-series `loc[[ts]]`
/// fast path.
///
/// Returns `None` (caller keeps its duplicate-aware fallback) when the index
/// has duplicate labels or is not entirely Datetime64. The index is unique
/// here, so each requested label yields at most one position; missing or
/// non-Datetime64 selectors map to `None` and callers preserve their own
/// fail-closed error surface.
#[must_use]
#[doc(hidden)]
pub fn unique_datetime64_positions(&self, labels: &[IndexLabel]) -> Option<Vec<Option<usize>>> {
if self.has_duplicates() {
return None;
}
let lookup = datetime64_position_lookup_cached(self.label_identity, self.labels())?;
Some(
labels
.iter()
.map(|label| match label {
IndexLabel::Datetime64(ns) => lookup.get(ns).copied(),
_ => None,
})
.collect(),
)
}
/// Resolve a list-like selector against a unique all-Timedelta64 index using
/// a first-occurrence ns->position hashtable cached by the index's runtime
/// label identity — the `loc[[td]]` fast path for a TimedeltaIndex. Exact
/// sibling of [`Self::unique_datetime64_positions`] (the deferred mirror of
/// the Datetime64 batch resolver). Returns `None` (caller keeps its
/// duplicate-aware pointer-key fallback) when the index has duplicates or is
/// not entirely Timedelta64; the index is unique here, so each requested
/// label yields at most one position and a missing/non-Timedelta64 selector
/// maps to `None`.
#[must_use]
#[doc(hidden)]
pub fn unique_timedelta64_positions(
&self,
labels: &[IndexLabel],
) -> Option<Vec<Option<usize>>> {
if self.has_duplicates() {
return None;
}
let lookup = timedelta64_position_lookup_cached(self.label_identity, self.labels())?;
Some(
labels
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(ns) => lookup.get(ns).copied(),
_ => None,
})
.collect(),
)
}
#[must_use]
pub fn isin(&self, values: &[IndexLabel]) -> Vec<bool> {
// Typed all-Int64 fast path: probe over raw `i64` keys. An all-Int64
// index matches the needles that equal an int - an Int64, or an
// integral Float64 (labels compare numbers by value; l5sed) - so the
// others are dropped without changing membership, bit-identical to
// the pointer-keyed `FxHashMap` probe but without the per-label
// enum-pointer cache miss.
if let Some(self_i64) = self.labels.int64_view() {
let needles: Vec<i64> = values.iter().filter_map(IndexLabel::exact_int).collect();
return Self::isin_i64(&self_i64, &needles);
}
let set: FxHashMap<&IndexLabel, ()> = values.iter().map(|v| (v, ())).collect();
self.labels.iter().map(|l| set.contains_key(l)).collect()
}
// ── Pandas Index Model: deduplication ──────────────────────────────
#[must_use]
pub fn is_monotonic_increasing(&self) -> bool {
*self.monotonic_cache[0].get_or_init(|| self.labels_ascend())
}
fn labels_ascend(&self) -> bool {
if let Some(answer) = self
.labels
.held()
.and_then(held_datetimes_monotonic::<true>)
{
// An ascent read every label as a datetime, none NaT: those are
// the label kinds, kept for the next asker (a resampler's axis
// check scanned them again on a fresh index).
if answer && !self.labels.is_empty() {
self.remember_label_kinds(LabelKinds::DATETIME64);
}
return answer;
}
if self.labels.has_datetime64_nat() {
return false;
}
if self.labels.len() <= 1 {
return true;
}
// Affine Int64 backings (RangeIndex / unit / affine) are monotonic by
// construction: ascending iff the step is non-negative. O(1), no
// IndexLabel materialization (br-frankenpandas-k9tlb vein).
if let Some(affine) = self.labels.int64_affine_range() {
return affine.step >= 0;
}
// Datetime64 affine backings carry the same validated `(start, step,
// len)` witness. IndexLabel::Datetime64 ordering compares the raw
// nanoseconds, so the step sign is exactly the former label-window
// result without materializing any labels. Keep NaT-bearing ranges on
// the existing fallback because i64::MIN is the reserved NaT sentinel.
if let Some(affine) = self.labels.datetime64_affine_range()
&& affine.position(i64::MIN).is_none()
{
return affine.step >= 0;
}
// Typed non-affine Int64: scan the i64 view instead of the wider
// IndexLabel window, so we never materialize the label vector. All-Int64
// backings carry no missing labels and IndexLabel::Int64 Ord matches i64
// Ord, so this is bit-identical to the fallback.
if let Some(values) = self.labels.int64_view() {
return values.windows(2).all(|pair| pair[0] <= pair[1]);
}
for pair in self.labels.windows(2) {
if pair[0] > pair[1] {
return false;
}
}
true
}
/// Alias for is_monotonic_increasing.
#[must_use]
pub fn is_monotonic(&self) -> bool {
self.is_monotonic_increasing()
}
#[must_use]
pub fn is_monotonic_decreasing(&self) -> bool {
*self.monotonic_cache[1].get_or_init(|| self.labels_descend())
}
fn labels_descend(&self) -> bool {
if let Some(answer) = self
.labels
.held()
.and_then(held_datetimes_monotonic::<false>)
{
return answer;
}
if self.labels.has_datetime64_nat() {
return false;
}
if self.labels.len() <= 1 {
return true;
}
// Affine Int64 backings are monotonic by construction: descending iff the
// step is non-positive. O(1), no IndexLabel materialization
// (br-frankenpandas-k9tlb vein).
if let Some(affine) = self.labels.int64_affine_range() {
return affine.step <= 0;
}
if let Some(affine) = self.labels.datetime64_affine_range()
&& affine.position(i64::MIN).is_none()
{
return affine.step <= 0;
}
// Typed non-affine Int64: scan the i64 view (no label materialization),
// bit-identical to the IndexLabel fallback for all-Int64 backings.
if let Some(values) = self.labels.int64_view() {
return values.windows(2).all(|pair| pair[0] >= pair[1]);
}
for pair in self.labels.windows(2) {
if pair[0] < pair[1] {
return false;
}
}
true
}
#[must_use]
pub fn unique(&self) -> Self {
// A strictly-ascending index (every recognized SortOrder) is already
// all-unique in first-seen order, so unique() is an identity — return an
// O(1) Arc-sharing clone instead of hashing every label and rebuilding
// the vector (br-frankenpandas-idxdup dedup family).
if !matches!(self.sort_order(), SortOrder::Unsorted) {
return self.clone();
}
// Typed all-Int64 fast path: inline `i64` first-occurrence dedup instead
// of the pointer-keyed `FxHashMap<&IndexLabel>`. Bit-identical order.
if let Some(vals) = self.labels.int64_view() {
return self.propagate_name(Self::from_i64_values(Self::unique_i64(&vals)));
}
// Datetime64 / Timedelta64 (no NaT): inline-i64 first-occurrence dedup via
// unique_i64, rebuilt with the temporal dtype (unique over a DatetimeIndex
// was 0.49x pandas). NaT bails to the pointer-key path (which keeps the
// one NaT). Bit-identical: same first-occurrence ns order and dtype.
if let Some(ns) = self.temporal_ns_present(true) {
return self.propagate_name(Self::from_datetime64(Self::unique_i64(&ns)));
}
if let Some(ns) = self.temporal_ns_present(false) {
return self.propagate_name(Self::from_timedelta64(Self::unique_i64(&ns)));
}
// Float64 labels: the first of each through the i64 mask over their
// keys ([`Self::float_label_keys`]).
if let Some(keys) = self.float_label_keys() {
let repeats = Self::duplicated_i64(&keys, DuplicateKeep::First);
let labels: Vec<IndexLabel> = self
.labels
.iter()
.zip(repeats)
.filter(|(_, repeat)| !repeat)
.map(|(label, _)| label.clone())
.collect();
return self.propagate_name(Self::new(labels));
}
let mut seen = FxHashMap::<&IndexLabel, ()>::default();
let labels: Vec<IndexLabel> = self
.labels
.iter()
.filter(|l| seen.insert(l, ()).is_none())
.cloned()
.collect();
self.propagate_name(Self::new(labels))
}
#[must_use]
pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
let mut result = vec![false; self.labels.len()];
// Strictly-ascending => no duplicates under any keep mode; skip hashing.
if !matches!(self.sort_order(), SortOrder::Unsorted) {
return result;
}
// Typed all-Int64 fast path: inline `i64` keys (dense bitsets when the
// value span is bounded) instead of the pointer-keyed
// `FxHashMap<&IndexLabel>`. Bit-identical mask per keep mode.
if let Some(vals) = self.labels.int64_view() {
return Self::duplicated_i64(&vals, keep);
}
// Datetime64 / Timedelta64 (no NaT): inline-i64 duplicate mask via
// duplicated_i64 instead of the pointer-key FxHashMap (duplicated over a
// DatetimeIndex was 0.66x pandas). NaT bails to the per-keep fallback.
// Bit-identical: present timestamps mask exactly like any i64.
if let Some(ns) = self
.temporal_ns_present(true)
.or_else(|| self.temporal_ns_present(false))
{
return Self::duplicated_i64(&ns, keep);
}
// Float64 labels through the i64 mask over their keys
// ([`Self::float_label_keys`]): the label map was 0.54x pandas.
if let Some(keys) = self.float_label_keys() {
return Self::duplicated_i64(&keys, keep);
}
match keep {
DuplicateKeep::First => {
let mut seen = FxHashMap::<&IndexLabel, ()>::default();
for (i, label) in self.labels.iter().enumerate() {
if seen.insert(label, ()).is_some() {
result[i] = true;
}
}
}
DuplicateKeep::Last => {
let mut seen = FxHashMap::<&IndexLabel, ()>::default();
for (i, label) in self.labels.iter().enumerate().rev() {
if seen.insert(label, ()).is_some() {
result[i] = true;
}
}
}
DuplicateKeep::None => {
let mut counts = FxHashMap::<&IndexLabel, usize>::default();
for label in &self.labels {
*counts.entry(label).or_insert(0) += 1;
}
for (i, label) in self.labels.iter().enumerate() {
if counts[label] > 1 {
result[i] = true;
}
}
}
}
result
}
#[must_use]
pub fn drop_duplicates(&self) -> Self {
self.drop_duplicates_keep(DuplicateKeep::First)
}
/// Drop duplicated labels with explicit keep behavior.
///
/// Matches `pd.Index.drop_duplicates(keep=...)`.
#[must_use]
pub fn drop_duplicates_keep(&self, keep: DuplicateKeep) -> Self {
// Strictly-ascending => nothing is dropped; O(1) Arc-sharing clone.
if !matches!(self.sort_order(), SortOrder::Unsorted) {
return self.clone();
}
if let Some(values) = self.labels.int64_view() {
let duplicated = Self::duplicated_i64(&values, keep);
let labels = values
.iter()
.copied()
.zip(duplicated)
.filter_map(|(value, is_duplicated)| (!is_duplicated).then_some(value))
.collect();
return self.propagate_name(Self::from_i64_values(labels));
}
// Datetime64 / Timedelta64 (no NaT): inline-i64 keep-mask filter, rebuilt
// with the temporal dtype (drop_duplicates over a DatetimeIndex was 0.69x
// pandas). NaT bails to the generic path. Bit-identical: same kept
// first/last occurrences in self order.
for datetime in [true, false] {
if let Some(values) = self.temporal_ns_present(datetime) {
let duplicated = Self::duplicated_i64(&values, keep);
let labels: Vec<i64> = values
.iter()
.copied()
.zip(duplicated)
.filter_map(|(value, is_duplicated)| (!is_duplicated).then_some(value))
.collect();
let result = if datetime {
Self::from_datetime64(labels)
} else {
Self::from_timedelta64(labels)
};
return self.propagate_name(result);
}
}
let duplicated = self.duplicated(keep);
let labels = self
.labels
.iter()
.zip(duplicated)
.filter(|(_, is_duplicated)| !is_duplicated)
.map(|(label, _)| label.clone())
.collect();
self.propagate_name(Self::new(labels))
}
// ── Pandas Index Model: set operations ─────────────────────────────
#[must_use]
pub fn intersection(&self, other: &Self) -> Self {
// Both strictly ascending (every SortOrder::Ascending* is globally
// IndexLabel::Ord-sorted and unique) => a two-pointer merge yields the
// same self-ordered, deduplicated intersection without building either
// FxHashMap (br-frankenpandas-idxdup set ops).
if let Some(labels) = self.sorted_merge_set_op_i64(other, SetMergeKind::Intersection) {
let mut result = Self::from_i64_values(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
if let Some(labels) = self.sorted_merge_set_op(other, SetMergeKind::Intersection) {
let mut result = Self::new(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
// Typed all-Int64 fast path: inline `i64` membership + dedup instead of
// the pointer-keyed `FxHashMap<&IndexLabel>` (whose probes chase into
// the enum vector — ~9× slower than pandas at 1M). Bit-identical:
// self-order, first-occurrence dedup, same matched labels.
if let (Some(a_i64), Some(b_i64)) = (self.labels.int64_view(), other.labels.int64_view()) {
let mut result =
Self::from_i64_values(Self::membership_filter_i64(&a_i64, &b_i64, true));
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
// Datetime64 / Timedelta64 i64-keyed intersection (unsorted temporal
// indexes miss the sorted-merge path and int64_view's Int64-only gate, so
// they fell to the pointer-key FxHashMap — intersection over an UNSORTED
// DatetimeIndex was 0.37x pandas). Reuse membership_filter_i64 over the ns
// and rebuild the temporal dtype. Bit-identical: same self-order
// first-occurrence kept-present labels, inline i64 keys.
if let (Some(a_ns), Some(b_ns)) = (
Self::all_temporal_ns(self.labels(), true),
Self::all_temporal_ns(other.labels(), true),
) {
let mut result = Self::from_datetime64(Self::membership_filter_i64(&a_ns, &b_ns, true));
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
if let (Some(a_ns), Some(b_ns)) = (
Self::all_temporal_ns(self.labels(), false),
Self::all_temporal_ns(other.labels(), false),
) {
let mut result =
Self::from_timedelta64(Self::membership_filter_i64(&a_ns, &b_ns, true));
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
// Typed all-Utf8 fast path (Utf8 sibling of membership_filter_i64): both
// sides are pure `IndexLabel::Utf8` (no Null), so hash `&str` directly
// (skipping the FxHashMap<&IndexLabel> enum load) AND dedup via a "matched"
// flag stored IN the other-map, eliminating the separate `seen` set — one
// hash map instead of two (~40% fewer string-hash probes). Bit-identical to
// the generic path: same self-order, first-occurrence dedup (a self label
// present in other emits once, then its map flag suppresses repeats), same
// matched labels. The all-Utf8 gate (no Null) is what makes skipping the
// `&IndexLabel` keys safe — the generic path would otherwise also match a
// Null self label against a Null in other.
let self_labels = self.labels();
let other_labels = other.labels();
if self_labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)))
&& other_labels
.iter()
.all(|l| matches!(l, IndexLabel::Utf8(_)))
{
let mut b_matched: FxHashMap<&str, bool> = FxHashMap::default();
b_matched.reserve(other_labels.len());
for label in other_labels {
if let IndexLabel::Utf8(s) = label {
b_matched.entry(s.as_str()).or_insert(false);
}
}
let mut labels: Vec<IndexLabel> = Vec::new();
for label in self_labels {
if let IndexLabel::Utf8(s) = label
&& let Some(matched) = b_matched.get_mut(s.as_str())
&& !*matched
{
*matched = true;
labels.push(label.clone());
}
}
let mut result = Self::new(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
let other_set = other.position_map_first_ref();
let mut seen = FxHashMap::<&IndexLabel, ()>::default();
let labels: Vec<IndexLabel> = self
.labels
.iter()
.filter(|l| other_set.contains_key(l) && seen.insert(l, ()).is_none())
.cloned()
.collect();
let mut result = Self::new(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
result
}
/// Hash-free two-pointer set merge for two strictly-ascending (hence
/// `IndexLabel::Ord`-sorted and unique) indexes; returns `None` when either
/// side is unsorted so the caller keeps its FxHashMap path. Emits labels in
/// `self`'s order, which equals the sorted order on the fast path — exactly
/// what the hash path's `self`-iteration-order filter produces.
fn sorted_merge_set_op_i64(&self, other: &Self, kind: SetMergeKind) -> Option<Vec<i64>> {
if !matches!(self.sort_order(), SortOrder::AscendingInt64)
|| !matches!(other.sort_order(), SortOrder::AscendingInt64)
{
return None;
}
let a = self.labels.int64_view()?;
let b = other.labels.int64_view()?;
let mut labels = Vec::with_capacity(a.len().min(b.len()));
let (mut i, mut j) = (0usize, 0usize);
while i < a.len() {
if j >= b.len() {
if kind == SetMergeKind::Difference {
labels.extend_from_slice(&a[i..]);
}
break;
}
match a[i].cmp(&b[j]) {
std::cmp::Ordering::Less => {
if kind == SetMergeKind::Difference {
labels.push(a[i]);
}
i += 1;
}
std::cmp::Ordering::Greater => j += 1,
std::cmp::Ordering::Equal => {
if kind == SetMergeKind::Intersection {
labels.push(a[i]);
}
i += 1;
j += 1;
}
}
}
Some(labels)
}
fn sorted_merge_set_op(&self, other: &Self, kind: SetMergeKind) -> Option<Vec<IndexLabel>> {
if matches!(self.sort_order(), SortOrder::Unsorted)
|| matches!(other.sort_order(), SortOrder::Unsorted)
{
return None;
}
let a = self.labels();
let b = other.labels();
let mut labels = Vec::with_capacity(a.len().min(b.len()));
let (mut i, mut j) = (0usize, 0usize);
while i < a.len() {
if j >= b.len() {
if kind == SetMergeKind::Difference {
labels.extend_from_slice(&a[i..]);
}
break;
}
match a[i].cmp(&b[j]) {
std::cmp::Ordering::Less => {
if kind == SetMergeKind::Difference {
labels.push(a[i].clone());
}
i += 1;
}
std::cmp::Ordering::Greater => j += 1,
std::cmp::Ordering::Equal => {
if kind == SetMergeKind::Intersection {
labels.push(a[i].clone());
}
i += 1;
j += 1;
}
}
}
Some(labels)
}
#[must_use]
pub fn union_with(&self, other: &Self) -> Self {
// Typed all-Int64 fast path: inline `i64` multiplicity accounting instead
// of enum-keyed maps. It retains pandas' first-seen label ordering while
// preserving each label's maximum count across the two inputs.
if let (Some(a_i64), Some(b_i64)) = (self.labels.int64_view(), other.labels.int64_view()) {
let mut result = Self::from_i64_values(Self::union_i64(&a_i64, &b_i64));
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
let self_labels = self.labels();
let other_labels = other.labels();
// Datetime64 / Timedelta64 are ns-backed, so reuse the typed i64 multiset
// union and rebuild the matching temporal dtype. Empty inputs return None
// so the degenerate empty-union dtype stays the generic fallback's.
let temporal_ns = |labels: &[IndexLabel], datetime: bool| -> Option<Vec<i64>> {
if labels.is_empty() {
return None;
}
let mut out = Vec::with_capacity(labels.len());
for label in labels {
match (datetime, label) {
(true, IndexLabel::Datetime64(ns)) | (false, IndexLabel::Timedelta64(ns)) => {
out.push(*ns);
}
_ => return None,
}
}
Some(out)
};
if let (Some(a_ns), Some(b_ns)) = (
temporal_ns(self_labels, true),
temporal_ns(other_labels, true),
) {
let mut result = Self::from_datetime64(Self::union_i64(&a_ns, &b_ns));
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
if let (Some(a_ns), Some(b_ns)) = (
temporal_ns(self_labels, false),
temporal_ns(other_labels, false),
) {
let mut result = Self::from_timedelta64(Self::union_i64(&a_ns, &b_ns));
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
if other.is_unique() {
let mut labels = self_labels.to_vec();
let mut seen = FxHashSet::<&IndexLabel>::default();
seen.reserve(combined_output_capacity(
self_labels.len(),
other_labels.len(),
));
seen.extend(self_labels.iter());
for label in other_labels {
if seen.insert(label) {
labels.push(label.clone());
}
}
let mut result = Self::new(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
let mut counts = FxHashMap::<&IndexLabel, (usize, usize)>::default();
counts.reserve(combined_output_capacity(
self.labels.len(),
other.labels.len(),
));
let mut order = Vec::with_capacity(combined_output_capacity(
self.labels.len(),
other.labels.len(),
));
for label in &self.labels {
let entry = counts.entry(label).or_insert((0, 0));
if entry.0 == 0 && entry.1 == 0 {
order.push(label);
}
entry.0 += 1;
}
for label in &other.labels {
let entry = counts.entry(label).or_insert((0, 0));
if entry.0 == 0 && entry.1 == 0 {
order.push(label);
}
entry.1 += 1;
}
let mut labels = Vec::with_capacity(combined_output_capacity(
self.labels.len(),
other.labels.len(),
));
for label in order {
let (left_count, right_count) = counts[label];
labels.extend(std::iter::repeat_n(
label.clone(),
left_count.max(right_count),
));
}
let mut result = Self::new(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
result
}
#[must_use]
pub fn difference(&self, other: &Self) -> Self {
// Two-pointer merge when both sides are strictly ascending (see
// intersection / sorted_merge_set_op).
if let Some(labels) = self.sorted_merge_set_op_i64(other, SetMergeKind::Difference) {
return self.propagate_name(Self::from_i64_values(labels));
}
if let Some(labels) = self.sorted_merge_set_op(other, SetMergeKind::Difference) {
return self.propagate_name(Self::new(labels));
}
// Typed all-Int64 fast path: inline `i64` membership (keep absent) +
// dedup instead of the pointer-keyed `FxHashMap<&IndexLabel>`.
// Bit-identical: self-order, first-occurrence dedup, labels not in other.
if let (Some(a_i64), Some(b_i64)) = (self.labels.int64_view(), other.labels.int64_view()) {
return self.propagate_name(Self::from_i64_values(Self::membership_filter_i64(
&a_i64, &b_i64, false,
)));
}
// Datetime64 / Timedelta64 i64-keyed difference (unsorted temporal indexes
// miss sorted-merge + the Int64-only int64_view, so they hit the
// pointer-key map — difference over an UNSORTED DatetimeIndex was 0.57x
// pandas). Reuse membership_filter_i64(keep_present=false). Bit-identical:
// self-order, labels not in other, first-occurrence dedup, inline i64 keys.
if let (Some(a_ns), Some(b_ns)) = (
Self::all_temporal_ns(self.labels(), true),
Self::all_temporal_ns(other.labels(), true),
) {
return self.propagate_name(Self::from_datetime64(Self::membership_filter_i64(
&a_ns, &b_ns, false,
)));
}
if let (Some(a_ns), Some(b_ns)) = (
Self::all_temporal_ns(self.labels(), false),
Self::all_temporal_ns(other.labels(), false),
) {
return self.propagate_name(Self::from_timedelta64(Self::membership_filter_i64(
&a_ns, &b_ns, false,
)));
}
// Typed all-Utf8 fast path: ONE FxHashMap<&str,()> seeded with other's
// labels doubles as membership AND self-dedup — `insert(s).is_none()` is
// true only when s is neither in other nor already emitted, so there is no
// separate `seen` set (one map instead of two). Bit-identical: self-order,
// labels not in other, first-occurrence dedup. The all-Utf8 gate (no Null)
// makes &str keys safe.
let self_labels = self.labels();
let other_labels = other.labels();
if self_labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)))
&& other_labels
.iter()
.all(|l| matches!(l, IndexLabel::Utf8(_)))
{
let mut set: FxHashMap<&str, ()> = FxHashMap::default();
set.reserve(other_labels.len());
for label in other_labels {
if let IndexLabel::Utf8(s) = label {
set.insert(s.as_str(), ());
}
}
let mut labels: Vec<IndexLabel> = Vec::new();
for label in self_labels {
if let IndexLabel::Utf8(s) = label
&& set.insert(s.as_str(), ()).is_none()
{
labels.push(label.clone());
}
}
return self.propagate_name(Self::new(labels));
}
let other_set = other.position_map_first_ref();
let mut seen = FxHashMap::<&IndexLabel, ()>::default();
let labels: Vec<IndexLabel> = self
.labels
.iter()
.filter(|l| !other_set.contains_key(l) && seen.insert(l, ()).is_none())
.cloned()
.collect();
self.propagate_name(Self::new(labels))
}
#[must_use]
pub fn symmetric_difference(&self, other: &Self) -> Self {
// Typed all-Int64 fast path: the two halves (self-not-in-other,
// other-not-in-self) are disjoint by construction, so the original
// shared `seen` only ever dedups WITHIN a half — exactly what two
// independent `membership_filter_i64(.., keep_present=false)` calls do,
// with inline `i64` keys instead of the pointer-keyed `FxHashMap`.
if let (Some(a_i64), Some(b_i64)) = (self.labels.int64_view(), other.labels.int64_view()) {
let mut labels = Self::membership_filter_i64(&a_i64, &b_i64, false);
labels.extend(Self::membership_filter_i64(&b_i64, &a_i64, false));
let mut result = Self::from_i64_values(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
// Datetime64 / Timedelta64 i64-keyed symmetric_difference (unsorted
// temporal indexes hit the pointer-key map — symdiff over an UNSORTED
// DatetimeIndex was 0.48x pandas). The two halves are disjoint, so two
// independent membership_filter_i64(keep_present=false) calls reproduce
// the shared-`seen` within-half dedup. Bit-identical: self-not-in-other
// then other-not-in-self, inline i64 keys.
if let (Some(a_ns), Some(b_ns)) = (
Self::all_temporal_ns(self.labels(), true),
Self::all_temporal_ns(other.labels(), true),
) {
let mut labels = Self::membership_filter_i64(&a_ns, &b_ns, false);
labels.extend(Self::membership_filter_i64(&b_ns, &a_ns, false));
let mut result = Self::from_datetime64(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
if let (Some(a_ns), Some(b_ns)) = (
Self::all_temporal_ns(self.labels(), false),
Self::all_temporal_ns(other.labels(), false),
) {
let mut labels = Self::membership_filter_i64(&a_ns, &b_ns, false);
labels.extend(Self::membership_filter_i64(&b_ns, &a_ns, false));
let mut result = Self::from_timedelta64(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
// Typed all-Utf8 fast path: the two halves are disjoint, so the shared
// `seen` only ever dedups WITHIN a half. Build self_set/other_set as
// FxHashMap<&str,()> and let each membership map ALSO carry its half's
// dedup: for the self-half, `other_set.insert(s).is_none()` is true only
// when s is not in other and not yet emitted; symmetrically for the
// other-half via self_set. Drops the separate `seen` map (3 maps -> 2) and
// hashes &str. Bit-identical: self-then-other order, label not in the
// opposite side, first-occurrence dedup within each half.
let self_labels = self.labels();
let other_labels = other.labels();
if self_labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)))
&& other_labels
.iter()
.all(|l| matches!(l, IndexLabel::Utf8(_)))
{
let mut self_set: FxHashMap<&str, ()> = FxHashMap::default();
self_set.reserve(self_labels.len());
for label in self_labels {
if let IndexLabel::Utf8(s) = label {
self_set.insert(s.as_str(), ());
}
}
let mut other_set: FxHashMap<&str, ()> = FxHashMap::default();
other_set.reserve(other_labels.len());
for label in other_labels {
if let IndexLabel::Utf8(s) = label {
other_set.insert(s.as_str(), ());
}
}
let mut labels: Vec<IndexLabel> = Vec::new();
for label in self_labels {
if let IndexLabel::Utf8(s) = label
&& other_set.insert(s.as_str(), ()).is_none()
{
labels.push(label.clone());
}
}
for label in other_labels {
if let IndexLabel::Utf8(s) = label
&& self_set.insert(s.as_str(), ()).is_none()
{
labels.push(label.clone());
}
}
let mut result = Self::new(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
return result;
}
let self_set = self.position_map_first_ref();
let other_set = other.position_map_first_ref();
let mut seen = FxHashMap::<&IndexLabel, ()>::default();
let mut labels = Vec::new();
for label in &self.labels {
if !other_set.contains_key(label) && seen.insert(label, ()).is_none() {
labels.push(label.clone());
}
}
for label in &other.labels {
if !self_set.contains_key(label) && seen.insert(label, ()).is_none() {
labels.push(label.clone());
}
}
let mut result = Self::new(labels);
result.name = self.shared_name(other);
result.tz = joined_tz(self, other);
result
}
// ── Pandas Index Model: ordering and slicing ───────────────────────
#[must_use]
pub fn argsort(&self) -> Vec<usize> {
if let Some(range) = self.labels.int64_affine_range() {
return Self::argsort_int64_affine(range);
}
if let Some(vals) = self.labels.int64_view() {
return Self::argsort_i64(&vals);
}
// Datetime64 / Timedelta64: radix/stable-key argsort over the raw ns
// instead of the comparison sort that derefs into the IndexLabel vector
// per compare (argsort over a DatetimeIndex was 0.57x pandas). Bit-
// identical: IndexLabel derives Ord so Datetime64/Timedelta64 order by
// their inner i64 (NaT == i64::MIN sorts first in BOTH paths), and both
// argsort_i64 (sort_by_key) and the fallback (sort_by) are STABLE, so
// duplicate-timestamp ties keep input order identically.
if let Some(ns) = Self::all_temporal_ns(self.labels(), true)
.or_else(|| Self::all_temporal_ns(self.labels(), false))
{
return Self::argsort_i64(&ns);
}
let mut indices: Vec<usize> = (0..self.labels.len()).collect();
indices.sort_by(|&a, &b| self.labels[a].cmp(&self.labels[b]));
indices
}
#[must_use]
pub fn sort_values(&self) -> Self {
if let Some(range) = self.labels.int64_affine_range() {
if range.len <= 1 || range.step > 0 {
return self.clone();
}
if let Ok(last_offset) = i64::try_from(range.len - 1)
&& let Some(delta) = range.step.checked_mul(last_offset)
&& let Some(start) = range.start.checked_add(delta)
&& let Some(step) = range.step.checked_neg()
&& let Some(sorted) =
Self::new_known_unique_int64_affine_range(start, step, range.len)
{
return self.propagate_name(sorted);
}
}
if let Some(vals) = self.labels.int64_view() {
let order = Self::argsort_i64(&vals);
let sorted = order.iter().map(|&idx| vals[idx]).collect();
return self.propagate_name(Self::from_i64_values(sorted));
}
// Datetime64 / Timedelta64: stable i64 argsort + gather, rebuilt with the
// temporal dtype (sort_values over a DatetimeIndex was 0.58x pandas).
// Bit-identical to the comparison-sort fallback (see argsort).
if let Some(ns) = Self::all_temporal_ns(self.labels(), true) {
let order = Self::argsort_i64(&ns);
let sorted = order.iter().map(|&idx| ns[idx]).collect();
return self.propagate_name(Self::from_datetime64(sorted));
}
if let Some(ns) = Self::all_temporal_ns(self.labels(), false) {
let order = Self::argsort_i64(&ns);
let sorted = order.iter().map(|&idx| ns[idx]).collect();
return self.propagate_name(Self::from_timedelta64(sorted));
}
let order = self.argsort();
self.propagate_name(Self::new(
order.iter().map(|&i| self.labels[i].clone()).collect(),
))
}
/// Select labels by position, carrying the row `MultiIndex` levels (taken at
/// the same positions) when the index has them.
#[must_use]
pub fn take(&self, indices: &[usize]) -> Self {
let mut taken = self.take_labels(indices);
// A run of consecutive positions is a slice: it keeps the freq, as
// pandas' getitem keeps it for a slice or a mask selecting a run
// (pandas' take keeps a steady step too: see `take_freq`).
if !indices.is_empty() && indices.windows(2).all(|pair| pair[1] == pair[0] + 1) {
taken.freq.clone_from(&self.freq);
}
match self
.row_multiindex
.as_deref()
.map(|levels| levels.take(indices))
{
Some(Ok(levels)) => taken.attach_row_multiindex(levels),
_ => taken,
}
}
fn take_labels(&self, indices: &[usize]) -> Self {
// Affine-in, affine-out fast path (br-frankenpandas, BlackThrush): when the
// backing is an Int64 affine range AND the requested positions are
// themselves arithmetic (constant stride), the gathered labels are
// `start + step*pos` evaluated at an arithmetic position sequence — which
// is again an affine range with `label_step = step * position_step`. A
// single O(len) stride-verification pass (no `Vec<i64>` materialization,
// no per-element gather + index rebuild — the dominant cost in the
// `affine_index_take` hot loop, ~1.5x slower than pandas' numpy gather)
// yields a lazy affine index in O(1). Mirrors `RangeIndex::take_
// arithmetic_positions`. Bit-transparent: produces the identical labels in
// the identical order as the materialize-then-rebuild path below; out-of-
// bounds or non-arithmetic positions return `None` and fall through to it.
if let Some(idx) = self.take_affine_positions(indices) {
return idx;
}
if let Some(values) = self.labels.take_i64_values(indices) {
return self.propagate_name(Self::from_i64_values(values));
}
self.propagate_name(Self::new(
indices.iter().map(|&i| self.labels[i].clone()).collect(),
))
}
/// Lazy affine result for an affine-backed index taken at arithmetic
/// positions. Returns `None` (caller falls back to the materializing path)
/// when the backing is not an Int64 affine range, the positions are not a
/// constant-stride sequence, any position is out of bounds, or the resulting
/// affine parameters overflow `i64`.
fn take_affine_positions(&self, positions: &[usize]) -> Option<Self> {
let affine = self.labels.int64_affine_range()?;
let len = affine.len;
let value_at = |p: usize| -> Option<i64> {
let offset = i64::try_from(p).ok()?;
affine
.step
.checked_mul(offset)
.and_then(|delta| affine.start.checked_add(delta))
};
let result = match positions {
[] => Index::new_known_unique_int64_affine_range(affine.start, affine.step, 0)?,
&[p] => {
if p >= len {
return None;
}
Index::new_known_unique_int64_affine_range(value_at(p)?, affine.step, 1)?
}
&[first, second, ..] => {
if first >= len {
return None;
}
// `i64` (not `i128`) stride arithmetic: every position is a valid
// index `< len <= isize::MAX`, so the difference of any two fits
// `i64` without overflow — and the `i64` windows scan autovectorizes
// where the `i128` form could not (the hot loop of this fast path).
let position_step = second as i64 - first as i64;
if position_step == 0 {
return None;
}
// Single pass: verify the constant position stride. Because the
// sequence is monotone with that stride, all positions lie in
// `[min(first,last), max(first,last)]`, so a single endpoint
// bounds check below suffices.
if !positions
.windows(2)
.all(|w| w[1] as i64 - w[0] as i64 == position_step)
{
return None;
}
let last = *positions.last().expect("non-empty by match arm");
if first.max(last) >= len {
return None;
}
let label_step = affine.step.checked_mul(position_step)?;
let first_label = value_at(first)?;
Index::new_known_unique_int64_affine_range(
first_label,
label_step,
positions.len(),
)?
}
};
Some(self.propagate_name(result))
}
#[must_use]
pub fn slice(&self, start: usize, len: usize) -> Self {
let mut sliced = self.propagate_name(Self {
labels: self.labels.slice(start, len),
name: None,
label_identity: next_index_label_identity(),
duplicate_cache: OnceLock::new(),
sort_order_cache: OnceLock::new(),
monotonic_cache: Default::default(),
semantic_fingerprint_cache: OnceLock::new(),
row_multiindex: None,
tz: None,
freq: None,
range: None,
declared: None,
categories: None,
});
sliced.freq.clone_from(&self.freq);
// A slice of a RangeIndex is one (pandas).
if self.range.is_some() {
let first = start.min(self.len());
sliced.range = i64::try_from(first).ok().and_then(|first| {
let stop = first.checked_add(i64::try_from(sliced.len()).ok()?)?;
self.sliced_range_span(first, stop, 1)
});
}
let Some(levels) = self.row_multiindex.as_deref() else {
return sliced;
};
let positions: Vec<usize> = (start..start.saturating_add(sliced.len())).collect();
match levels.take(&positions) {
Ok(levels) => sliced.attach_row_multiindex(levels),
Err(_) => sliced,
}
}
/// Attach the levels of the row `MultiIndex` whose flattened labels this
/// index holds, one level tuple per label, in label order. The caller
/// vouches that label `i` is the flat form of tuple `i`; the heights must
/// match.
pub fn with_row_multiindex(self, levels: MultiIndex) -> Result<Self, IndexError> {
if levels.len() != self.len() {
return Err(IndexError::LengthMismatch {
expected: self.len(),
actual: levels.len(),
context: "row MultiIndex height vs index length".to_owned(),
});
}
Ok(self.attach_row_multiindex(levels))
}
fn attach_row_multiindex(mut self, levels: MultiIndex) -> Self {
self.row_multiindex = Some(Arc::new(levels));
self
}
/// The row `MultiIndex` levels these flat labels stand for, when attached
/// (see [`Self::with_row_multiindex`]).
#[must_use]
pub fn row_multiindex(&self) -> Option<&MultiIndex> {
self.row_multiindex.as_deref()
}
#[must_use]
pub fn from_range(start: i64, stop: i64, step: i64) -> Self {
let len = if step > 0 {
if start >= stop {
Some(0_i128)
} else {
let distance = stop as i128 - start as i128;
let step = step as i128;
Some((distance + step - 1) / step)
}
} else if step < 0 {
if start <= stop {
Some(0_i128)
} else {
let distance = start as i128 - stop as i128;
let step = -(step as i128);
Some((distance + step - 1) / step)
}
} else {
Some(0_i128)
};
if let Some(len) = len.and_then(|value| usize::try_from(value).ok())
&& let Some(mut index) = Self::new_known_unique_int64_affine_range(start, step, len)
{
// Known to be a range: marked without reading the lazy labels.
index.range = (step != 0).then_some((start, stop, step));
return index;
}
let mut labels = Vec::new();
let mut val = start;
if step > 0 {
while val < stop {
labels.push(IndexLabel::Int64(val));
val += step;
}
} else if step < 0 {
while val > stop {
labels.push(IndexLabel::Int64(val));
val += step;
}
}
Self::new(labels).with_range_span((step != 0).then_some((start, stop, step)))
}
// ── Pandas Index Model: aggregation ──────────────────────────────
/// Minimum label.
///
/// Matches `pd.Index.min()`.
#[must_use]
pub fn min(&self) -> Option<IndexLabel> {
// Affine Int64 ranges have their minimum at a known endpoint; return an
// owned scalar without forcing the lazy label vector.
if let Some(affine) = self.labels.int64_affine_range() {
if affine.len == 0 {
return None;
}
let position = if affine.step >= 0 { 0 } else { affine.len - 1 };
return Some(IndexLabel::Int64(affine.value_at(position)));
}
// Datetime64 affine ranges have the same validated endpoint witness.
// Derived IndexLabel ordering compares their raw nanoseconds, including
// the reserved i64::MIN NaT sentinel, so the minimum is exactly the
// first endpoint when ascending and the last when descending.
if let Some(affine) = self.labels.datetime64_affine_range() {
if affine.len == 0 {
return None;
}
let position = if affine.step >= 0 { 0 } else { affine.len - 1 };
return Some(IndexLabel::Datetime64(affine.value_at(position)));
}
// Lazy typed/strided Int64: scan raw i64 values and return the same
// scalar the IndexLabel fallback would have yielded, without materializing.
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
return values.iter().copied().min().map(IndexLabel::Int64);
}
self.labels.iter().min().cloned()
}
/// Maximum label.
///
/// Matches `pd.Index.max()`.
#[must_use]
pub fn max(&self) -> Option<IndexLabel> {
// Affine Int64 ranges have their maximum at the opposite endpoint from
// min(); no IndexLabel materialization needed.
if let Some(affine) = self.labels.int64_affine_range() {
if affine.len == 0 {
return None;
}
let position = if affine.step >= 0 { affine.len - 1 } else { 0 };
return Some(IndexLabel::Int64(affine.value_at(position)));
}
// Datetime64 affine ranges carry the same validated endpoint witness.
// IndexLabel ordering compares raw nanoseconds, including the reserved
// i64::MIN NaT sentinel, so the opposite endpoint from min() is exact.
if let Some(affine) = self.labels.datetime64_affine_range() {
if affine.len == 0 {
return None;
}
let position = if affine.step >= 0 { affine.len - 1 } else { 0 };
return Some(IndexLabel::Datetime64(affine.value_at(position)));
}
// Lazy typed/strided Int64: scan raw i64 values and return an owned
// scalar, preserving fallback ordering semantics for all-Int64 labels.
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
return values.iter().copied().max().map(IndexLabel::Int64);
}
self.labels.iter().max().cloned()
}
/// Position of the minimum label.
///
/// Matches `pd.Index.argmin()`.
#[must_use]
pub fn argmin(&self) -> Option<usize> {
// Affine Int64 (RangeIndex / unit / affine): the minimum sits at a known
// end — index 0 when ascending (step >= 0), len-1 when descending. O(1),
// no IndexLabel materialization (br-frankenpandas-ikbh9 vein).
if let Some(affine) = self.labels.int64_affine_range() {
return (affine.len > 0).then(|| if affine.step >= 0 { 0 } else { affine.len - 1 });
}
// A validated Datetime64 affine range is unique for len > 1, and its
// raw-nanosecond ordering is the same ordering used by IndexLabel.
// Therefore the minimum position is the corresponding endpoint even
// when that endpoint is the reserved i64::MIN NaT sentinel.
if let Some(affine) = self.labels.datetime64_affine_range() {
return (affine.len > 0).then(|| if affine.step >= 0 { 0 } else { affine.len - 1 });
}
// Lazy typed/strided Int64: scan the i64 view with the identical min_by
// (last-of-equal) tie-break — bit-identical, no label vector. Guarded by
// has_lazy_int64_backing so already-materialized indexes keep the label
// iter and avoid an extra i64 allocation (matches any()/all()).
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
return values
.iter()
.enumerate()
.min_by(|(_, a), (_, b)| a.cmp(b))
.map(|(i, _)| i);
}
self.labels
.iter()
.enumerate()
.min_by(|(_, a), (_, b)| a.cmp(b))
.map(|(i, _)| i)
}
/// Position of the maximum label.
///
/// Matches `pd.Index.argmax()`.
#[must_use]
pub fn argmax(&self) -> Option<usize> {
// Affine Int64: the maximum sits at a known end — index len-1 when
// ascending (step >= 0), 0 when descending. O(1), no materialization
// (br-frankenpandas-ikbh9 vein).
if let Some(affine) = self.labels.int64_affine_range() {
return (affine.len > 0).then(|| if affine.step >= 0 { affine.len - 1 } else { 0 });
}
// A validated Datetime64 affine range is unique for len > 1 and uses
// raw nanosecond ordering, so its maximum is the same endpoint without
// materializing one IndexLabel per row. Singleton and empty ranges keep
// the former tie/empty behavior.
if let Some(affine) = self.labels.datetime64_affine_range() {
return (affine.len > 0).then(|| if affine.step >= 0 { affine.len - 1 } else { 0 });
}
// Lazy typed/strided Int64: scan the i64 view with the identical max_by
// (last-of-equal) tie-break — bit-identical, no label vector.
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
return values
.iter()
.enumerate()
.max_by(|(_, a), (_, b)| a.cmp(b))
.map(|(i, _)| i);
}
self.labels
.iter()
.enumerate()
.max_by(|(_, a), (_, b)| a.cmp(b))
.map(|(i, _)| i)
}
/// Number of unique labels.
///
/// Matches `pd.Index.nunique()`.
#[must_use]
pub fn nunique(&self) -> usize {
self.nunique_with_dropna(true)
}
/// Number of unique labels with explicit missing-value control.
///
/// Matches `pd.Index.nunique(dropna=...)`.
#[must_use]
pub fn nunique_with_dropna(&self, dropna: bool) -> usize {
// Affine Int64 (RangeIndex / unit / affine) is strictly monotonic, so all
// `len` labels are distinct, and an Int64 backing carries no missing
// labels — nunique == len for either dropna setting, with no IndexLabel
// materialization (br-frankenpandas-a55d8 vein).
if let Some(affine) = self.labels.int64_affine_range() {
return affine.len;
}
// A validated affine Datetime64 backing has no repeated raw nanosecond
// values. It can contain the reserved NaT sentinel at most once, so the
// witness gives the exact dropna-aware count without materializing the
// IndexLabel vector or allocating a temporary nanosecond buffer.
if let Some(affine) = self.labels.datetime64_affine_range() {
return affine.len - usize::from(dropna && affine.position(i64::MIN).is_some());
}
if let Some(values) = self.labels.int64_view() {
return Self::nunique_i64(&values);
}
// Datetime64 / Timedelta64 (no NaT): reuse nunique_i64 over the ns instead
// of the pointer-key FxHashMap (nunique over a DatetimeIndex was 0.52x
// pandas). NaT-bearing temporal indexes bail so the dropna fallback below
// keeps its missing semantics. Bit-identical: distinct present timestamps.
if let Some(ns) = self
.temporal_ns_present(true)
.or_else(|| self.temporal_ns_present(false))
{
return Self::nunique_i64(&ns);
}
self.unique()
.labels
.iter()
.filter(|label| !dropna || !label.is_missing())
.count()
}
// ── Pandas Index Model: transformation ───────────────────────────
/// Apply a function to each label, producing a new Index.
///
/// Matches `pd.Index.map(func)`.
#[must_use]
pub fn map<F>(&self, func: F) -> Self
where
F: Fn(&IndexLabel) -> IndexLabel,
{
self.propagate_name(Self::new(self.labels.iter().map(&func).collect()))
}
/// Rename the index (create a copy with transformed labels).
///
/// Matches `pd.Index.rename(name)` / `pd.Index.set_names(name)`.
/// Applies a function to each label.
#[must_use]
pub fn rename<F>(&self, func: F) -> Self
where
F: Fn(&IndexLabel) -> IndexLabel,
{
self.map(func)
}
/// Drop specific labels from the index.
///
/// Matches `pd.Index.drop(labels)`.
#[must_use]
pub fn drop_labels(&self, labels_to_drop: &[IndexLabel]) -> Self {
if let Some(values) = self.labels.int64_view() {
let drop_values = int64_drop_values(labels_to_drop);
let kept = if drop_values.is_empty() {
values.as_ref().clone()
} else if is_non_decreasing_i64(values.as_slice()) {
drop_sorted_i64_values(values.as_slice(), drop_values)
} else {
let drop_set: FxHashSet<i64> = drop_values.into_iter().collect();
values
.iter()
.copied()
.filter(|value| !drop_set.contains(value))
.collect()
};
return self.propagate_name(Self::from_i64_values(kept));
}
let kept = if labels_to_drop.len() < 8 {
self.labels
.iter()
.filter(|label| !labels_to_drop.contains(label))
.cloned()
.collect()
} else {
let drop_set: FxHashSet<&IndexLabel> = labels_to_drop.iter().collect();
self.labels
.iter()
.filter(|label| !drop_set.contains(label))
.cloned()
.collect()
};
self.propagate_name(Self::new(kept))
}
/// Convert all labels to Int64 (if possible) or Utf8.
///
/// Matches `pd.Index.astype(dtype)`. Returns a new Index with labels
/// converted to the target type representation.
#[must_use]
pub fn astype_int(&self) -> Self {
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
return self.propagate_name(Self::from_i64_values(values.as_ref().clone()));
}
self.propagate_name(Self::new(
self.labels
.iter()
.map(|l| match l {
IndexLabel::Int64(_) => l.clone(),
IndexLabel::Float64(v) => IndexLabel::Int64(v.0 as i64),
IndexLabel::Bool(b) => IndexLabel::Int64(i64::from(*b)),
IndexLabel::Utf8(s) => s
.parse::<i64>()
.map_or_else(|_| l.clone(), IndexLabel::Int64),
IndexLabel::Timedelta64(ns) => IndexLabel::Int64(*ns),
IndexLabel::Datetime64(ns) => IndexLabel::Int64(*ns),
// A period is its ordinal (NaT's too), as pandas'.
IndexLabel::Period(period) => IndexLabel::Int64(period.ordinal),
// Missing labels, objects and intervals have no integer
// form; preserved like unparseable strings (pandas
// astype(int) raises on them — callers reject before
// reaching here).
IndexLabel::Object(_) | IndexLabel::Interval(_) | IndexLabel::Null(_) => {
l.clone()
}
})
.collect(),
))
}
/// Convert labels to Float64 (`pd.Index.astype('float64')`): integers and
/// bools widen, numeric strings parse, a missing label becomes NaN;
/// datetimes, timedeltas and non-numeric strings are pandas' TypeError /
/// ValueError, reported as `InvalidArgument`. (fvsao.4)
pub fn astype_float(&self) -> Result<Self, IndexError> {
let labels = self
.labels
.iter()
.map(|label| {
let value = match label {
IndexLabel::Int64(v) => *v as f64,
IndexLabel::Float64(v) => v.0,
IndexLabel::Bool(b) => f64::from(u8::from(*b)),
IndexLabel::Utf8(s) => s.parse::<f64>().map_err(|_| {
IndexError::InvalidArgument(format!(
"could not convert string to float: '{s}'"
))
})?,
IndexLabel::Null(_) => f64::NAN,
IndexLabel::Timedelta64(_) | IndexLabel::Datetime64(_) => {
return Err(IndexError::InvalidArgument(
"Cannot cast a datetime-like Index to dtype float64".to_owned(),
));
}
IndexLabel::Period(_) => {
return Err(IndexError::InvalidArgument(
"Cannot cast PeriodIndex to dtype float64".to_owned(),
));
}
IndexLabel::Interval(_) => {
return Err(IndexError::InvalidArgument(
"Cannot cast IntervalIndex to dtype float64".to_owned(),
));
}
IndexLabel::Object(object) => {
return Err(IndexError::InvalidArgument(format!(
"float() argument must be a string or a real number, not {}",
object.repr()
)));
}
};
Ok(IndexLabel::Float64(OrderedF64(value)))
})
.collect::<Result<Vec<_>, IndexError>>()?;
Ok(self.propagate_name(Self::new(labels)))
}
/// Convert labels to bool (`pd.Index.astype(bool)`): nonzero numbers and
/// non-empty strings are true; missing and datetime-like labels are
/// refused. (fvsao.4)
pub fn astype_bool(&self) -> Result<Self, IndexError> {
let labels = self
.labels
.iter()
.map(|label| {
let flag = match label {
IndexLabel::Int64(v) => *v != 0,
IndexLabel::Float64(v) => v.0 != 0.0,
IndexLabel::Bool(b) => *b,
IndexLabel::Utf8(s) => !s.is_empty(),
IndexLabel::Object(_) => index_label_is_truthy(label),
// NaT is false, a period true (pandas').
IndexLabel::Period(period) => !period.is_nat(),
IndexLabel::Null(_)
| IndexLabel::Timedelta64(_)
| IndexLabel::Datetime64(_)
| IndexLabel::Interval(_) => {
return Err(IndexError::InvalidArgument(format!(
"cannot cast index label {label:?} to bool"
)));
}
};
Ok(IndexLabel::Bool(flag))
})
.collect::<Result<Vec<_>, IndexError>>()?;
Ok(self.propagate_name(Self::new(labels)))
}
/// Convert all labels to Utf8 strings.
///
/// Matches `pd.Index.astype(str)`.
#[must_use]
pub fn astype_str(&self) -> Self {
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
return self.propagate_name(Self::new(
values
.iter()
.map(|value| IndexLabel::Utf8(value.to_string()))
.collect(),
));
}
self.propagate_name(Self::new(
self.labels
.iter()
.map(|l| match l {
IndexLabel::Int64(v) => IndexLabel::Utf8(v.to_string()),
IndexLabel::Float64(v) => IndexLabel::Utf8(if v.0.is_nan() {
"nan".to_owned()
} else {
let t = format!("{}", v.0);
if t.contains('.') || t.contains('e') || t.contains("inf") {
t
} else {
format!("{t}.0")
}
}),
IndexLabel::Bool(b) => {
IndexLabel::Utf8(if *b { "True" } else { "False" }.to_owned())
}
IndexLabel::Utf8(_) => l.clone(),
IndexLabel::Timedelta64(ns) => IndexLabel::Utf8(Timedelta::format(*ns)),
IndexLabel::Datetime64(ns) => IndexLabel::Utf8(format_datetime_ns(*ns)),
IndexLabel::Object(object) => IndexLabel::Utf8(object.to_string()),
// A period's calendar text, NaT's 'NaT'.
IndexLabel::Period(period) => IndexLabel::Utf8(period.to_string()),
// An interval's str ('(0, 1]').
IndexLabel::Interval(interval) => IndexLabel::Utf8(interval.to_string()),
// astype(str) uses Python str() forms: str(None)=='None',
// str(nan)=='nan' (LOWERCASE, unlike the repr surface),
// str(NaT)=='NaT'. Verified pandas 2.2.3.
IndexLabel::Null(kind) => IndexLabel::Utf8(
match kind {
fp_types::NullKind::Null => "None",
fp_types::NullKind::NaN => "nan",
fp_types::NullKind::NaT => "NaT",
}
.to_owned(),
),
})
.collect(),
))
}
/// Convert labels to a pandas dtype string.
///
/// Matches `pd.Index.astype(dtype)` for the generic dtype names this crate
/// can represent directly.
pub fn astype(&self, dtype: &str) -> Result<Self, IndexError> {
let (out, declared) = match dtype {
"int" | "int64" => (self.astype_int(), DeclaredDtype::Int64),
"float" | "float64" => (self.astype_float()?, DeclaredDtype::Float64),
"bool" => (self.astype_bool()?, DeclaredDtype::Bool),
"str" | "string" | "object" => (self.astype_str(), DeclaredDtype::Object),
"datetime64[ns]" => {
ensure_index_kind(self, LabelKinds::DATETIME64, "DatetimeIndex")?;
(self.clone(), DeclaredDtype::Datetime64)
}
"timedelta64[ns]" => {
ensure_index_kind(self, LabelKinds::TIMEDELTA64, "TimedeltaIndex")?;
(self.clone(), DeclaredDtype::Timedelta64)
}
other => {
return Err(IndexError::InvalidArgument(format!(
"unsupported Index.astype dtype {other:?}"
)));
}
};
// No labels show a type: an empty index is the dtype asked for
// (Index([], dtype='int64') is int64, it was object;
// br-frankenpandas-ce86r).
Ok(if out.is_empty() {
out.with_declared_dtype(Some(declared))
} else {
out
})
}
/// Equality check against another Index.
///
/// Matches `pd.Index.equals(other)`. Returns true iff `other` has
/// the same labels in the same order, in the same time zone (pandas:
/// the same instants in two zones, or aware against naive, differ in
/// dtype and are not equal). Names are ignored (use `identical` for a
/// name-sensitive check).
#[must_use]
pub fn equals(&self, other: &Self) -> bool {
self == other
}
/// Strict equality including name.
///
/// Matches `pd.Index.identical(other)`. Requires the same labels in
/// the same order AND the same name (and zone).
#[must_use]
pub fn identical(&self, other: &Self) -> bool {
self == other && self.name == other.name
}
/// Typed `value_counts_raw` over raw `i64` keys: first-seen (value, count)
/// pairs, then the same stable count sort. Bit-identical to the
/// `FxHashMap<IndexLabel,usize>` path for all-Int64 indexes (which have no
/// missing labels, so `dropna` is a no-op): a dense direct-address histogram
/// when the value span is bounded, else an inline-key `FxHashMap<i64,usize>`.
fn value_counts_raw_i64(
vals: &[i64],
sort: bool,
ascending: bool,
) -> (Vec<(IndexLabel, usize)>, usize) {
let total = vals.len();
let mut seen: Vec<i64> = Vec::new();
let mut pairs: Vec<(IndexLabel, usize)> = match Self::i64_dense_span(vals) {
Some((min, span)) => {
let mut counts = vec![0usize; span];
for &v in vals {
let s = (v - min) as usize;
if counts[s] == 0 {
seen.push(v);
}
counts[s] += 1;
}
seen.iter()
.map(|&v| (IndexLabel::Int64(v), counts[(v - min) as usize]))
.collect()
}
None => {
let mut counts: FxHashMap<i64, usize> =
FxHashMap::with_capacity_and_hasher(vals.len(), Default::default());
for &v in vals {
let c = counts.entry(v).or_insert(0);
if *c == 0 {
seen.push(v);
}
*c += 1;
}
seen.iter()
.map(|&v| (IndexLabel::Int64(v), counts[&v]))
.collect()
}
};
if sort {
if ascending {
pairs.sort_by_key(|entry| entry.1);
} else {
pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
}
}
(pairs, total)
}
fn value_counts_raw(
&self,
sort: bool,
ascending: bool,
dropna: bool,
) -> (Vec<(IndexLabel, usize)>, usize) {
// Typed all-Int64 fast path: inline `i64` histogram instead of the
// cloned-key, double-hashed `FxHashMap<IndexLabel,usize>`. Int64 labels
// are never missing, so `dropna` changes nothing — bit-identical pairs.
if let Some(vals) = self.labels.int64_view() {
return Self::value_counts_raw_i64(&vals, sort, ascending);
}
// Datetime64 / Timedelta64 (no NaT): reuse the i64 histogram and relabel
// the Int64 pairs to the temporal dtype instead of the cloned-key
// FxHashMap<IndexLabel> (value_counts over a DatetimeIndex was 0.58x
// pandas). NaT bails so the dropna fallback keeps its semantics.
// Bit-identical: value_counts_raw_i64 yields the same first-seen-then-sort
// (value, count) order; only the label variant changes (1:1 with the ns).
for datetime in [true, false] {
if let Some(ns) = self.temporal_ns_present(datetime) {
let (pairs, total) = Self::value_counts_raw_i64(&ns, sort, ascending);
let make: fn(i64) -> IndexLabel = if datetime {
IndexLabel::Datetime64
} else {
IndexLabel::Timedelta64
};
let pairs = pairs
.into_iter()
.map(|(label, count)| match label {
IndexLabel::Int64(v) => (make(v), count),
other => (other, count),
})
.collect();
return (pairs, total);
}
}
// Typed all-Utf8 fast path: tally `&str` keys (ONE `entry` hash per label,
// and NO per-label `String` clone — the generic path below clones every
// label twice into an `FxHashMap<IndexLabel>` key) — making value_counts a
// LOSS vs pandas. Both sides pure Utf8 (no Null), so `dropna` is moot
// (total == len). Bit-identical: same first-seen order, same per-label
// counts, same `sort_by_key` (stable, so first-seen breaks ties). Allocates
// a String only once per DISTINCT label when building the final pairs.
if self
.labels()
.iter()
.all(|l| matches!(l, IndexLabel::Utf8(_)))
{
let labels = self.labels();
let mut seen_order: Vec<&str> = Vec::new();
let mut counts: FxHashMap<&str, usize> = FxHashMap::default();
for label in labels {
if let IndexLabel::Utf8(s) = label {
let e = counts.entry(s.as_str()).or_insert(0);
if *e == 0 {
seen_order.push(s.as_str());
}
*e += 1;
}
}
let total = labels.len();
let mut pairs: Vec<(IndexLabel, usize)> = seen_order
.into_iter()
.map(|s| (IndexLabel::Utf8(s.to_owned()), counts[s]))
.collect();
if sort {
if ascending {
pairs.sort_by_key(|entry| entry.1);
} else {
pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
}
}
return (pairs, total);
}
let mut seen_order: Vec<IndexLabel> = Vec::new();
let mut counts: FxHashMap<IndexLabel, usize> = FxHashMap::default();
let mut total = 0usize;
for label in &self.labels {
if dropna && label.is_missing() {
continue;
}
total += 1;
if !counts.contains_key(label) {
seen_order.push(label.clone());
}
*counts.entry(label.clone()).or_insert(0) += 1;
}
let mut pairs: Vec<(IndexLabel, usize)> = seen_order
.into_iter()
.map(|label| {
let count = counts[&label];
(label, count)
})
.collect();
if sort {
if ascending {
pairs.sort_by_key(|entry| entry.1);
} else {
pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
}
}
(pairs, total)
}
/// Count occurrences of each distinct label.
///
/// Matches `pd.Index.value_counts()` default behavior. Missing labels are
/// dropped, counts are sorted descending, and first-seen order breaks ties.
#[must_use]
pub fn value_counts(&self) -> Vec<(IndexLabel, usize)> {
self.value_counts_raw(true, false, true).0
}
/// Count occurrences of each distinct label with pandas-style options.
///
/// Matches `pd.Index.value_counts(normalize, sort, ascending, dropna)`.
/// Returns `Scalar::Int64` counts unless `normalize=true`, in which case
/// the values are `Scalar::Float64` fractions.
#[must_use]
pub fn value_counts_with_options(
&self,
normalize: bool,
sort: bool,
ascending: bool,
dropna: bool,
) -> Vec<(IndexLabel, Scalar)> {
let (pairs, total) = self.value_counts_raw(sort, ascending, dropna);
if normalize {
let denom = total as f64;
return pairs
.into_iter()
.map(|(label, count)| (label, Scalar::Float64(count as f64 / denom)))
.collect();
}
pairs
.into_iter()
.map(|(label, count)| (label, Scalar::Int64(count as i64)))
.collect()
}
/// Shift the labels by `periods` positions, filling vacated slots
/// with `fill`.
///
/// ⚠️ THIS IS NOT `pd.Index.shift`, and the claim that used to be here cited a
/// signature pandas does not have. It said "Matches `pd.Index.shift(periods,
/// fill_value=...)` for the positional form". MEASURED, live pandas 2.2.3
/// (CrimsonPine 2026-08-19):
/// ```text
/// inspect.signature(pd.Index.shift) -> (self, periods=1, freq=None)
/// there is NO fill_value parameter, and no positional form at all
/// pd.Index([10,20,30]).shift(1)
/// -> NotImplementedError: This method is only implemented for
/// DatetimeIndex, PeriodIndex and TimedeltaIndex
/// pd.date_range('2024-01-01', periods=3, freq='D').shift(1)
/// -> ['2024-01-02','2024-01-03','2024-01-04']
/// labels move FORWARD IN TIME by one freq unit; length preserved;
/// nothing is filled and nothing falls off the end
/// pd.DatetimeIndex([...]).shift(1) with no inferable freq
/// -> NullFrequencyError: Cannot shift with no freq
/// ```
/// So pandas' `Index.shift` is a TEMPORAL relabel available only on datetime-like
/// indexes, whereas this is a POSITIONAL shift that vacates slots and fills them —
/// the semantics of `pd.Series.shift`, applied to labels. The two share a name and
/// nothing else.
///
/// Kept as a FrankenPandas operation (its behaviour is pinned by
/// `index_shift_positive_pads_left` / `_negative_pads_right` / `_zero_is_clone`);
/// only the false parity claim is removed. Positive periods shift right, negative
/// shift left.
#[must_use]
pub fn shift(&self, periods: i64, fill: IndexLabel) -> Self {
let len = self.labels.len();
if len == 0 || periods == 0 {
return self.clone();
}
let abs = periods.unsigned_abs() as usize;
if let Some(values) = self.labels.int64_view()
&& let IndexLabel::Int64(fill_value) = &fill
{
let mut out: Vec<i64> = Vec::with_capacity(len);
if abs >= len {
out.resize(len, *fill_value);
} else if periods > 0 {
out.resize(abs, *fill_value);
out.extend_from_slice(&values[..len - abs]);
} else {
out.extend_from_slice(&values[abs..]);
out.resize(len, *fill_value);
}
return self.propagate_name(Self::from_i64_values(out));
}
let mut out: Vec<IndexLabel> = Vec::with_capacity(len);
if abs >= len {
for _ in 0..len {
out.push(fill.clone());
}
} else if periods > 0 {
for _ in 0..abs {
out.push(fill.clone());
}
out.extend_from_slice(&self.labels[..len - abs]);
} else {
out.extend_from_slice(&self.labels[abs..]);
for _ in 0..abs {
out.push(fill.clone());
}
}
self.propagate_name(Self::new(out))
}
/// Nearest-preceding-or-equal label lookup.
///
/// Matches `pd.Index.asof(label)` for monotonic-increasing indexes: returns the
/// largest label `<= key`, or `None` when the key precedes every entry.
///
/// ⚠️ THE NON-MONOTONIC CLAIM THAT USED TO BE HERE WAS WRONG IN BOTH HALVES. It
/// said pandas "emits a warning in the non-monotonic case but still does a linear
/// scan — we match that behavior". MEASURED, live pandas 2.2.3 (CrimsonPine
/// 2026-08-19), on `pd.Index([30, 10, 20])`:
/// ```text
/// .asof(25) -> ValueError: index must be monotonic increasing or decreasing
/// .asof(5) -> ValueError (same)
/// .asof(35) -> ValueError (same)
/// ```
/// pandas REFUSES; it does not warn and scan. And this function does not scan
/// either — the loop below BREAKS at the first label greater than the key, which
/// is correct only on sorted input. So on `[30, 10, 20]` it stops at 30 and
/// returns `None`, silently answering "nothing precedes 25" for an index that
/// contains 20.
///
/// ⚠️ DOCUMENTED DIVERGENCE, not a fix: matching pandas means RAISING on a
/// non-monotonic index, and this returns `Option` rather than `Result`, so the
/// change is a signature decision rather than a repair. Callers must sort first;
/// `is_sorted()` answers the precondition. Pinned by
/// `asof_on_a_non_monotonic_index_is_a_documented_divergence`.
#[must_use]
pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
if let (Some(range), IndexLabel::Int64(needle)) = (self.labels.int64_affine_range(), key) {
if range.len == 0 {
return None;
}
if range.len == 1 {
return (range.start <= *needle).then_some(IndexLabel::Int64(range.start));
}
if range.step > 0 {
let delta = i128::from(*needle) - i128::from(range.start);
if delta < 0 {
return None;
}
let position = usize::try_from(delta / i128::from(range.step))
.unwrap_or(range.len - 1)
.min(range.len - 1);
return Some(IndexLabel::Int64(range.value_at(position)));
}
}
if self.labels.has_lazy_int64_backing()
&& let IndexLabel::Int64(needle) = key
&& let Some(values) = self.labels.int64_view()
{
let mut best = None;
for &value in values.iter() {
if value <= *needle {
best = Some(value);
} else {
break;
}
}
return best.map(IndexLabel::Int64);
}
let mut best: Option<&IndexLabel> = None;
for label in &self.labels {
if label.is_missing() {
continue;
}
if label.cmp(key).is_le() {
best = Some(label);
} else {
break;
}
}
best.cloned()
}
/// Position where `value` would be inserted to keep the index
/// sorted ascending.
///
/// Matches `pd.Index.searchsorted(value, side)`. `side` is
/// `"left"` (first valid insertion) or `"right"` (last). Returns
/// an error for unknown sides or missing needles.
pub fn searchsorted(&self, value: &IndexLabel, side: &str) -> Result<usize, IndexError> {
if side != "left" && side != "right" {
return Err(IndexError::InvalidArgument(format!(
"searchsorted: side must be 'left' or 'right', got {side:?}"
)));
}
if value.is_missing() {
return Err(IndexError::InvalidArgument(
"searchsorted: needle cannot be missing".to_owned(),
));
}
if let Some(range) = self.labels.int64_affine_range()
&& let IndexLabel::Int64(needle) = value
{
if range.len == 0 {
return Ok(0);
}
if range.len == 1 {
let go_right = range.start < *needle || (range.start == *needle && side == "right");
return Ok(usize::from(go_right));
}
if range.step > 0 {
if *needle < range.start {
return Ok(0);
}
let delta = i128::from(*needle) - i128::from(range.start);
let step = i128::from(range.step);
let mut position = delta / step;
if side == "right" || delta % step != 0 {
position += 1;
}
return Ok(usize::try_from(position)
.unwrap_or(range.len)
.min(range.len));
}
}
if self.labels.has_lazy_int64_backing()
&& let IndexLabel::Int64(needle) = value
&& let Some(values) = self.labels.int64_view()
{
let mut lo = 0usize;
let mut hi = values.len();
while lo < hi {
let mid = lo + (hi - lo) / 2;
let go_right = values[mid] < *needle || (values[mid] == *needle && side == "right");
if go_right {
lo = mid + 1;
} else {
hi = mid;
}
}
return Ok(lo);
}
let mut lo = 0usize;
let mut hi = self.labels.len();
while lo < hi {
let mid = lo + (hi - lo) / 2;
let cmp = if self.labels[mid].is_missing() {
std::cmp::Ordering::Greater
} else {
self.labels[mid].cmp(value)
};
use std::cmp::Ordering;
let go_right = matches!(
(cmp, side),
(Ordering::Less, _) | (Ordering::Equal, "right")
);
if go_right {
lo = mid + 1;
} else {
hi = mid;
}
}
Ok(lo)
}
/// Approximate memory footprint (bytes) occupied by the labels.
///
/// Matches `pd.Index.memory_usage(deep=...)`. `deep=false` uses
/// a fixed per-label width (8 bytes for Int64/Timedelta64/
/// Datetime64, pointer-size for Utf8); `deep=true` additionally
/// accounts for each Utf8 string's byte length.
#[must_use]
pub fn memory_usage(&self, deep: bool) -> usize {
if self.labels.has_lazy_int64_backing() {
return fixed_width_label_memory_usage(self.labels.len(), 8);
}
self.labels.iter().fold(0usize, |total, label| {
total.saturating_add(match label {
IndexLabel::Int64(_)
| IndexLabel::Float64(_)
| IndexLabel::Timedelta64(_)
| IndexLabel::Datetime64(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_) => 8,
IndexLabel::Bool(_) => 1,
IndexLabel::Utf8(s) => {
if deep {
std::mem::size_of::<String>().saturating_add(s.len())
} else {
std::mem::size_of::<String>()
}
}
})
})
}
/// Number of levels in this index.
///
/// Matches `pd.Index.nlevels`. Always 1 for the flat Index type;
/// MultiIndex already overrides this. Provided so callers can
/// write level-agnostic code that works on either kind.
#[must_use]
pub fn nlevels(&self) -> usize {
1
}
/// Materialize labels into an owned `Vec<IndexLabel>`.
///
/// Matches `pd.Index.to_list()`. Convenience helper for callers
/// that need ownership without manually cloning via `labels()`.
#[must_use]
pub fn to_list(&self) -> Vec<IndexLabel> {
self.labels.to_owned_labels()
}
/// Stringify each label using its `Display` impl.
///
/// Matches `pd.Index.format()` / `pd.Index.astype(str).tolist()`.
/// Result is a `Vec<String>` in index order.
#[must_use]
pub fn format(&self) -> Vec<String> {
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
return values.iter().map(ToString::to_string).collect();
}
self.labels.iter().map(IndexLabel::to_string).collect()
}
/// Replace labels at positions where `cond` is true with `value`.
///
/// Matches `pd.Index.putmask(cond, value)`. A shorter `cond`
/// leaves trailing labels unchanged (pandas-style lenient
/// alignment); a longer `cond` is silently truncated. The name
/// is preserved. It is [`Self::where_cond`] of the other labels, so an
/// int index given a NaN or a float turns float64 as there (it kept
/// int64 beside the NaN; br-frankenpandas-oq1df).
#[must_use]
pub fn putmask(&self, cond: &[bool], value: &IndexLabel) -> Self {
let kept: Vec<bool> = (0..self.len())
.map(|i| !cond.get(i).copied().unwrap_or(false))
.collect();
self.where_cond(&kept, value)
}
/// Whether any label coerces to true.
///
/// Matches `pd.Index.any()`. Non-zero integers, non-empty strings,
/// and non-NaT timedeltas count as truthy. Missing labels are
/// treated as falsy. Empty index returns false.
#[must_use]
pub fn any(&self) -> bool {
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
return values.iter().any(|&value| value != 0);
}
self.labels.iter().any(index_label_is_truthy)
}
/// Whether all labels coerce to true.
///
/// Matches `pd.Index.all()`. Empty index returns true (pandas
/// convention: vacuously true). Missing labels count as falsy.
#[must_use]
pub fn all(&self) -> bool {
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
return values.iter().all(|&value| value != 0);
}
self.labels.iter().all(index_label_is_truthy)
}
/// Drop missing labels, preserving order.
///
/// Matches `pd.Index.dropna()`. Labels whose `is_missing()` returns
/// true are removed. The name (if any) is preserved.
#[must_use]
pub fn dropna(&self) -> Self {
if self.labels.has_lazy_int64_backing() {
return self.clone();
}
self.propagate_name(Self::new(
self.labels
.iter()
.filter(|label| !label.is_missing())
.cloned()
.collect(),
))
}
/// Insert a new label at the given position.
///
/// Matches `pd.Index.insert(loc, item)`. `loc` is an ordinal position
/// where the new label is inserted; positions equal to `len()` append
/// to the end. Out-of-bounds positions return an `OutOfBounds` error.
pub fn insert(&self, loc: usize, item: IndexLabel) -> Result<Self, IndexError> {
if loc > self.labels.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: self.labels.len(),
});
}
if let Some(values) = self.labels.int64_view()
&& let IndexLabel::Int64(value) = &item
{
let mut out = Vec::with_capacity(insert_output_capacity(values.len()));
let (head, tail) = values.split_at(loc);
out.extend_from_slice(head);
out.push(*value);
out.extend_from_slice(tail);
return Ok(self.propagate_name(Self::from_i64_values(out)));
}
let mut labels = self.labels().to_vec();
labels.insert(loc, item);
Ok(self.propagate_name(Self::new(labels)))
}
/// Delete the label at the given position.
///
/// Matches `pd.Index.delete(loc)`. Returns an `OutOfBounds` error
/// for positions outside `0..len()`.
pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
if loc >= self.labels.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: self.labels.len(),
});
}
if let Some(values) = self.labels.int64_view() {
let mut out = Vec::with_capacity(values.len() - 1);
let (head, deleted_and_tail) = values.split_at(loc);
let (_, tail) = deleted_and_tail.split_at(1);
out.extend_from_slice(head);
out.extend_from_slice(tail);
return Ok(self.propagate_name(Self::from_i64_values(out)));
}
let mut labels = self.labels().to_vec();
labels.remove(loc);
Ok(self.propagate_name(Self::new(labels)))
}
/// Append another index to the end of this one.
///
/// Matches `pd.Index.append(other)`. The returned index contains
/// `self.labels` followed by `other.labels`. Name is preserved from
/// `self`; a time zone only when both share it.
#[must_use]
pub fn append(&self, other: &Self) -> Self {
if let (Some(left), Some(right)) = (self.labels.int64_view(), other.labels.int64_view()) {
let mut values = Vec::with_capacity(combined_output_capacity(left.len(), right.len()));
values.extend_from_slice(left.as_slice());
values.extend_from_slice(right.as_slice());
return self.propagate_name(Self::from_i64_values(values));
}
let mut labels = self.labels().to_vec();
labels.extend(other.labels.iter().cloned());
let mut appended = self.propagate_name(Self::new(labels));
if self.tz != other.tz {
appended.tz = None;
}
appended
}
/// Repeat each label `repeats` times.
///
/// Matches `pd.Index.repeat(repeats)`. `repeats=0` yields an empty
/// index; `repeats=1` is a no-op clone. Name is preserved.
#[must_use]
pub fn repeat(&self, repeats: usize) -> Self {
if repeats == 0 {
if self.labels.int64_view().is_some() {
return self.propagate_name(Self::from_i64_values(Vec::new()));
}
return self.propagate_name(Self::new(Vec::new()));
}
if repeats == 1 {
return self.clone();
}
if let Some(values) = self.labels.int64_view() {
let mut out = Vec::with_capacity(repeat_output_capacity(values.len(), repeats));
for &value in values.iter() {
for _ in 0..repeats {
out.push(value);
}
}
return self.propagate_name(Self::from_i64_values(out));
}
let mut out = Vec::with_capacity(repeat_output_capacity(self.labels.len(), repeats));
for label in &self.labels {
for _ in 0..repeats {
out.push(label.clone());
}
}
self.propagate_name(Self::new(out))
}
/// Fill missing labels with the provided scalar.
///
/// Matches `pd.Index.fillna(value)`.
#[must_use]
pub fn fillna(&self, value: &IndexLabel) -> Self {
if self.labels.has_lazy_int64_backing() {
return self.clone();
}
self.propagate_name(Self::new(
self.labels
.iter()
.map(|label| {
if label.is_missing() {
value.clone()
} else {
label.clone()
}
})
.collect(),
))
}
/// Matches `pd.Index.isna()`.
#[must_use]
pub fn isna(&self) -> Vec<bool> {
if self.labels.has_lazy_int64_backing() {
return vec![false; self.labels.len()];
}
self.labels.iter().map(IndexLabel::is_missing).collect()
}
/// Matches `pd.Index.notna()`.
#[must_use]
pub fn notna(&self) -> Vec<bool> {
if self.labels.has_lazy_int64_backing() {
return vec![true; self.labels.len()];
}
self.labels
.iter()
.map(|label| !label.is_missing())
.collect()
}
/// Where: replace labels at false positions with a fill value.
///
/// Matches `pd.Index.where(cond, other)`.
#[must_use]
pub fn where_cond(&self, cond: &[bool], other: &IndexLabel) -> Self {
if let Some(values) = self.labels.int64_view()
&& let IndexLabel::Int64(replacement) = other
{
let new_labels: Vec<i64> = values
.iter()
.enumerate()
.map(|(i, &label)| {
if cond.get(i).copied().unwrap_or(false) {
label
} else {
*replacement
}
})
.collect();
return self.propagate_name(Self::from_i64_values(new_labels));
}
// An int index given a NaN or a float in place of a label is float64,
// as pandas' (the ints stayed beside the NaN: an int64 index holding
// NaN; br-frankenpandas-oq1df).
let replaced = (0..self.len()).any(|i| !cond.get(i).copied().unwrap_or(false));
let widened = replaced
&& matches!(
other,
IndexLabel::Float64(_) | IndexLabel::Null(fp_types::NullKind::NaN)
)
&& self
.labels
.iter()
.all(|label| matches!(label, IndexLabel::Int64(_)));
self.propagate_name(Self::new(
self.labels
.iter()
.enumerate()
.map(|(i, l)| {
if !cond.get(i).copied().unwrap_or(false) {
other.clone()
} else if let (true, IndexLabel::Int64(value)) = (widened, l) {
#[allow(clippy::cast_precision_loss)] // pandas' int64 -> float64
let value = *value as f64;
IndexLabel::Float64(OrderedF64(value))
} else {
l.clone()
}
})
.collect(),
))
}
/// Alias for `union_with`, matching `pd.Index.union`.
#[must_use]
pub fn union(&self, other: &Self) -> Self {
self.union_with(other)
}
/// Alias for `sort_values`, matching `pd.Index.sort`.
#[must_use]
pub fn sort(&self) -> Self {
self.sort_values()
}
/// Sort labels and return the positional indexer used for the sort.
///
/// Matches the flat-index shape of `pd.Index.sortlevel()`.
#[must_use]
pub fn sortlevel(&self) -> (Self, Vec<usize>) {
let order = self.argsort();
(self.take(&order), order)
}
/// Alias for `drop_labels`, matching `pd.Index.drop`.
#[must_use]
pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Self {
self.drop_labels(labels_to_drop)
}
/// Clone this index, matching `pd.Index.copy`.
#[must_use]
pub fn copy(&self) -> Self {
self.clone()
}
/// Alias for `where_cond`, matching `pd.Index.where`.
#[must_use]
pub fn where_(&self, cond: &[bool], other: &IndexLabel) -> Self {
self.where_cond(cond, other)
}
/// Alias for `to_list`, matching `pd.Index.tolist`.
#[must_use]
pub fn tolist(&self) -> Vec<IndexLabel> {
self.to_list()
}
/// Object-array-shaped materialization, matching `pd.Index.to_numpy`.
#[must_use]
pub fn to_numpy(&self) -> Vec<IndexLabel> {
self.to_list()
}
/// Alias for `to_numpy`, matching `pd.Index.array`.
#[must_use]
pub fn array(&self) -> Vec<IndexLabel> {
self.to_numpy()
}
/// Alias for `to_numpy`, matching `pd.Index.values`.
#[must_use]
pub fn values(&self) -> Vec<IndexLabel> {
self.to_numpy()
}
/// Alias for `to_numpy`, matching `pd.Index.ravel`.
#[must_use]
pub fn ravel(&self) -> Vec<IndexLabel> {
self.to_numpy()
}
/// Return a shallow clone view, matching `pd.Index.view` for this
/// immutable Rust representation.
#[must_use]
pub fn view(&self) -> Self {
self.clone()
}
/// Flat-index transpose is identity, matching `pd.Index.transpose`.
#[must_use]
pub fn transpose(&self) -> Self {
self.clone()
}
/// Alias for `transpose`, matching `pd.Index.T`.
#[allow(non_snake_case)]
#[must_use]
pub fn T(&self) -> Self {
self.transpose()
}
/// One-column row materialization, matching the flat-index shape of
/// `pd.Index.to_frame(index=False)`.
#[must_use]
pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
if let Some(values) = self.labels.int64_view() {
return values
.iter()
.map(|&value| vec![IndexLabel::Int64(value)])
.collect();
}
self.labels
.iter()
.map(|label| vec![label.clone()])
.collect()
}
/// Series-shaped materialization using the index labels as both index and
/// values until `fp-frame` owns the richer return type.
#[must_use]
pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
if let Some(values) = self.labels.int64_view() {
return values
.iter()
.map(|&value| {
let label = IndexLabel::Int64(value);
(label.clone(), label)
})
.collect();
}
self.labels
.iter()
.map(|label| (label.clone(), label.clone()))
.collect()
}
/// Pandas dtype string for this flat index.
#[must_use]
pub fn dtype(&self) -> &'static str {
if let Some(declared) = self.declared {
return declared.name();
}
// A range is int64 when it holds no label too (an empty one was
// object; br-frankenpandas-7bope).
if self.range.is_some() {
return "int64";
}
match self.inferred_type() {
"integer" => "int64",
"floating" => "float64",
"boolean" => "bool",
"string" => "object",
"timedelta64" => "timedelta64[ns]",
"datetime64" => "datetime64[ns]",
"empty" | "mixed" => "object",
_ => "object",
}
}
/// One-element dtype list, matching the `.dtypes` accessor shape used by
/// pandas containers.
#[must_use]
pub fn dtypes(&self) -> Vec<&'static str> {
vec![self.dtype()]
}
/// Infer object labels without changing the current typed representation.
#[must_use]
pub fn infer_objects(&self) -> Self {
self.clone()
}
/// Whether this index's dtype can hold integer labels.
#[must_use]
pub fn holds_integer(&self) -> bool {
self.is_integer()
}
/// Pandas-style inferred-type string for the label values.
#[must_use]
pub fn inferred_type(&self) -> &'static str {
if self.labels.is_empty() {
return "empty";
}
if self.labels.has_lazy_int64_backing() {
return "integer";
}
let mut non_missing = self.labels.iter().filter(|label| !label.is_missing());
let Some(first) = non_missing.next() else {
// Every label is missing: pandas infers NaN floating (NaN beside
// None too), NaT an instant and None alone mixed - an all-NaN
// index is float64 (it was object; br-frankenpandas-mzes1).
let all = |kind: fn(&IndexLabel) -> bool| self.labels.iter().all(kind);
return if all(|label| {
matches!(
label,
IndexLabel::Datetime64(_) | IndexLabel::Null(fp_types::NullKind::NaT)
)
}) {
"datetime64"
} else if all(|label| matches!(label, IndexLabel::Timedelta64(_))) {
"timedelta64"
} else if all(|label| matches!(label, IndexLabel::Period(_))) {
// A PeriodIndex of NaT alone is still one (45fzr).
"period"
} else if self.labels.iter().any(|label| {
matches!(
label,
IndexLabel::Float64(_) | IndexLabel::Null(fp_types::NullKind::NaN)
)
}) && all(|label| {
matches!(
label,
IndexLabel::Float64(_)
| IndexLabel::Null(fp_types::NullKind::NaN | fp_types::NullKind::Null)
)
}) {
"floating"
} else {
"mixed"
};
};
let same_kind = |label: &IndexLabel| {
matches!(
(first, label),
(IndexLabel::Int64(_), IndexLabel::Int64(_))
| (IndexLabel::Float64(_), IndexLabel::Float64(_))
| (IndexLabel::Bool(_), IndexLabel::Bool(_))
| (IndexLabel::Utf8(_), IndexLabel::Utf8(_))
| (IndexLabel::Timedelta64(_), IndexLabel::Timedelta64(_))
| (IndexLabel::Datetime64(_), IndexLabel::Datetime64(_))
) || matches!(
(first, label),
(IndexLabel::Period(a), IndexLabel::Period(b)) if a.freq == b.freq
) || matches!(
(first, label),
(IndexLabel::Interval(_), IndexLabel::Interval(_))
)
};
if !non_missing.all(same_kind) {
return "mixed";
}
// pandas infers with skipna=False: a missing label beside bools or
// strings is a kind of its own (an object Index; `[True, None]` read
// bool), where NaN is a float and NaT an instant.
let beside_missing = |kind| {
if self.labels.iter().any(IndexLabel::is_missing) {
"mixed"
} else {
kind
}
};
match first {
IndexLabel::Int64(_) => "integer",
IndexLabel::Float64(_) => "floating",
IndexLabel::Bool(_) => beside_missing("boolean"),
IndexLabel::Utf8(_) => beside_missing("string"),
IndexLabel::Timedelta64(_) => "timedelta64",
IndexLabel::Datetime64(_) => "datetime64",
// Periods of one freq (a NaT beside them too); another freq
// among them was mixed above.
IndexLabel::Period(_) => "period",
IndexLabel::Interval(_) => "interval",
// The core cannot read an object's kind (pandas says "date" for
// datetime.date labels); and unreachable for Null: `first` comes
// from the non-missing iterator and every Null label is_missing.
IndexLabel::Object(_) | IndexLabel::Null(_) => "mixed",
}
}
/// Whether this index contains missing labels, matching `pd.Index.hasnans`.
#[must_use]
pub fn hasnans(&self) -> bool {
if self.labels.has_lazy_int64_backing() {
return false;
}
self.labels.iter().any(IndexLabel::is_missing)
}
/// Number of dimensions, matching `pd.Index.ndim`.
#[must_use]
pub fn ndim(&self) -> usize {
1
}
/// One-dimensional shape, matching `pd.Index.shape`.
#[must_use]
pub fn shape(&self) -> (usize,) {
(self.len(),)
}
/// Number of entries, matching `pd.Index.size`.
#[must_use]
pub fn size(&self) -> usize {
self.len()
}
/// Shallow byte footprint, matching `pd.Index.nbytes`.
#[must_use]
pub fn nbytes(&self) -> usize {
self.memory_usage(false)
}
/// Alias for `is_empty`, matching the pandas `.empty` property.
#[must_use]
pub fn empty(&self) -> bool {
self.is_empty()
}
/// Return the single contained label.
///
/// Matches `pd.Index.item()`, which rejects indexes with length other than
/// one.
pub fn item(&self) -> Result<IndexLabel, IndexError> {
if self.len() == 1 {
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
&& let Some(&value) = values.first()
{
return Ok(IndexLabel::Int64(value));
}
Ok(self.labels[0].clone())
} else {
Err(IndexError::InvalidArgument(format!(
"item requires exactly one label, got {}",
self.len()
)))
}
}
/// Identity check, matching `pd.Index.is_`.
#[must_use]
pub fn is_(&self, other: &Self) -> bool {
std::ptr::eq(self, other)
}
/// Whether all non-missing labels are booleans.
#[must_use]
pub fn is_boolean(&self) -> bool {
false
}
/// Whether this generic index is categorical.
#[must_use]
pub fn is_categorical(&self) -> bool {
false
}
/// Whether all non-missing labels are floating-point.
#[must_use]
pub fn is_floating(&self) -> bool {
false
}
/// Whether all non-missing labels are Int64 labels.
#[must_use]
pub fn is_integer(&self) -> bool {
if self.labels.has_lazy_int64_backing() {
return !self.labels.is_empty();
}
!self.labels.is_empty()
&& self
.labels
.iter()
.filter(|label| !label.is_missing())
.all(|label| matches!(label, IndexLabel::Int64(_)))
}
/// Whether this generic index is interval-typed.
#[must_use]
pub fn is_interval(&self) -> bool {
false
}
/// Whether all non-missing labels are numeric.
#[must_use]
pub fn is_numeric(&self) -> bool {
self.is_integer()
}
/// Whether this index is object-backed.
#[must_use]
pub fn is_object(&self) -> bool {
matches!(self.dtype(), "object")
}
/// Alias for `isna`, matching `pd.Index.isnull`.
#[must_use]
pub fn isnull(&self) -> Vec<bool> {
self.isna()
}
/// Alias for `notna`, matching `pd.Index.notnull`.
#[must_use]
pub fn notnull(&self) -> Vec<bool> {
self.notna()
}
/// Factorize labels into integer codes and unique labels.
///
/// Missing labels receive code `-1`; non-missing labels preserve first-seen
/// order in the returned uniques index.
#[must_use]
pub fn factorize(&self) -> (Vec<isize>, Self) {
// Typed all-Int64 fast path: inline `i64` codes (dense code table when
// the value span is bounded) instead of the cloned-key
// `FxHashMap<IndexLabel, isize>`. Int64 labels are never missing, so the
// generic `-1` missing branch never fires — bit-identical codes/uniques.
if let Some(vals) = self.labels.int64_view() {
let (codes, uniques) = Self::factorize_i64(&vals);
// Build the uniques over the typed Int64 backing — defers the
// per-label `IndexLabel` materialization the `Vec<IndexLabel>` form
// would force (the dominant tail at high cardinality).
return (codes, self.propagate_name(Self::from_i64(uniques)));
}
let mut positions = FxHashMap::<IndexLabel, isize>::default();
let mut uniques = Vec::<IndexLabel>::new();
let mut codes = Vec::with_capacity(self.labels.len());
for label in &self.labels {
if label.is_missing() {
codes.push(-1);
} else if let Some(code) = positions.get(label) {
codes.push(*code);
} else {
let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
positions.insert(label.clone(), code);
uniques.push(label.clone());
codes.push(code);
}
}
(codes, self.propagate_name(Self::new(uniques)))
}
/// Positional indexer that EXPANDS duplicate matches, matching
/// `pd.Index.get_indexer_for`.
///
/// ⚠️ This was an alias for [`Self::get_indexer`], and pandas defines the two as
/// DIFFERENT precisely when the source has duplicates — that is the whole reason
/// `get_indexer_for` exists. pandas' rule is: `get_indexer` when the index is
/// unique, otherwise `get_indexer_non_unique(target)[0]`, so the result can be
/// LONGER than `target`.
///
/// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18), index `[10, 20, 20, 30]`:
/// ```text
/// target [20, 99, 10]
/// get_indexer_for -> [1, 2, -1, 0] FOUR entries for a THREE-entry target
/// get_indexer -> InvalidIndexError: Reindexing only valid with uniquely
/// valued Index objects
/// ```
/// The duplicate 20 contributes both of its positions. A `-1` (missing) becomes
/// `None` here, keeping this crate's `Option` spelling.
///
/// The sibling [`MultiIndex::get_indexer`] already models this correctly — it
/// REFUSES a duplicate-bearing source and documents that callers wanting
/// expansion should use `get_indexer_for` or `get_indexer_non_unique`. The flat
/// index simply had not been given the same treatment.
///
/// ⚠️ [`Self::get_indexer`] still does NOT refuse a duplicate source the way
/// pandas does; it answers with the first match per target. Changing that is a
/// signature question (it returns a `Vec`, not a `Result`) and is left alone
/// here so this stays a behaviour fix on one method.
#[must_use]
pub fn get_indexer_for(&self, target: &Self) -> Vec<Option<usize>> {
if self.has_duplicates() {
return self
.get_indexer_non_unique(target)
.0
.into_iter()
.map(|position| usize::try_from(position).ok())
.collect();
}
self.get_indexer(target)
}
/// Expand duplicate matches while indexing a target index.
///
/// Matches `pd.Index.get_indexer_non_unique(target)` shape: every matching
/// source position is emitted for each target label, and missing target
/// ordinal positions are returned separately.
#[must_use]
pub fn get_indexer_non_unique(&self, target: &Self) -> (Vec<isize>, Vec<usize>) {
if let (Some(source), Some(targets)) =
(self.labels.int64_view(), target.labels.int64_view())
{
if let Some(result) = Self::get_indexer_non_unique_sorted_dense_i64(&source, &targets) {
return result;
}
let mut positions = FxHashMap::<i64, Vec<usize>>::default();
for (position, &label) in source.iter().enumerate() {
positions.entry(label).or_default().push(position);
}
let mut indexer = Vec::with_capacity(targets.len());
let mut missing = Vec::new();
for (target_position, &label) in targets.iter().enumerate() {
if let Some(source_positions) = positions.get(&label) {
indexer.extend(
source_positions
.iter()
.map(|position| isize::try_from(*position).unwrap_or(isize::MAX)),
);
} else {
indexer.push(-1);
missing.push(target_position);
}
}
return (indexer, missing);
}
// Typed all-Utf8 fast path: key the source position map on `&str` instead
// of cloning every source `IndexLabel` (a String alloc per source row).
// Gate BOTH sides pure Utf8 (no Null) so every target label is a `&str`
// lookup (no skipped emissions). Bit-identical: same per-key source-order
// position lists, same target-order indexer, same missing list.
let self_labels = self.labels();
let target_labels = target.labels();
if self_labels.iter().all(|l| matches!(l, IndexLabel::Utf8(_)))
&& target_labels
.iter()
.all(|l| matches!(l, IndexLabel::Utf8(_)))
{
let mut positions = FxHashMap::<&str, Vec<usize>>::default();
for (position, label) in self_labels.iter().enumerate() {
if let IndexLabel::Utf8(s) = label {
positions.entry(s.as_str()).or_default().push(position);
}
}
let mut indexer = Vec::new();
let mut missing = Vec::new();
for (target_position, label) in target_labels.iter().enumerate() {
if let IndexLabel::Utf8(s) = label {
if let Some(source_positions) = positions.get(s.as_str()) {
indexer.extend(
source_positions
.iter()
.map(|position| isize::try_from(*position).unwrap_or(isize::MAX)),
);
} else {
indexer.push(-1);
missing.push(target_position);
}
}
}
return (indexer, missing);
}
let mut positions = FxHashMap::<IndexLabel, Vec<usize>>::default();
for (position, label) in self.labels.iter().enumerate() {
positions.entry(label.clone()).or_default().push(position);
}
let mut indexer = Vec::new();
let mut missing = Vec::new();
for (target_position, label) in target.labels.iter().enumerate() {
if let Some(source_positions) = positions.get(label) {
indexer.extend(
source_positions
.iter()
.map(|position| isize::try_from(*position).unwrap_or(isize::MAX)),
);
} else {
indexer.push(-1);
missing.push(target_position);
}
}
(indexer, missing)
}
/// Get labels for a level. Flat indexes only accept level 0.
pub fn get_level_values(&self, level: usize) -> Result<Self, IndexError> {
if level == 0 {
Ok(self.clone())
} else {
Err(IndexError::OutOfBounds {
position: level,
length: 1,
})
}
}
/// Bound for a label slice, matching `pd.Index.get_slice_bound(label,
/// side)`: over an increasing index where the label sorts; else the
/// label's own position (one past it for the right side; a run of equal
/// labels bounds by its ends), else where it sorts in a decreasing index.
/// A label an unsorted index does not hold is pandas' KeyError of it
/// ([`IndexError::LabelNotFound`]), one it holds apart from one run
/// pandas' non-unique KeyError. It was a bare searchsorted, wrong on a
/// decreasing or unsorted index (br-frankenpandas-h1kl9).
pub fn get_slice_bound(&self, label: &IndexLabel, side: &str) -> Result<usize, IndexError> {
let left = match side {
"left" => true,
"right" => false,
other => {
return Err(IndexError::InvalidArgument(format!(
"Invalid value for side kwarg, must be either 'left' or 'right': {other}"
)));
}
};
if self.is_monotonic_increasing() {
return self.searchsorted(label, side);
}
let labels = self.labels();
let matches: Vec<usize> = labels
.iter()
.enumerate()
.filter(|(_, candidate)| *candidate == label)
.map(|(position, _)| position)
.collect();
if let (Some(&first), Some(&last)) = (matches.first(), matches.last()) {
// Ascending positions are one run exactly when they span their
// count.
if last - first + 1 != matches.len() {
let shown = match label {
IndexLabel::Utf8(text) => format!("'{text}'"),
other => other.to_string(),
};
return Err(IndexError::KeyError(format!(
"Cannot get {side} slice bound for non-unique label: {shown}"
)));
}
return Ok(if left { first } else { last + 1 });
}
if self.is_monotonic_decreasing() && !label.is_missing() {
// The labels above the label (left) or not below it (right).
return Ok(labels
.iter()
.filter(|candidate| {
if left {
*candidate > label
} else {
*candidate >= label
}
})
.count());
}
Err(IndexError::LabelNotFound(label.clone()))
}
/// Return `(start, stop)` bounds for a label slice, as pandas'
/// `Index.slice_locs(start, end)`: each bound's [`Self::get_slice_bound`],
/// stop exclusive and not raised to the start (a stop before the start
/// slices nothing; it was clamped to the start).
pub fn slice_locs(
&self,
start: Option<&IndexLabel>,
end: Option<&IndexLabel>,
) -> Result<(usize, usize), IndexError> {
let start = match start {
Some(label) => self.get_slice_bound(label, "left")?,
None => 0,
};
let end = match end {
Some(label) => self.get_slice_bound(label, "right")?,
None => self.len(),
};
Ok((start, end))
}
/// Alias for `slice_locs`, matching `pd.Index.slice_indexer`.
pub fn slice_indexer(
&self,
start: Option<&IndexLabel>,
end: Option<&IndexLabel>,
) -> Result<(usize, usize), IndexError> {
self.slice_locs(start, end)
}
/// Reindex to a target index, returning the target and source positions.
#[must_use]
pub fn reindex(&self, target: &Self) -> (Self, Vec<Option<usize>>) {
(target.clone(), self.get_indexer(target))
}
/// Flat-index `droplevel` is invalid because it would remove the only
/// level.
pub fn droplevel(&self, level: usize) -> Result<Self, IndexError> {
if level == 0 {
Err(IndexError::InvalidArgument(
"cannot remove the only level from a flat Index".to_owned(),
))
} else {
Err(IndexError::OutOfBounds {
position: level,
length: 1,
})
}
}
/// Round Float64 labels to `decimals` places, halves to even as numpy's
/// `around` (which pandas' `Index.round` uses) does; a negative
/// `decimals` rounds to tens, hundreds, ... and then changes Int64 labels
/// too. Other labels are unchanged. This used to return the index
/// unchanged, float labels included
/// (br-frankenpandas-rc0923-epic-python-honest-dropin-fvsao.5).
#[must_use]
pub fn round(&self, decimals: i32) -> Self {
let labels = self
.labels()
.iter()
.map(|label| match label {
IndexLabel::Float64(f) => {
IndexLabel::Float64(OrderedF64(round_half_even(f.0, decimals)))
}
IndexLabel::Int64(i) if decimals < 0 => {
IndexLabel::Int64(round_half_even(*i as f64, decimals) as i64)
}
other => other.clone(),
})
.collect();
Self::new(labels).rename_index(self.name())
}
/// String accessor for Utf8 labels, matching `pd.Index.str`.
#[must_use]
pub fn r#str(&self) -> IndexStringAccessor<'_> {
IndexStringAccessor::borrowed(self)
}
/// Group label positions by label value, matching `pd.Index.groupby`.
#[must_use]
pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
let mut groups = HashMap::<IndexLabel, Vec<usize>>::new();
if self.labels.has_lazy_int64_backing()
&& let Some(values) = self.labels.int64_view()
{
for (position, &value) in values.iter().enumerate() {
groups
.entry(IndexLabel::Int64(value))
.or_default()
.push(position);
}
return groups;
}
for (position, label) in self.labels.iter().enumerate() {
groups.entry(label.clone()).or_default().push(position);
}
groups
}
/// Join two flat indexes using pandas-style join modes.
pub fn join(&self, other: &Self, how: &str) -> Result<Self, IndexError> {
match how {
"left" => Ok(self.clone()),
"right" => Ok(other.clone()),
"inner" => Ok(self.intersection(other)),
"outer" => Ok(self.union_with(other)),
other => Err(IndexError::InvalidArgument(format!(
"join: how must be 'left', 'right', 'inner', or 'outer', got {other:?}"
))),
}
}
/// Locate nearest preceding-or-equal positions for each target label.
///
/// Matches `pd.Index.asof_locs(where, mask)` for monotonic flat indexes.
#[must_use]
pub fn asof_locs(&self, where_index: &Self, mask: Option<&[bool]>) -> Vec<Option<usize>> {
if self.labels.has_lazy_int64_backing()
&& where_index.labels.has_lazy_int64_backing()
&& let (Some(source), Some(keys)) =
(self.labels.int64_view(), where_index.labels.int64_view())
{
if mask.is_none() {
if source.windows(2).all(|pair| pair[0] <= pair[1])
&& keys.windows(2).all(|pair| pair[0] <= pair[1])
{
let mut out = Vec::with_capacity(keys.len());
let mut source_pos = 0usize;
for &key in keys.iter() {
while source_pos < source.len() && source[source_pos] <= key {
source_pos += 1;
}
out.push(source_pos.checked_sub(1));
}
return out;
}
return keys
.iter()
.map(|&key| {
let mut lo = 0usize;
let mut hi = source.len();
while lo < hi {
let mid = lo + (hi - lo) / 2;
if source[mid] <= key {
lo = mid + 1;
} else {
hi = mid;
}
}
lo.checked_sub(1)
})
.collect();
}
return keys
.iter()
.map(|&key| {
let mut best = None;
for (position, &label) in source.iter().enumerate() {
if mask
.and_then(|values| values.get(position))
.is_some_and(|include| !include)
{
continue;
}
if label <= key {
best = Some(position);
} else {
break;
}
}
best
})
.collect();
}
where_index
.labels
.iter()
.map(|key| {
let mut best = None;
for (position, label) in self.labels.iter().enumerate() {
if mask
.and_then(|values| values.get(position))
.is_some_and(|include| !include)
{
continue;
}
if label.is_missing() {
continue;
}
if label.cmp(key).is_le() {
best = Some(position);
} else {
break;
}
}
best
})
.collect()
}
/// Positional first differences for comparable scalar index labels.
///
/// Int64 and Timedelta64 labels produce same-kind differences. Datetime64
/// labels produce Timedelta64 deltas. Unsupported label combinations and
/// overflow return `None` for that position.
#[must_use]
pub fn diff(&self, periods: usize) -> Vec<Option<IndexLabel>> {
if periods == 0 {
if let Some(values) = self.labels.int64_view() {
return values.iter().map(|_| Some(IndexLabel::Int64(0))).collect();
}
return self
.labels
.iter()
.map(|label| match label {
IndexLabel::Int64(_) => Some(IndexLabel::Int64(0)),
IndexLabel::Timedelta64(current) if *current != Timedelta::NAT => {
Some(IndexLabel::Timedelta64(0))
}
IndexLabel::Datetime64(current) if *current != i64::MIN => {
Some(IndexLabel::Timedelta64(0))
}
_ => None,
})
.collect();
}
if let Some(values) = self.labels.int64_view() {
let leading = periods.min(values.len());
let mut out = Vec::with_capacity(values.len());
out.extend(std::iter::repeat_n(None, leading));
if periods >= values.len() {
return out;
}
for (¤t, &previous) in values[periods..]
.iter()
.zip(&values[..values.len() - periods])
{
out.push(current.checked_sub(previous).map(IndexLabel::Int64));
}
return out;
}
let mut out = vec![None; self.len()];
for (position, slot) in out.iter_mut().enumerate().skip(periods) {
*slot = match (&self.labels[position], &self.labels[position - periods]) {
(IndexLabel::Int64(current), IndexLabel::Int64(previous)) => {
current.checked_sub(*previous).map(IndexLabel::Int64)
}
(IndexLabel::Timedelta64(current), IndexLabel::Timedelta64(previous))
if *current != Timedelta::NAT && *previous != Timedelta::NAT =>
{
current.checked_sub(*previous).map(IndexLabel::Timedelta64)
}
(IndexLabel::Datetime64(current), IndexLabel::Datetime64(previous))
if *current != i64::MIN && *previous != i64::MIN =>
{
current.checked_sub(*previous).map(IndexLabel::Timedelta64)
}
_ => None,
};
}
out
}
}
#[derive(Debug, Clone)]
pub struct IndexStringAccessor<'a> {
index: Cow<'a, Index>,
}
impl<'a> IndexStringAccessor<'a> {
fn borrowed(index: &'a Index) -> Self {
Self {
index: Cow::Borrowed(index),
}
}
fn owned(index: Index) -> Self {
Self {
index: Cow::Owned(index),
}
}
fn map_utf8<T>(&self, func: impl Fn(&str) -> T) -> Vec<Option<T>> {
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Utf8(value) => Some(func(value)),
IndexLabel::Int64(_)
| IndexLabel::Float64(_)
| IndexLabel::Bool(_)
| IndexLabel::Timedelta64(_)
| IndexLabel::Datetime64(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_) => None,
})
.collect()
}
/// Lowercase string labels.
#[must_use]
pub fn lower(&self) -> Vec<Option<String>> {
self.map_utf8(str::to_lowercase)
}
/// Uppercase string labels.
#[must_use]
pub fn upper(&self) -> Vec<Option<String>> {
self.map_utf8(str::to_uppercase)
}
/// Substring membership for string labels.
#[must_use]
pub fn contains(&self, needle: &str) -> Vec<Option<bool>> {
self.map_utf8(|value| value.contains(needle))
}
/// String length for string labels.
#[must_use]
pub fn len(&self) -> Vec<Option<usize>> {
self.map_utf8(str::len)
}
/// String emptiness for string labels.
#[must_use]
pub fn is_empty(&self) -> Vec<Option<bool>> {
self.map_utf8(str::is_empty)
}
}
fn datetime_from_nanos(nanos: i64) -> Option<chrono::DateTime<chrono::Utc>> {
if nanos == i64::MIN {
return None;
}
let secs = nanos.div_euclid(1_000_000_000);
let subsec_nanos = nanos.rem_euclid(1_000_000_000) as u32;
chrono::DateTime::from_timestamp(secs, subsec_nanos)
}
fn datetime_to_period_error(message: impl Into<String>) -> IndexError {
IndexError::InvalidArgument(format!(
"DatetimeIndex to_period failed: {}",
message.into()
))
}
/// The weekly ordinal of `date` for weeks ending on `freq`'s weekday:
/// whole weeks since the Monday 1969-12-22, the week start moved `shift`
/// days later for an anchor other than Sunday (W-MON weeks start Tuesday).
fn date_to_weekly_period_ordinal(
date: chrono::NaiveDate,
freq: PeriodFreq,
) -> Result<i64, IndexError> {
let base = period_epoch_date(1969, 12, 22)?;
Ok((date.signed_duration_since(base).num_days() - freq.week_start_shift()).div_euclid(7))
}
/// `date`'s month count since 1970-01 on `freq`'s fiscal calendar: a fiscal
/// year ending in June starts in July, so July 2023 counts as the first
/// month of fiscal 2024 (Period('2023-07-01', 'Y-JUN') is '2024').
fn fiscal_month_ordinal(date: chrono::NaiveDate, freq: PeriodFreq) -> Result<i64, IndexError> {
(i64::from(date.year()) - 1970)
.checked_mul(12)
.and_then(|base| base.checked_add(i64::from(date.month() - 1)))
.and_then(|months| months.checked_add(freq.fiscal_month_shift()))
.ok_or_else(|| datetime_to_period_error("fiscal month ordinal overflow"))
}
fn business_period_anchor_date(date: chrono::NaiveDate) -> Result<chrono::NaiveDate, IndexError> {
match date.weekday().num_days_from_monday() {
5 => period_add_days(date, 2),
6 => period_add_days(date, 1),
_ => Ok(date),
}
}
fn date_to_business_period_ordinal(date: chrono::NaiveDate) -> Result<i64, IndexError> {
let adjusted = business_period_anchor_date(date)?;
let days = adjusted
.signed_duration_since(period_epoch_date(1970, 1, 1)?)
.num_days();
let rem_ordinal = match days.rem_euclid(7) {
0 => 0,
1 => 1,
4 => 2,
5 => 3,
6 => 4,
_ => {
return Err(datetime_to_period_error(
"business period anchor did not land on a business day",
));
}
};
days.div_euclid(7)
.checked_mul(5)
.and_then(|base| base.checked_add(rem_ordinal))
.ok_or_else(|| datetime_to_period_error("business ordinal overflow"))
}
fn business_period_end_anchor_date(
date: chrono::NaiveDate,
) -> Result<chrono::NaiveDate, IndexError> {
match date.weekday().num_days_from_monday() {
5 => period_add_days(date, -1),
6 => period_add_days(date, -2),
_ => Ok(date),
}
}
fn datetime_period_ordinal(nanos: i64, freq: PeriodFreq) -> Result<i64, IndexError> {
let dt = datetime_from_nanos(nanos).ok_or_else(|| {
datetime_to_period_error(format!("invalid or NaT datetime nanos {nanos}"))
})?;
let date = dt.date_naive();
let year_offset = i64::from(date.year()) - 1970;
match freq {
// Fiscal years / quarters: the month count on the fiscal calendar,
// twelve (three) to a period (Q-JAN puts 2024-03 in 2025Q1).
PeriodFreq::Annual(_) => {
fiscal_month_ordinal(date, freq).map(|months| months.div_euclid(12))
}
PeriodFreq::Quarterly(_) => {
fiscal_month_ordinal(date, freq).map(|months| months.div_euclid(3))
}
PeriodFreq::Monthly => year_offset
.checked_mul(12)
.and_then(|base| base.checked_add(i64::from(date.month() - 1)))
.ok_or_else(|| datetime_to_period_error("monthly ordinal overflow")),
PeriodFreq::Daily => {
let epoch = chrono::NaiveDate::from_ymd_opt(1970, 1, 1)
.ok_or_else(|| datetime_to_period_error("invalid epoch boundary"))?;
Ok(date.signed_duration_since(epoch).num_days())
}
PeriodFreq::Hourly => Ok(nanos.div_euclid(Timedelta::NANOS_PER_HOUR)),
PeriodFreq::Minutely => Ok(nanos.div_euclid(Timedelta::NANOS_PER_MIN)),
PeriodFreq::Secondly => Ok(nanos.div_euclid(Timedelta::NANOS_PER_SEC)),
// MEASURED, live pandas 2.2.3: the ordinal is simply the unit count since
// the epoch, FLOORED -- Timestamp('1969-12-31 23:59:59.999').to_period('ms')
// has ordinal -1, and '...999000001' at 'ns' has -999999. div_euclid is
// that floor; plain `/` would truncate toward zero and be wrong pre-epoch.
PeriodFreq::Milliseconds => Ok(nanos.div_euclid(Timedelta::NANOS_PER_MILLI)),
PeriodFreq::Microseconds => Ok(nanos.div_euclid(Timedelta::NANOS_PER_MICRO)),
// Storage is already nanoseconds, so this is the identity.
PeriodFreq::Nanoseconds => Ok(nanos),
PeriodFreq::Weekly(_) => date_to_weekly_period_ordinal(date, freq),
PeriodFreq::Business => date_to_business_period_ordinal(date),
_ => Err(datetime_to_period_error("unsupported period frequency")),
}
}
fn datetime_period_ordinal_at_boundary(
nanos: i64,
freq: PeriodFreq,
boundary: PeriodBoundary,
) -> Result<i64, IndexError> {
if freq == PeriodFreq::Business && matches!(boundary, PeriodBoundary::End) {
let dt = datetime_from_nanos(nanos).ok_or_else(|| {
datetime_to_period_error(format!("invalid or NaT datetime nanos {nanos}"))
})?;
return date_to_business_period_ordinal(business_period_end_anchor_date(dt.date_naive())?);
}
datetime_period_ordinal(nanos, freq)
}
/// The period of `freq` holding the wall-clock instant `nanos`, as pandas'
/// `Timestamp.to_period(freq)` (a NaT or out-of-range instant is an error).
pub fn datetime_nanos_to_period(nanos: i64, freq: PeriodFreq) -> Result<Period, IndexError> {
datetime_period_ordinal(nanos, freq).map(|ordinal| Period::new(ordinal, freq))
}
fn map_datetime_labels<T, F>(labels: &[IndexLabel], func: F) -> Vec<Option<T>>
where
F: Fn(chrono::DateTime<chrono::Utc>) -> T,
{
labels
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) => datetime_from_nanos(*nanos).map(&func),
IndexLabel::Int64(_)
| IndexLabel::Float64(_)
| IndexLabel::Bool(_)
| IndexLabel::Utf8(_)
| IndexLabel::Timedelta64(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_) => None,
})
.collect()
}
fn time_to_nanos(time: chrono::NaiveTime) -> i64 {
use chrono::Timelike;
i64::from(time.num_seconds_from_midnight()) * 1_000_000_000 + i64::from(time.nanosecond())
}
fn parse_time_of_day_nanos(time: &str, context: &str) -> Result<i64, IndexError> {
let trimmed = time.trim();
for format in ["%H:%M:%S%.f", "%H:%M:%S", "%H:%M"] {
if let Ok(parsed) = chrono::NaiveTime::parse_from_str(trimmed, format) {
return Ok(time_to_nanos(parsed));
}
}
Err(IndexError::InvalidArgument(format!(
"{context}: invalid time {time:?}; expected HH:MM, HH:MM:SS, or fractional seconds"
)))
}
fn datetime_label_time_nanos(label: &IndexLabel) -> Option<i64> {
match label {
IndexLabel::Datetime64(nanos) => {
datetime_from_nanos(*nanos).map(|dt| time_to_nanos(dt.time()))
}
IndexLabel::Int64(_)
| IndexLabel::Float64(_)
| IndexLabel::Bool(_)
| IndexLabel::Utf8(_)
| IndexLabel::Timedelta64(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_) => None,
}
}
fn time_nanos_in_between(
time: i64,
start: i64,
end: i64,
include_start: bool,
include_end: bool,
) -> bool {
let after_start = if include_start {
time >= start
} else {
time > start
};
let before_end = if include_end { time <= end } else { time < end };
if start <= end {
after_start && before_end
} else {
after_start || before_end
}
}
fn map_timedelta_labels<T, F>(labels: &[IndexLabel], func: F) -> Vec<Option<T>>
where
F: Fn(i64) -> T,
{
labels
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(nanos) if *nanos != Timedelta::NAT => Some(func(*nanos)),
IndexLabel::Int64(_)
| IndexLabel::Float64(_)
| IndexLabel::Bool(_)
| IndexLabel::Utf8(_)
| IndexLabel::Timedelta64(_)
| IndexLabel::Datetime64(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_) => None,
})
.collect()
}
fn timedelta_components_for_index(nanos: i64) -> TimedeltaComponents {
let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
let hours = rem / Timedelta::NANOS_PER_HOUR;
let rem = rem % Timedelta::NANOS_PER_HOUR;
let minutes = rem / Timedelta::NANOS_PER_MIN;
let rem = rem % Timedelta::NANOS_PER_MIN;
let seconds = rem / Timedelta::NANOS_PER_SEC;
let rem = rem % Timedelta::NANOS_PER_SEC;
let milliseconds = rem / Timedelta::NANOS_PER_MILLI;
let rem = rem % Timedelta::NANOS_PER_MILLI;
let microseconds = rem / Timedelta::NANOS_PER_MICRO;
let nanoseconds = rem % Timedelta::NANOS_PER_MICRO;
TimedeltaComponents {
days,
hours,
minutes,
seconds,
milliseconds,
microseconds,
nanoseconds,
}
}
#[derive(Clone, Copy)]
enum TemporalRoundMode {
Floor,
Ceil,
Round,
}
#[derive(Clone, Copy)]
enum PeriodBoundary {
Start,
End,
}
fn parse_fixed_temporal_freq(freq: &str, context: &str) -> Result<i64, IndexError> {
let trimmed = freq.trim();
let unit_nanos = Timedelta::unit_to_nanos(trimmed)
.or_else(|| Timedelta::parse(trimmed).ok())
.ok_or_else(|| {
IndexError::InvalidArgument(format!("{context}: invalid frequency {freq:?}"))
})?;
if unit_nanos <= 0 {
return Err(IndexError::InvalidArgument(format!(
"{context}: frequency must be positive, got {freq:?}"
)));
}
Ok(unit_nanos)
}
fn round_nanos_to_unit(nanos: i64, unit_nanos: i64, mode: TemporalRoundMode) -> i64 {
match mode {
TemporalRoundMode::Floor => nanos.div_euclid(unit_nanos).saturating_mul(unit_nanos),
TemporalRoundMode::Ceil => {
let rem = nanos.rem_euclid(unit_nanos);
if rem == 0 {
nanos
} else {
nanos.saturating_add(unit_nanos - rem)
}
}
TemporalRoundMode::Round => {
let floor = nanos.div_euclid(unit_nanos);
let rem = nanos.rem_euclid(unit_nanos);
if rem == 0 {
return nanos;
}
let twice_rem = i128::from(rem) * 2;
let unit = i128::from(unit_nanos);
let chosen = if twice_rem < unit {
floor
} else if twice_rem > unit {
floor.saturating_add(1)
} else if floor % 2 == 0 {
floor
} else {
floor.saturating_add(1)
};
chosen.saturating_mul(unit_nanos)
}
}
}
fn positional_diff<T>(
len: usize,
periods: i64,
mut diff_at: impl FnMut(usize, usize) -> Option<T>,
) -> Vec<Option<T>> {
let mut out = (0..len).map(|_| None).collect::<Vec<_>>();
if periods == 0 {
for (position, slot) in out.iter_mut().enumerate() {
*slot = diff_at(position, position);
}
return out;
}
let Ok(offset) = usize::try_from(periods.unsigned_abs()) else {
return out;
};
if offset >= len {
return out;
}
if periods > 0 {
for (position, slot) in out.iter_mut().enumerate().skip(offset) {
*slot = diff_at(position, position - offset);
}
} else {
for (position, slot) in out.iter_mut().enumerate().take(len - offset) {
*slot = diff_at(position, position + offset);
}
}
out
}
fn optional_diffs_to_timedelta_index(
values: Vec<Option<i64>>,
name: Option<&LabelName>,
) -> TimedeltaIndex {
let mut out = TimedeltaIndex::new(
values
.into_iter()
.map(|value| value.unwrap_or(Timedelta::NAT))
.collect(),
);
if let Some(name) = name {
out = out.set_name(name);
}
out
}
fn period_timestamp_error(message: impl Into<String>) -> IndexError {
IndexError::InvalidArgument(format!(
"PeriodIndex timestamp conversion failed: {}",
message.into()
))
}
fn period_date_error(err: DateRangeError) -> IndexError {
period_timestamp_error(err.to_string())
}
fn period_date_to_nanos(date: chrono::NaiveDate) -> Result<i64, IndexError> {
date_to_midnight_nanos(date).map_err(period_date_error)
}
fn period_checked_add_nanos(nanos: i64, delta: i64) -> Result<i64, IndexError> {
nanos
.checked_add(delta)
.ok_or_else(|| period_timestamp_error("nanosecond timestamp overflow"))
}
fn period_month_start(month_ordinal: i64) -> Result<chrono::NaiveDate, IndexError> {
let year = 1970_i64
.checked_add(month_ordinal.div_euclid(12))
.ok_or_else(|| period_timestamp_error("year overflow"))?;
let year = i32::try_from(year).map_err(|_| period_timestamp_error("year out of range"))?;
let month = u32::try_from(month_ordinal.rem_euclid(12) + 1)
.map_err(|_| period_timestamp_error("month out of range"))?;
chrono::NaiveDate::from_ymd_opt(year, month, 1)
.ok_or_else(|| period_timestamp_error("invalid month boundary"))
}
fn period_epoch_date(year: i32, month: u32, day: u32) -> Result<chrono::NaiveDate, IndexError> {
chrono::NaiveDate::from_ymd_opt(year, month, day)
.ok_or_else(|| period_timestamp_error("invalid epoch boundary"))
}
fn period_add_days(date: chrono::NaiveDate, days: i64) -> Result<chrono::NaiveDate, IndexError> {
let delta = chrono::Duration::try_days(days)
.ok_or_else(|| period_timestamp_error("day offset overflow"))?;
date.checked_add_signed(delta)
.ok_or_else(|| period_timestamp_error("date overflow"))
}
fn period_business_date(ordinal: i64) -> Result<chrono::NaiveDate, IndexError> {
let week = ordinal.div_euclid(5);
let day_offset = match ordinal.rem_euclid(5) {
0 => 0,
1 => 1,
2 => 4,
3 => 5,
4 => 6,
_ => {
return Err(period_timestamp_error(
"business-day remainder out of range",
));
}
};
let calendar_days = week
.checked_mul(7)
.and_then(|days| days.checked_add(day_offset))
.ok_or_else(|| period_timestamp_error("business-day ordinal overflow"))?;
period_add_days(period_epoch_date(1970, 1, 1)?, calendar_days)
}
/// The instant (epoch nanoseconds) a period starts at, pandas'
/// `Period.start_time`: fp-frame reads a period label there where a
/// datetime label's own instant is read (45fzr). NaT and an ordinal past
/// the calendar are errors.
pub fn period_start_nanos(period: Period) -> Result<i64, IndexError> {
match period.freq {
// A fiscal year / quarter starts the shift's months before its
// calendar counterpart: Y-JUN 2024 (ordinal 54) starts 2023-07-01.
PeriodFreq::Annual(_) | PeriodFreq::Quarterly(_) => {
let months = if matches!(period.freq, PeriodFreq::Annual(_)) {
12
} else {
3
};
let month_ordinal = period
.ordinal
.checked_mul(months)
.and_then(|month| month.checked_sub(period.freq.fiscal_month_shift()))
.ok_or_else(|| period_timestamp_error("fiscal ordinal overflow"))?;
period_date_to_nanos(period_month_start(month_ordinal)?)
}
PeriodFreq::Monthly => period_date_to_nanos(period_month_start(period.ordinal)?),
PeriodFreq::Weekly(_) => {
let base = period_epoch_date(1969, 12, 22)?;
let days = period
.ordinal
.checked_mul(7)
.and_then(|days| days.checked_add(period.freq.week_start_shift()))
.ok_or_else(|| period_timestamp_error("weekly ordinal overflow"))?;
period_date_to_nanos(period_add_days(base, days)?)
}
PeriodFreq::Daily => {
let base = period_epoch_date(1970, 1, 1)?;
period_date_to_nanos(period_add_days(base, period.ordinal)?)
}
PeriodFreq::Business => period_date_to_nanos(period_business_date(period.ordinal)?),
PeriodFreq::Hourly => period
.ordinal
.checked_mul(Timedelta::NANOS_PER_HOUR)
.ok_or_else(|| period_timestamp_error("hourly ordinal overflow")),
PeriodFreq::Minutely => period
.ordinal
.checked_mul(Timedelta::NANOS_PER_MIN)
.ok_or_else(|| period_timestamp_error("minutely ordinal overflow")),
PeriodFreq::Secondly => period
.ordinal
.checked_mul(Timedelta::NANOS_PER_SEC)
.ok_or_else(|| period_timestamp_error("secondly ordinal overflow")),
PeriodFreq::Milliseconds => period
.ordinal
.checked_mul(Timedelta::NANOS_PER_MILLI)
.ok_or_else(|| period_timestamp_error("millisecond ordinal overflow")),
PeriodFreq::Microseconds => period
.ordinal
.checked_mul(Timedelta::NANOS_PER_MICRO)
.ok_or_else(|| period_timestamp_error("microsecond ordinal overflow")),
// Identity, and therefore the one arm that cannot overflow -- which also
// makes period_end_nanos (next_start - 1ns) collapse to the start, the
// correct end for a period one nanosecond wide.
PeriodFreq::Nanoseconds => Ok(period.ordinal),
_ => Err(period_timestamp_error("unsupported period frequency")),
}
}
fn period_next_start_nanos(period: Period) -> Result<i64, IndexError> {
let next = Period {
ordinal: period
.ordinal
.checked_add(1)
.ok_or_else(|| period_timestamp_error("period ordinal overflow"))?,
freq: period.freq,
};
period_start_nanos(next)
}
fn period_end_nanos(period: Period) -> Result<i64, IndexError> {
period_checked_add_nanos(period_next_start_nanos(period)?, -1)
}
fn period_boundary_nanos(period: Period, boundary: PeriodBoundary) -> Result<i64, IndexError> {
// A NaT period's boundary is NaT (pandas' start_time / end_time /
// to_timestamp of NaT; every field read through it raised).
if period.ordinal == i64::MIN {
return Ok(i64::MIN);
}
match boundary {
PeriodBoundary::Start => period_start_nanos(period),
PeriodBoundary::End => period_end_nanos(period),
}
}
fn parse_period_boundary_how(how: &str, context: &str) -> Result<PeriodBoundary, IndexError> {
match how.trim().to_ascii_lowercase().as_str() {
"" | "e" | "end" | "finish" => Ok(PeriodBoundary::End),
"s" | "start" | "begin" | "b" => Ok(PeriodBoundary::Start),
other => Err(IndexError::InvalidArgument(format!(
"{context} how must be 'start' or 'end', got {other:?}"
))),
}
}
fn period_qyear(period: Period) -> Result<i32, IndexError> {
// pandas' field of a NaT period is -1.
if period.ordinal == i64::MIN {
return Ok(-1);
}
// A quarter's qyear is the fiscal year its ordinal counts: Q-JAN's
// 2025Q1 ends 2024-04-30 and its qyear is 2025.
if matches!(period.freq, PeriodFreq::Quarterly(_)) {
return i32::try_from(1970 + period.ordinal.div_euclid(4))
.map_err(|_| period_timestamp_error("qyear out of range"));
}
let end_nanos = period_end_nanos(period)?;
datetime_nanos_to_date(end_nanos)
.map(|date| date.year())
.map_err(period_date_error)
}
#[derive(Debug, Clone, Copy)]
pub struct PeriodFields<'a> {
pub year: &'a [i32],
pub quarter: Option<&'a [u32]>,
pub month: Option<&'a [u32]>,
pub day: Option<&'a [u32]>,
pub hour: Option<&'a [u32]>,
pub minute: Option<&'a [u32]>,
pub second: Option<&'a [u32]>,
pub freq: Option<PeriodFreq>,
}
impl<'a> PeriodFields<'a> {
#[must_use]
pub const fn new(year: &'a [i32]) -> Self {
Self {
year,
quarter: None,
month: None,
day: None,
hour: None,
minute: None,
second: None,
freq: None,
}
}
}
fn period_fields_error(message: impl Into<String>) -> IndexError {
IndexError::InvalidArgument(format!(
"PeriodIndex.from_fields failed: {}",
message.into()
))
}
fn period_fields_freq(fields: &PeriodFields<'_>) -> Result<PeriodFreq, IndexError> {
let freq = fields
.freq
.or_else(|| fields.quarter.map(|_| PeriodFreq::QUARTERLY))
.ok_or_else(|| {
period_fields_error("freq is required unless quarter fields imply quarterly periods")
})?;
if fields.quarter.is_some() && !matches!(freq, PeriodFreq::Quarterly(_)) {
return Err(period_fields_error(
"quarter fields require quarterly frequency",
));
}
Ok(freq)
}
fn validate_period_field_len(
name: &str,
values: Option<&[u32]>,
expected: usize,
) -> Result<(), IndexError> {
if values.is_some_and(|items| items.len() != expected) {
return Err(period_fields_error(format!(
"Mismatched Period array lengths for {name}"
)));
}
Ok(())
}
fn validate_period_fields(fields: &PeriodFields<'_>) -> Result<(), IndexError> {
let expected = fields.year.len();
validate_period_field_len("quarter", fields.quarter, expected)?;
validate_period_field_len("month", fields.month, expected)?;
validate_period_field_len("day", fields.day, expected)?;
validate_period_field_len("hour", fields.hour, expected)?;
validate_period_field_len("minute", fields.minute, expected)?;
validate_period_field_len("second", fields.second, expected)
}
fn period_field_value(values: Option<&[u32]>, position: usize, default: u32) -> u32 {
values
.and_then(|items| items.get(position).copied())
.unwrap_or(default)
}
fn required_period_field(
values: Option<&[u32]>,
name: &str,
position: usize,
) -> Result<u32, IndexError> {
values
.and_then(|items| items.get(position).copied())
.ok_or_else(|| period_fields_error(format!("{name} fields are required")))
}
/// The period a fiscal `year` and `quarter` name under `freq` (pandas'
/// quarter_to_myear): the ordinal counts fiscal quarters, so Q-JAN's 2024
/// quarter 1 is 2024Q1 whatever calendar months it spans (2023-02..04).
fn fiscal_quarter_period(year: i32, quarter: u32, freq: PeriodFreq) -> Result<Period, IndexError> {
if !(1..=4).contains(&quarter) {
return Err(period_fields_error(format!(
"quarter must be in 1..=4, got {quarter}"
)));
}
let ordinal = (i64::from(year) - 1970) * 4 + i64::from(quarter) - 1;
Ok(Period::new(ordinal, freq))
}
fn period_from_fields_at(
fields: &PeriodFields<'_>,
freq: PeriodFreq,
position: usize,
) -> Result<Period, IndexError> {
let year = fields
.year
.get(position)
.copied()
.ok_or_else(|| period_fields_error("year fields are required"))?;
let month = if matches!(freq, PeriodFreq::Quarterly(_)) {
if let Some(quarters) = fields.quarter {
let quarter = quarters
.get(position)
.copied()
.ok_or_else(|| period_fields_error("quarter fields are required"))?;
return fiscal_quarter_period(year, quarter, freq);
} else {
required_period_field(fields.month, "month", position)?
}
} else {
if fields.quarter.is_some() && fields.month.is_none() {
return Err(period_fields_error(
"quarter fields require quarterly frequency unless month is also supplied",
));
}
required_period_field(fields.month, "month", position)?
};
let day = if matches!(
freq,
PeriodFreq::Annual(_) | PeriodFreq::Quarterly(_) | PeriodFreq::Monthly
) {
1
} else {
period_field_value(fields.day, position, 1)
};
let hour = if matches!(
freq,
PeriodFreq::Hourly
| PeriodFreq::Minutely
| PeriodFreq::Secondly
| PeriodFreq::Milliseconds
| PeriodFreq::Microseconds
| PeriodFreq::Nanoseconds
) {
period_field_value(fields.hour, position, 0)
} else {
0
};
let minute = if matches!(
freq,
PeriodFreq::Minutely
| PeriodFreq::Secondly
| PeriodFreq::Milliseconds
| PeriodFreq::Microseconds
| PeriodFreq::Nanoseconds
) {
period_field_value(fields.minute, position, 0)
} else {
0
};
let second = if matches!(
freq,
PeriodFreq::Secondly
| PeriodFreq::Milliseconds
| PeriodFreq::Microseconds
| PeriodFreq::Nanoseconds
) {
period_field_value(fields.second, position, 0)
} else {
0
};
let date = chrono::NaiveDate::from_ymd_opt(year, month, day)
.ok_or_else(|| period_fields_error("invalid year/month/day combination"))?;
let time = chrono::NaiveTime::from_hms_opt(hour, minute, second)
.ok_or_else(|| period_fields_error("invalid hour/minute/second combination"))?;
let nanos = date_and_time_to_nanos(date, time_to_nanos(time)).map_err(period_date_error)?;
datetime_period_ordinal(nanos, freq).map(|ordinal| Period::new(ordinal, freq))
}
fn ensure_index_kind(index: &Index, kinds: LabelKinds, kind: &str) -> Result<(), IndexError> {
if index.label_kinds().within(kinds) {
Ok(())
} else {
Err(IndexError::InvalidArgument(format!(
"{kind} requires homogeneous {kind} labels"
)))
}
}
const FREQ_MONTH_CODES: [&str; 12] = [
"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
];
const FREQ_WEEKDAY_CODES: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
/// A freqstr from a count and a rule code, as pandas writes it: the count
/// only when it is not 1 ('D', '2D', '-1D').
fn freq_with_count(n: i64, rule: &str) -> String {
if n == 1 {
rule.to_owned()
} else {
format!("{n}{rule}")
}
}
/// A freqstr's count and rule code ('2D' -> (2, "D"), '-1D' -> (-1, "D"),
/// 'W-SUN' -> (1, "W-SUN")).
#[must_use]
pub fn split_freq_count(freqstr: &str) -> Option<(i64, &str)> {
let body = freqstr
.char_indices()
.find(|&(i, c)| !(c.is_ascii_digit() || (i == 0 && matches!(c, '-' | '+'))))
.map_or(freqstr.len(), |(i, _)| i);
let (count, rule) = freqstr.split_at(body);
let n = match count {
"" | "+" => 1,
"-" => -1,
digits => digits.parse().ok()?,
};
(!rule.is_empty()).then_some((n, rule))
}
/// pandas' freqstr for a frequency alias - what `date_range(freq=alias)
/// .freqstr` reports ('W' -> 'W-SUN', '12H' -> '12h', 'M' -> 'ME', 'Q' ->
/// 'QE-DEC', 'T' -> 'min', '1D' -> 'D') - or None for an alias this does
/// not know.
#[must_use]
pub fn canonical_freq(alias: &str) -> Option<String> {
let (n, rule) = split_freq_count(alias.trim())?;
let (base, suffix) = match rule.split_once('-') {
Some((base, suffix)) => (base, Some(suffix.to_ascii_uppercase())),
None => (rule, None),
};
let month = |default: &str| -> Option<String> {
let code = suffix.clone().unwrap_or_else(|| default.to_owned());
FREQ_MONTH_CODES.contains(&code.as_str()).then_some(code)
};
let semimonth_day = || -> Option<i64> {
let day = suffix
.as_deref()
.map_or(Some(15), |text| text.parse().ok())?;
(2..=27).contains(&day).then_some(day)
};
let plain = |code: &str| suffix.is_none().then(|| code.to_owned());
let canonical = match base {
"D" | "d" => plain("D")?,
"h" | "H" => plain("h")?,
"min" | "T" => plain("min")?,
"s" | "S" => plain("s")?,
"ms" | "L" => plain("ms")?,
"us" | "U" => plain("us")?,
"ns" | "N" => plain("ns")?,
"B" => plain("B")?,
"M" | "ME" => plain("ME")?,
"MS" => plain("MS")?,
"BM" | "BME" => plain("BME")?,
"BMS" => plain("BMS")?,
"W" => {
let day = suffix.clone().unwrap_or_else(|| "SUN".to_owned());
if !FREQ_WEEKDAY_CODES.contains(&day.as_str()) {
return None;
}
format!("W-{day}")
}
"SM" | "SME" => format!("SME-{}", semimonth_day()?),
"SMS" => format!("SMS-{}", semimonth_day()?),
"Q" | "QE" => format!("QE-{}", month("DEC")?),
"QS" => format!("QS-{}", month("JAN")?),
"Y" | "A" | "YE" => format!("YE-{}", month("DEC")?),
"YS" | "AS" => format!("YS-{}", month("JAN")?),
_ => return None,
};
Some(freq_with_count(n, &canonical))
}
/// A freqstr with its count multiplied by `factor` - the freq of a slice
/// with that step ('D' x 2 -> '2D', 'D' x -1 -> '-1D'); None for a zero
/// factor.
#[must_use]
pub fn scale_freq(freqstr: &str, factor: i64) -> Option<String> {
if factor == 0 {
return None;
}
let (n, rule) = split_freq_count(freqstr)?;
Some(freq_with_count(n.checked_mul(factor)?, rule))
}
/// pandas' tick units, coarsest first: the rule code, its length in
/// nanoseconds and the resolution a tick's Timedelta holds it at (seconds
/// for a day down to a second).
const TICK_UNITS: [(&str, i64, i64); 7] = [
("D", 86_400_000_000_000, 1_000_000_000),
("h", 3_600_000_000_000, 1_000_000_000),
("min", 60_000_000_000, 1_000_000_000),
("s", 1_000_000_000, 1_000_000_000),
("ms", 1_000_000, 1_000_000),
("us", 1_000, 1_000),
("ns", 1, 1),
];
/// A tick freqstr's count and unit (its place in [`TICK_UNITS`]).
fn tick_count(freqstr: &str) -> Option<(i64, usize)> {
let (n, rule) = split_freq_count(freqstr)?;
let unit = TICK_UNITS.iter().position(|(code, _, _)| *code == rule)?;
Some((n, unit))
}
/// The tick freqstr of a duration, pandas' `delta_to_tick`: whole days in
/// days, other whole seconds in hours, minutes or seconds, else in milli-,
/// micro- or nanoseconds ('0D' for none).
fn duration_tick(nanos: i64) -> String {
const SECOND: i64 = 1_000_000_000;
let (n, rule) = if nanos % SECOND == 0 {
let seconds = nanos / SECOND;
if seconds % 86_400 == 0 {
(seconds / 86_400, "D")
} else if seconds % 3_600 == 0 {
(seconds / 3_600, "h")
} else if seconds % 60 == 0 {
(seconds / 60, "min")
} else {
(seconds, "s")
}
} else if nanos % 1_000_000 == 0 {
(nanos / 1_000_000, "ms")
} else if nanos % 1_000 == 0 {
(nanos / 1_000, "us")
} else {
(nanos, "ns")
};
freq_with_count(n, rule)
}
/// The freq of a TimedeltaIndex multiplied by a float, pandas' `Tick *
/// factor`: the same unit when the product is whole (truncated), else the
/// next finer unit's count times it ('D' x 1.5 -> '36h'). None for a freq
/// that is not a tick or a product that is zero or not finite (pandas
/// drops that freq); Err past nanoseconds, pandas' ValueError.
pub fn multiply_tick_freq(freqstr: &str, factor: f64) -> Result<Option<String>, String> {
let Some((mut n, mut unit)) = tick_count(freqstr) else {
return Ok(None);
};
loop {
let product = factor * n as f64;
if !product.is_finite() {
return Ok(None);
}
// pandas: np.isclose(n % 1, 0), then int(n).
if product.rem_euclid(1.0) <= 1e-8 {
let count = product.trunc() as i64;
return Ok((count != 0).then(|| freq_with_count(count, TICK_UNITS[unit].0)));
}
let Some(&(_, finer, _)) = TICK_UNITS.get(unit + 1) else {
return Err("Could not convert to integer offset at any resolution".to_owned());
};
n = n
.checked_mul(TICK_UNITS[unit].1 / finer)
.ok_or_else(|| "Could not convert to integer offset at any resolution".to_owned())?;
unit += 1;
}
}
/// The freq of a TimedeltaIndex divided by a number, pandas' `Tick /
/// divisor`: the tick's Timedelta at its own resolution divided and
/// truncated there, as a tick again ('D' / 7 -> '12342s', 'D' / 2 ->
/// '12h'). None for a freq that is not a tick, a quotient that is not
/// finite, or one that truncates a nonzero freq to nothing (pandas drops
/// that freq).
#[must_use]
pub fn divide_tick_freq(freqstr: &str, divisor: f64) -> Option<String> {
let (n, unit) = tick_count(freqstr)?;
let (_, length, resolution) = TICK_UNITS[unit];
let held = n.checked_mul(length / resolution)?;
let quotient = held as f64 / divisor;
if !quotient.is_finite() {
return None;
}
let nanos = (quotient.trunc() as i64).checked_mul(resolution)?;
(nanos != 0 || n == 0).then(|| duration_tick(nanos))
}
/// The freq a `take` of `positions` keeps: pandas reads positions in one
/// constant nonzero step as a slice (`maybe_indices_to_slice`), so the freq
/// scales by the step ([0, 2] of 'h' is '2h'); any other take has none.
/// pandas' take-based selections (iloc / take with positions, between_time,
/// at_time) keep it so; its getitem with positions (Series.sort_values, loc)
/// does not.
#[must_use]
pub fn take_freq(freq: Option<String>, positions: &[usize]) -> Option<String> {
let freq = freq?;
let step = match positions {
// No positions is an empty slice to pandas (`s.iloc[[]]` keeps 'D';
// br-frankenpandas-0l1nu).
[] => return Some(freq),
[_] => 1,
[first, second, ..] => i64::try_from(*second).ok()? - i64::try_from(*first).ok()?,
};
let steady = positions.windows(2).all(|pair| {
i64::try_from(pair[1])
.ok()
.zip(i64::try_from(pair[0]).ok())
.is_some_and(|(next, current)| next - current == step)
});
if step == 0 || !steady {
return None;
}
scale_freq(&freq, step)
}
/// pandas' month-position check: whether every date is a calendar ('ce') or
/// business ('be') month end, a calendar ('cs') or business ('bs') month
/// start, in that order of preference.
fn freq_month_position(stamps: &[Timestamp]) -> Option<&'static str> {
let (mut calendar_end, mut business_end) = (true, true);
let (mut calendar_start, mut business_start) = (true, true);
for stamp in stamps {
let day = stamp.day()?;
let weekday = stamp.dayofweek()?;
let month_days = stamp.days_in_month()?;
calendar_start &= day == 1;
business_start &= day == 1 || (day <= 3 && weekday == 0);
let at_end = day == month_days;
calendar_end &= at_end;
business_end &= at_end || (month_days - day < 3 && weekday == 4);
}
if calendar_end {
Some("ce")
} else if business_end {
Some("be")
} else if calendar_start {
Some("cs")
} else if business_start {
Some("bs")
} else {
None
}
}
/// The sorted distinct consecutive differences of `values`.
fn freq_unique_deltas(values: &[i64]) -> Vec<i64> {
let mut deltas: Vec<i64> = values.windows(2).map(|pair| pair[1] - pair[0]).collect();
deltas.sort_unstable();
deltas.dedup();
deltas
}
/// pandas' frequency inference (`inferred_freq`): `wall` is each label's
/// wall clock (a calendar rule reads it) and `instants` the UTC instants (a
/// sub-day step reads them, as a DST change moves the wall clock). Needs
/// three or more strictly monotonic labels. A day multiple tries the annual,
/// quarterly and monthly rules (the dates' month position: YS / YE / QS /
/// QE / MS / ME and their business forms), then 'D' or `W-<day>` for a
/// single step, then business days ('B'); a sub-day step is its tick
/// ('h', 'min', 's', 'ms', 'us', 'ns') with a count. None otherwise.
#[must_use]
pub fn infer_datetime_freq(wall: &[i64], instants: &[i64]) -> Option<String> {
const DAY: i64 = 86_400_000_000_000;
if wall.len() < 3 || wall.len() != instants.len() {
return None;
}
let increasing = wall.windows(2).all(|pair| pair[1] > pair[0]);
let decreasing = wall.windows(2).all(|pair| pair[1] < pair[0]);
if !(increasing || decreasing) {
return None;
}
let deltas = freq_unique_deltas(wall);
if deltas[0] % DAY == 0 {
let stamps: Vec<Timestamp> = wall
.iter()
.map(|&nanos| Timestamp::from_nanos(nanos))
.collect();
let years: Vec<i64> = stamps.iter().map(Timestamp::year).collect::<Option<_>>()?;
let months: Vec<i64> = stamps.iter().map(Timestamp::month).collect::<Option<_>>()?;
let month_ordinals: Vec<i64> = years
.iter()
.zip(&months)
.map(|(year, month)| year * 12 + month)
.collect();
let ydiffs = freq_unique_deltas(&years);
let mdiffs = freq_unique_deltas(&month_ordinals);
let position = freq_month_position(&stamps);
let first_month = usize::try_from(months[0] - 1).ok()?;
if ydiffs.len() == 1 && months.iter().all(|&month| month == months[0]) {
let rule = match position {
Some("cs") => Some("YS"),
Some("bs") => Some("BYS"),
Some("ce") => Some("YE"),
Some("be") => Some("BYE"),
_ => None,
};
if let Some(rule) = rule {
let code = FREQ_MONTH_CODES.get(first_month)?;
return Some(freq_with_count(ydiffs[0], &format!("{rule}-{code}")));
}
}
if mdiffs.len() == 1 && mdiffs[0] % 3 == 0 {
let rule = match position {
Some("cs") => Some("QS"),
Some("bs") => Some("BQS"),
Some("ce") => Some("QE"),
Some("be") => Some("BQE"),
_ => None,
};
if let Some(rule) = rule {
// pandas names the quarter by (month % 3): 0 -> DEC, 2 -> NOV,
// 1 -> OCT (so a January-April-July run is 'QS-OCT').
let code = match months[0] % 3 {
0 => "DEC",
2 => "NOV",
_ => "OCT",
};
return Some(freq_with_count(mdiffs[0] / 3, &format!("{rule}-{code}")));
}
}
if mdiffs.len() == 1 {
let rule = match position {
Some("cs") => Some("MS"),
Some("bs") => Some("BMS"),
Some("ce") => Some("ME"),
Some("be") => Some("BME"),
_ => None,
};
if let Some(rule) = rule {
return Some(freq_with_count(mdiffs[0], rule));
}
}
if deltas.len() == 1 {
let days = deltas[0] / DAY;
if days % 7 == 0 {
let weekday = usize::try_from(stamps[0].dayofweek()?).ok()?;
let code = FREQ_WEEKDAY_CODES.get(weekday)?;
return Some(freq_with_count(days / 7, &format!("W-{code}")));
}
return Some(freq_with_count(days, "D"));
}
// Business days: one-day steps, and three-day ones only from a
// Friday to a Monday.
if deltas == [DAY, 3 * DAY] {
let mut weekday = stamps[0].dayofweek()?;
let business = wall.windows(2).all(|pair| {
let shift = (pair[1] - pair[0]) / DAY;
weekday = (weekday + shift).rem_euclid(7);
(weekday == 0 && shift == 3) || ((1..=4).contains(&weekday) && shift == 1)
});
if business {
return Some("B".to_owned());
}
}
return None;
}
let steps = freq_unique_deltas(instants);
let [step] = steps.as_slice() else {
return None;
};
[
(3_600_000_000_000, "h"),
(60_000_000_000, "min"),
(1_000_000_000, "s"),
(1_000_000, "ms"),
(1_000, "us"),
(1, "ns"),
]
.into_iter()
.find(|(unit, _)| step % unit == 0)
.map(|(unit, rule)| freq_with_count(step / unit, rule))
}
/// Public pandas-style datetime index wrapper.
///
/// The canonical storage remains [`Index`] with `Datetime64` labels so existing
/// DataFrame/Series alignment code keeps one representation. This wrapper adds
/// the type-level public surface pandas users expect (`DatetimeIndex`) and a
/// small first slice of datetime accessors.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatetimeIndex {
index: Index,
}
impl DatetimeIndex {
#[must_use]
pub fn new(nanos: Vec<i64>) -> Self {
Self {
index: Index::from_datetime64(nanos),
}
}
pub fn from_index(index: Index) -> Result<Self, IndexError> {
if index.labels.datetime64_affine_range().is_none() {
ensure_index_kind(&index, LabelKinds::DATETIME64, "DatetimeIndex")?;
}
Ok(Self { index })
}
#[must_use]
pub fn as_index(&self) -> &Index {
&self.index
}
#[must_use]
pub fn into_index(self) -> Index {
self.index
}
#[must_use]
pub fn len(&self) -> usize {
self.index.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.index.is_empty()
}
#[must_use]
pub fn name(&self) -> Option<&LabelName> {
self.index.name()
}
#[must_use]
pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
Self {
index: self.index.set_name(name),
}
}
#[must_use]
pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
Self {
index: self.index.set_names(name),
}
}
#[must_use]
pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
self.set_names(name)
}
#[must_use]
pub fn names(&self) -> Vec<Option<String>> {
self.index.names()
}
#[must_use]
pub fn copy(&self) -> Self {
self.clone()
}
#[must_use]
pub fn shape(&self) -> (usize,) {
self.index.shape()
}
#[must_use]
pub fn size(&self) -> usize {
self.index.size()
}
#[must_use]
pub fn empty(&self) -> bool {
self.index.empty()
}
#[must_use]
pub fn dtype(&self) -> &'static str {
"datetime64[ns]"
}
#[must_use]
pub fn dtypes(&self) -> Vec<&'static str> {
vec![self.dtype()]
}
#[must_use]
pub fn memory_usage(&self, deep: bool) -> usize {
self.index.memory_usage(deep)
}
#[must_use]
pub fn nbytes(&self) -> usize {
self.index.nbytes()
}
#[must_use]
pub fn hasnans(&self) -> bool {
self.index.hasnans()
}
#[must_use]
pub fn isna(&self) -> Vec<bool> {
self.index.isna()
}
#[must_use]
pub fn notna(&self) -> Vec<bool> {
self.index.notna()
}
#[must_use]
pub fn is_unique(&self) -> bool {
self.index.is_unique()
}
#[must_use]
pub fn has_duplicates(&self) -> bool {
self.index.has_duplicates()
}
#[must_use]
pub fn is_monotonic_increasing(&self) -> bool {
self.index.is_monotonic_increasing()
}
#[must_use]
pub fn is_monotonic(&self) -> bool {
self.index.is_monotonic()
}
#[must_use]
pub fn is_monotonic_decreasing(&self) -> bool {
self.index.is_monotonic_decreasing()
}
#[must_use]
pub fn nunique(&self) -> usize {
self.index.nunique()
}
#[must_use]
pub fn nunique_with_dropna(&self, dropna: bool) -> usize {
self.index.nunique_with_dropna(dropna)
}
#[must_use]
pub fn ndim(&self) -> usize {
self.index.ndim()
}
pub fn item(&self) -> Result<Option<i64>, IndexError> {
match self.index.item()? {
IndexLabel::Datetime64(nanos) if nanos != i64::MIN => Ok(Some(nanos)),
IndexLabel::Datetime64(_) => Ok(None),
label => Err(IndexError::InvalidArgument(format!(
"DatetimeIndex item must be datetime64, got {label}"
))),
}
}
#[must_use]
pub fn is_(&self, other: &Self) -> bool {
std::ptr::eq(self, other)
}
#[must_use]
pub fn equals(&self, other: &Self) -> bool {
self.index.equals(&other.index)
}
#[must_use]
pub fn identical(&self, other: &Self) -> bool {
self.index.identical(&other.index)
}
#[must_use]
pub fn holds_integer(&self) -> bool {
false
}
#[must_use]
pub fn inferred_type(&self) -> &'static str {
"datetime64"
}
#[must_use]
pub fn is_boolean(&self) -> bool {
false
}
#[must_use]
pub fn is_categorical(&self) -> bool {
false
}
#[must_use]
pub fn is_floating(&self) -> bool {
false
}
#[must_use]
pub fn is_integer(&self) -> bool {
false
}
#[must_use]
pub fn is_interval(&self) -> bool {
false
}
#[must_use]
pub fn is_numeric(&self) -> bool {
false
}
#[must_use]
pub fn is_object(&self) -> bool {
false
}
#[must_use]
pub fn nanos(&self) -> Vec<Option<i64>> {
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => Some(*nanos),
IndexLabel::Int64(_)
| IndexLabel::Float64(_)
| IndexLabel::Bool(_)
| IndexLabel::Utf8(_)
| IndexLabel::Timedelta64(_)
| IndexLabel::Datetime64(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_) => None,
})
.collect()
}
#[must_use]
pub fn values(&self) -> Vec<Option<i64>> {
self.nanos()
}
#[must_use]
pub fn to_list(&self) -> Vec<Option<i64>> {
self.nanos()
}
#[must_use]
pub fn tolist(&self) -> Vec<Option<i64>> {
self.to_list()
}
#[must_use]
pub fn to_numpy(&self) -> Vec<Option<i64>> {
self.nanos()
}
#[must_use]
pub fn array(&self) -> Vec<Option<i64>> {
self.nanos()
}
/// Underlying nanoseconds-since-epoch, matching `pd.DatetimeIndex.asi8`.
/// NAT is preserved as `i64::MIN` to match the on-disk sentinel.
#[must_use]
pub fn asi8(&self) -> Vec<i64> {
// A date_range's lazy range, its labels not made (br-frankenpandas-so0mr).
if let Some(range) = self.index.labels.datetime64_affine_range() {
return range.materialize_i64();
}
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) => *nanos,
IndexLabel::Int64(_)
| IndexLabel::Float64(_)
| IndexLabel::Bool(_)
| IndexLabel::Utf8(_)
| IndexLabel::Timedelta64(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_) => i64::MIN,
})
.collect()
}
/// The one element of [`Self::asi8`] at `pos` (`None` past the end),
/// without building the rest: reading element by element through `asi8()`
/// made iterating a DatetimeIndex quadratic (br-frankenpandas-tumiz).
#[must_use]
pub fn asi8_at(&self, pos: usize) -> Option<i64> {
if pos >= self.index.len() {
return None;
}
if let Some(range) = self.index.labels.datetime64_affine_range() {
return Some(range.value_at(pos));
}
Some(match self.index.labels().get(pos)? {
IndexLabel::Datetime64(nanos) => *nanos,
_ => i64::MIN,
})
}
/// Convert datetime labels to period ordinals at the requested frequency,
/// matching `pd.DatetimeIndex.to_period(freq)` for supported fixed
/// calendar frequencies.
pub fn to_period(&self, freq: &str) -> Result<PeriodIndex, IndexError> {
let period_freq = PeriodFreq::parse(freq).ok_or_else(|| {
IndexError::InvalidArgument(format!("to_period: unsupported frequency '{freq}'"))
})?;
let periods = self
.wall_labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) => datetime_nanos_to_period(*nanos, period_freq),
other => Err(IndexError::InvalidArgument(format!(
"to_period requires DatetimeIndex labels, got {other:?}"
))),
})
.collect::<Result<Vec<_>, _>>()?;
let mut out = PeriodIndex::new(periods);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
/// Format each timestamp as Python's strftime does, matching
/// `pd.DatetimeIndex.strftime(format)` (see [`fp_types::strftime_python`];
/// chrono's formatter printed `%f` with nine digits and panicked on an
/// unknown directive). A tz-aware instant formats its wall clock, `%z` /
/// `%Z` its zone's offset and abbreviation then. NAT propagates as `None`.
#[must_use]
pub fn strftime(&self, format: &str) -> Vec<Option<String>> {
let zone = self.index.tz();
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => {
Some(fp_types::strftime_in_zone(*nanos, format, zone))
}
_ => None,
})
.collect()
}
/// Position of the maximum label, matching `pd.DatetimeIndex.argmax()`.
/// Pandas returns the *first* tied position and skips NAT entries; this
/// method walks the labels itself to match that ordering exactly. Empty
/// indexes (or all-NAT indexes) raise pandas-style `ValueError` mirrored
/// as [`IndexError::InvalidArgument`].
pub fn argmax(&self) -> Result<usize, IndexError> {
let labels = self.index.labels();
let mut best: Option<usize> = None;
for (i, label) in labels.iter().enumerate() {
let nanos = match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => *n,
_ => continue,
};
best = Some(match best {
Some(b) => match labels[b] {
IndexLabel::Datetime64(prev) if nanos > prev => i,
_ => b,
},
None => i,
});
}
best.ok_or_else(|| {
IndexError::InvalidArgument("attempt to get argmax of an empty sequence".to_owned())
})
}
/// Position of the minimum label, matching `pd.DatetimeIndex.argmin()`.
/// Returns the first-tied position and skips NAT to match pandas semantics.
pub fn argmin(&self) -> Result<usize, IndexError> {
let labels = self.index.labels();
let mut best: Option<usize> = None;
for (i, label) in labels.iter().enumerate() {
let nanos = match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => *n,
_ => continue,
};
best = Some(match best {
Some(b) => match labels[b] {
IndexLabel::Datetime64(prev) if nanos < prev => i,
_ => b,
},
None => i,
});
}
best.ok_or_else(|| {
IndexError::InvalidArgument("attempt to get argmin of an empty sequence".to_owned())
})
}
/// Positions that would sort the labels ascending, matching
/// `pd.DatetimeIndex.argsort()`.
#[must_use]
pub fn argsort(&self) -> Vec<usize> {
self.index.argsort()
}
/// First-seen unique labels, matching `pd.DatetimeIndex.unique()`.
/// Returns a new DatetimeIndex; one with no repeats is itself, freq kept.
pub fn unique(&self) -> Result<Self, IndexError> {
if !self.index.has_duplicates() {
return Ok(self.clone());
}
Self::from_index(self.index.unique())
}
/// Identity-stable factorization, matching `pd.DatetimeIndex.factorize()`.
/// Returns `(codes, uniques)` where `uniques` is rebuilt as DatetimeIndex.
pub fn factorize(&self) -> Result<(Vec<isize>, Self), IndexError> {
let (codes, uniques) = self.index.factorize();
Ok((codes, Self::from_index(uniques)?))
}
/// Value counts, matching `pd.DatetimeIndex.value_counts()`.
#[must_use]
pub fn value_counts(&self) -> Vec<(IndexLabel, usize)> {
self.index.value_counts()
}
/// Duplicate mask per position, matching `pd.DatetimeIndex.duplicated(keep)`.
#[must_use]
pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
self.index.duplicated(keep)
}
/// Drop duplicate labels, matching `pd.DatetimeIndex.drop_duplicates()`.
pub fn drop_duplicates(&self) -> Result<Self, IndexError> {
Self::from_index(self.index.drop_duplicates())
}
/// Pick labels at the given positions, matching `pd.DatetimeIndex.take()`.
/// Out-of-bounds positions raise [`IndexError::OutOfBounds`].
pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
let labels = self.index.labels();
for &p in positions {
if p >= labels.len() {
return Err(IndexError::OutOfBounds {
position: p,
length: labels.len(),
});
}
}
let nanos: Vec<i64> = positions
.iter()
.map(|&p| match labels[p] {
IndexLabel::Datetime64(n) => n,
_ => i64::MIN,
})
.collect();
let freq = take_freq(self.freq(), positions);
Ok(self.with_instants(nanos).with_freq(freq))
}
/// Repeat each label `repeats` times, matching `pd.DatetimeIndex.repeat()`.
#[must_use]
pub fn repeat(&self, repeats: usize) -> Self {
let mut out = Vec::with_capacity(repeat_output_capacity(self.len(), repeats));
for label in self.index.labels() {
if let IndexLabel::Datetime64(n) = label {
for _ in 0..repeats {
out.push(*n);
}
}
}
self.with_instants(out)
}
/// Per-position membership mask, matching `pd.DatetimeIndex.isin(values)`.
/// `values` is interpreted as a slice of nanoseconds-since-epoch; pass
/// `i64::MIN` to test for NAT.
#[must_use]
pub fn isin(&self, values: &[i64]) -> Vec<bool> {
let needle: FxHashSet<i64> = values.iter().copied().collect();
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(n) => needle.contains(n),
_ => false,
})
.collect()
}
/// Concatenate with another DatetimeIndex, matching
/// `pd.DatetimeIndex.append(other)`. The index name is preserved when
/// both operands share it; otherwise pandas drops the name.
#[must_use]
pub fn append(&self, other: &Self) -> Self {
let mut nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
})
.collect();
nanos.extend(other.index.labels().iter().filter_map(|label| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
}));
let mut out = Self::new(nanos);
if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
out = out.set_name(name);
}
// A zone only when both share it (pandas gives an object Index
// of the two zones' Timestamps otherwise).
if self.index.tz == other.index.tz {
out.index.tz.clone_from(&self.index.tz);
}
out
}
/// Minimum non-NAT label, matching `pd.DatetimeIndex.min()`.
/// Returns `None` for empty or all-NAT inputs to mirror pandas' NaT.
#[must_use]
pub fn min(&self) -> Option<i64> {
self.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n),
_ => None,
})
.min()
}
/// Shift each label by `periods` units of `freq_nanos`, matching
/// `pd.DatetimeIndex.shift(periods, freq)` once `freq` has been
/// resolved to a nanosecond duration. NAT propagates as NAT;
/// arithmetic overflow saturates.
#[must_use]
pub fn shift(&self, periods: i64, freq_nanos: i64) -> Self {
let delta = periods.saturating_mul(freq_nanos);
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => n.saturating_add(delta),
_ => i64::MIN,
})
.collect();
// Every label moves by the same span, so the freq holds (pandas).
self.with_instants(nanos).with_freq(self.freq())
}
/// Positional first differences, matching `pd.DatetimeIndex.diff()`.
/// Datetime deltas materialize as a TimedeltaIndex; NAT inputs propagate
/// to NAT outputs, and signed `periods` follows pandas' forward/backward
/// lookup direction.
#[must_use]
pub fn diff(&self, periods: i64) -> TimedeltaIndex {
let labels = self.index.labels();
optional_diffs_to_timedelta_index(
positional_diff(labels.len(), periods, |current, previous| {
match (&labels[current], &labels[previous]) {
(
IndexLabel::Datetime64(current_nanos),
IndexLabel::Datetime64(previous_nanos),
) if *current_nanos != i64::MIN && *previous_nanos != i64::MIN => {
current_nanos.checked_sub(*previous_nanos)
}
_ => None,
}
}),
self.name(),
)
}
/// Rounding reads the wall clock: a tz-aware index rounds its wall
/// times and places them back in its zone, as pandas.
fn round_fixed_freq(&self, freq: &str, mode: TemporalRoundMode) -> Result<Self, IndexError> {
let unit_nanos = parse_fixed_temporal_freq(freq, "DatetimeIndex rounding")?;
let nanos: Vec<i64> = self
.wall_labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => {
round_nanos_to_unit(*n, unit_nanos, mode)
}
_ => i64::MIN,
})
.collect();
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
self.rezoned(out)
}
/// Round timestamps down to a fixed pandas frequency.
pub fn floor(&self, freq: &str) -> Result<Self, IndexError> {
self.round_fixed_freq(freq, TemporalRoundMode::Floor)
}
/// Round timestamps up to a fixed pandas frequency.
pub fn ceil(&self, freq: &str) -> Result<Self, IndexError> {
self.round_fixed_freq(freq, TemporalRoundMode::Ceil)
}
/// Round timestamps to the nearest fixed pandas frequency, using half-even ties.
pub fn round(&self, freq: &str) -> Result<Self, IndexError> {
self.round_fixed_freq(freq, TemporalRoundMode::Round)
}
/// Validate the frequency and return a clone, matching pandas DatetimeIndex.snap.
pub fn snap(&self, freq: &str) -> Result<Self, IndexError> {
parse_fixed_temporal_freq(freq, "DatetimeIndex.snap")?;
Ok(self.clone())
}
/// Average non-NAT label as nanoseconds-since-epoch, matching
/// `pd.DatetimeIndex.mean()`. Empty / all-NAT returns `None`.
/// Sum is computed in `i128` to avoid overflow.
#[must_use]
pub fn mean(&self) -> Option<i64> {
let mut total: i128 = 0;
let mut count: i128 = 0;
for label in self.index.labels() {
if let IndexLabel::Datetime64(n) = label
&& *n != i64::MIN
{
total += i128::from(*n);
count += 1;
}
}
if count == 0 {
return None;
}
i64::try_from(total / count).ok()
}
/// Sample variance over non-NAT labels in nanoseconds-squared,
/// matching `pd.DatetimeIndex.var(ddof=1)`. Returns `None` for
/// fewer than two non-NAT entries.
#[must_use]
pub fn var(&self) -> Option<f64> {
let nanos: Vec<f64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n as f64),
_ => None,
})
.collect();
if nanos.len() < 2 {
return None;
}
let mean = nanos.iter().sum::<f64>() / nanos.len() as f64;
Some(nanos.iter().map(|n| (n - mean).powi(2)).sum::<f64>() / (nanos.len() as f64 - 1.0))
}
/// Sample standard deviation of non-NAT labels in nanoseconds,
/// matching `pd.DatetimeIndex.std(ddof=1)`. Returns `None` for
/// fewer than two non-NAT entries.
#[must_use]
pub fn std(&self) -> Option<i64> {
let nanos: Vec<f64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n as f64),
_ => None,
})
.collect();
if nanos.len() < 2 {
return None;
}
let mean = nanos.iter().sum::<f64>() / nanos.len() as f64;
let var =
nanos.iter().map(|n| (n - mean).powi(2)).sum::<f64>() / (nanos.len() as f64 - 1.0);
Some(var.sqrt() as i64)
}
/// Median non-NAT label. Empty returns None. For an even-length non-NAT
/// subset, returns the average of the two middle values.
///
/// ⚠️ `pd.DatetimeIndex.median()` does NOT exist (measured 2.2.3:
/// `AttributeError`). Its sibling `mean()` DOES -- do not infer one from
/// the other. FP superset; the pandas spelling is `idx.to_series().median()`.
#[must_use]
pub fn median(&self) -> Option<i64> {
let mut nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n),
_ => None,
})
.collect();
if nanos.is_empty() {
return None;
}
nanos.sort_unstable();
let mid = nanos.len() / 2;
if nanos.len() % 2 == 1 {
Some(nanos[mid])
} else {
let total = i128::from(nanos[mid - 1]) + i128::from(nanos[mid]);
i64::try_from(total / 2).ok()
}
}
/// Maximum non-NAT label, matching `pd.DatetimeIndex.max()`.
#[must_use]
pub fn max(&self) -> Option<i64> {
self.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => Some(*n),
_ => None,
})
.max()
}
/// Labels present in both indexes, matching
/// `pd.DatetimeIndex.intersection(other)`. Preserves first-seen order
/// from `self`.
#[must_use]
pub fn intersection(&self, other: &Self) -> Self {
let other_set: FxHashSet<i64> = other
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
})
.collect();
let mut seen = FxHashSet::<i64>::default();
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) if other_set.contains(n) && seen.insert(*n) => Some(*n),
_ => None,
})
.collect();
// pandas infers the freq of the shared labels.
let shared = self.with_joined_instants(other, nanos);
let freq = shared.inferred_freq();
shared.with_freq(freq)
}
/// `pd.DatetimeIndex.union(other)` (pandas' default `sort=None`); see
/// [`Self::union_sorted`].
#[must_use]
pub fn union(&self, other: &Self) -> Self {
self.union_sorted(other, None)
}
/// `pd.DatetimeIndex.union(other, sort=)`: the labels of both, each
/// once, sorted (pandas' default `sort=None` returns this index itself
/// when `other` is empty or equal, and `other` when this one is empty;
/// `sort=False` keeps first-seen order - it never sorted, so
/// `[03, 01] | [02]` came back `[03, 01, 02]`). The result carries its
/// inferred freq, as pandas'.
#[must_use]
pub fn union_sorted(&self, other: &Self, sort: Option<bool>) -> Self {
if sort.is_none() {
if other.is_empty() || self.index == other.index {
return self.clone();
}
if self.is_empty() {
return other.clone();
}
}
let mut seen = FxHashSet::<i64>::default();
let mut nanos: Vec<i64> = Vec::new();
for label in self
.index
.labels()
.iter()
.chain(other.index.labels().iter())
{
if let IndexLabel::Datetime64(n) = label
&& seen.insert(*n)
{
nanos.push(*n);
}
}
if sort != Some(false) {
nanos.sort_unstable();
}
let joined = self.with_joined_instants(other, nanos);
let freq = joined.inferred_freq();
joined.with_freq(freq)
}
/// Labels in self not in other, matching
/// `pd.DatetimeIndex.difference(other)`.
#[must_use]
pub fn difference(&self, other: &Self) -> Self {
let other_set: FxHashSet<i64> = other
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
})
.collect();
let mut seen = FxHashSet::<i64>::default();
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) if !other_set.contains(n) && seen.insert(*n) => Some(*n),
_ => None,
})
.collect();
// Per br-frankenpandas-6r1lq: difference is asymmetric — pandas
// always preserves self.name (unlike union/intersection which use
// shared_name).
let mut out = self.with_instants(nanos);
out.index.tz = joined_tz(&self.index, &other.index);
out
}
/// Labels in either but not both, matching
/// `pd.DatetimeIndex.symmetric_difference(other)`.
#[must_use]
pub fn symmetric_difference(&self, other: &Self) -> Self {
let self_set: FxHashSet<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
})
.collect();
let other_set: FxHashSet<i64> = other
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
})
.collect();
let mut seen = FxHashSet::<i64>::default();
let mut nanos: Vec<i64> = Vec::new();
for label in self.index.labels() {
if let IndexLabel::Datetime64(n) = label
&& !other_set.contains(n)
&& seen.insert(*n)
{
nanos.push(*n);
}
}
for label in other.index.labels() {
if let IndexLabel::Datetime64(n) = label
&& !self_set.contains(n)
&& seen.insert(*n)
{
nanos.push(*n);
}
}
self.with_joined_instants(other, nanos)
}
/// Sort labels ascending, matching `pd.DatetimeIndex.sort_values()`.
/// NAT sorts first because the underlying sentinel is `i64::MIN`,
/// matching pandas' `na_position='first'` default for datetime indexes.
#[must_use]
pub fn sort_values(&self) -> Self {
let mut nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
})
.collect();
nanos.sort_unstable();
self.with_instants(nanos)
}
/// Alias for `sort_values`, matching `pd.DatetimeIndex.sort()`.
#[must_use]
pub fn sort(&self) -> Self {
self.sort_values()
}
/// Remove the label at the given position, matching
/// `pd.DatetimeIndex.delete(loc)`.
pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
let labels = self.index.labels();
if loc >= labels.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: labels.len(),
});
}
let nanos: Vec<i64> = labels
.iter()
.enumerate()
.filter(|(i, _)| *i != loc)
.filter_map(|(_, label)| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
})
.collect();
Ok(self.with_instants(nanos))
}
/// Replace positions where `cond` is `false` with `other`, matching
/// `pd.DatetimeIndex.where(cond, other)`. Pass `i64::MIN` to insert
/// NAT.
pub fn r#where(&self, cond: &[bool], other: i64) -> Result<Self, IndexError> {
let labels = self.index.labels();
if cond.len() != labels.len() {
return Err(IndexError::LengthMismatch {
expected: labels.len(),
actual: cond.len(),
context: "where: cond length must match index length".to_owned(),
});
}
let nanos: Vec<i64> = labels
.iter()
.zip(cond.iter())
.map(|(label, &keep)| {
if keep {
match label {
IndexLabel::Datetime64(n) => *n,
_ => i64::MIN,
}
} else {
other
}
})
.collect();
Ok(self.with_instants(nanos))
}
/// Replace positions where `mask` is `true` with `value`, matching
/// `pd.DatetimeIndex.putmask(mask, value)`. The complement of `where`.
pub fn putmask(&self, mask: &[bool], value: i64) -> Result<Self, IndexError> {
let labels = self.index.labels();
if mask.len() != labels.len() {
return Err(IndexError::LengthMismatch {
expected: labels.len(),
actual: mask.len(),
context: "putmask: mask length must match index length".to_owned(),
});
}
let nanos: Vec<i64> = labels
.iter()
.zip(mask.iter())
.map(|(label, &replace)| {
if replace {
value
} else {
match label {
IndexLabel::Datetime64(n) => *n,
_ => i64::MIN,
}
}
})
.collect();
Ok(self.with_instants(nanos))
}
/// Binary-search insertion position, matching
/// `pd.DatetimeIndex.searchsorted(value, side)`. The needle is the
/// nanoseconds-since-epoch value to locate; pandas behavior on NAT
/// needles is to raise, mirrored as
/// [`IndexError::InvalidArgument("searchsorted: needle cannot be missing")`].
pub fn searchsorted(&self, value: i64, side: &str) -> Result<usize, IndexError> {
self.index
.searchsorted(&IndexLabel::Datetime64(value), side)
}
/// Convert each label to a `chrono::DateTime<Utc>`, matching
/// `pd.DatetimeIndex.to_pydatetime()`. NAT propagates as `None`.
#[must_use]
pub fn to_pydatetime(&self) -> Vec<Option<chrono::DateTime<chrono::Utc>>> {
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) => datetime_from_nanos(*nanos),
_ => None,
})
.collect()
}
/// Insert `value` at position `loc`, matching
/// `pd.DatetimeIndex.insert(loc, value)`. `loc == len()` appends;
/// `loc > len()` raises [`IndexError::OutOfBounds`].
pub fn insert(&self, loc: usize, value: i64) -> Result<Self, IndexError> {
let labels = self.index.labels();
if loc > labels.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: labels.len(),
});
}
let mut nanos: Vec<i64> = labels
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
})
.collect();
nanos.insert(loc, value);
Ok(self.with_instants(nanos))
}
/// Stringify each label, matching `pd.DatetimeIndex.format()`.
/// Non-NAT labels render as the chrono RFC3339 timestamp (a tz-aware
/// index's on its wall clock with the zone's offset); NAT renders as
/// the `NaT` literal pandas uses.
#[must_use]
pub fn format(&self) -> Vec<String> {
let zone = self.index.tz();
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) => match datetime_from_nanos(*nanos) {
Some(dt) => {
let offset = zone
.and_then(|zone| fp_types::tz_offset_seconds(zone, *nanos).ok())
.and_then(chrono::FixedOffset::east_opt);
match offset {
Some(offset) => dt.with_timezone(&offset).to_rfc3339(),
None => dt.to_rfc3339(),
}
}
None => "NaT".to_owned(),
},
_ => "NaT".to_owned(),
})
.collect()
}
/// Replace NAT positions with `value`, matching
/// `pd.DatetimeIndex.fillna(value)`. Preserves the index name.
#[must_use]
pub fn fillna(&self, value: i64) -> Self {
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(n) if *n != i64::MIN => *n,
_ => value,
})
.collect();
self.with_instants(nanos)
}
/// Alias for [`isna`](Self::isna), matching `pd.DatetimeIndex.isnull()`.
#[must_use]
pub fn isnull(&self) -> Vec<bool> {
self.isna()
}
/// Alias for [`notna`](Self::notna), matching `pd.DatetimeIndex.notnull()`.
#[must_use]
pub fn notnull(&self) -> Vec<bool> {
self.notna()
}
/// Calendar date part of each label, matching `pd.DatetimeIndex.date`.
#[must_use]
pub fn date(&self) -> Vec<Option<chrono::NaiveDate>> {
map_datetime_labels(&self.wall_labels(), |dt| dt.date_naive())
}
/// Within-day clock time of each label, matching
/// `pd.DatetimeIndex.time`.
#[must_use]
pub fn time(&self) -> Vec<Option<chrono::NaiveTime>> {
map_datetime_labels(&self.wall_labels(), |dt| dt.time())
}
/// Time component preserving timezone semantics, matching
/// `pd.DatetimeIndex.timetz`. FrankenPandas currently stores
/// timezone-naive UTC nanoseconds, so this matches [`Self::time`].
#[must_use]
pub fn timetz(&self) -> Vec<Option<chrono::NaiveTime>> {
self.time()
}
/// Convert each label to its Julian Date, matching
/// `pd.DatetimeIndex.to_julian_date()`. The formula is
/// `JD = unix_seconds / 86400 + 2440587.5` and the result is
/// computed in f64; NAT propagates as `None`.
#[must_use]
pub fn to_julian_date(&self) -> Vec<Option<f64>> {
const SECONDS_PER_DAY: f64 = 86_400.0;
const UNIX_EPOCH_JD: f64 = 2_440_587.5;
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => {
let secs = (*nanos as f64) / 1_000_000_000.0;
Some(secs / SECONDS_PER_DAY + UNIX_EPOCH_JD)
}
_ => None,
})
.collect()
}
/// pandas' `DatetimeIndex.tz_localize(tz)`: a naive index's wall-clock
/// times placed in `tz` (a wall time a DST change skips or repeats is an
/// error, pandas' default `ambiguous` / `nonexistent='raise'`), or an
/// aware index's wall clock kept without its zone (`None`). Localizing
/// an aware index to a zone is pandas' TypeError.
pub fn tz_localize(&self, tz: Option<&str>) -> Result<Self, IndexError> {
match (tz, self.index.tz()) {
(Some(_), Some(_)) => Err(IndexError::TimeZoneMismatch(
"Already tz-aware, use tz_convert to convert.".to_owned(),
)),
(None, None) => Ok(self.clone()),
(None, Some(_)) => Ok(self.wall_index()),
(Some(zone), None) => {
let nanos = self
.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) => {
fp_types::tz_wall_to_utc_nanos(zone, *nanos)
}
_ => Ok(i64::MIN),
})
.collect::<Result<Vec<_>, _>>()?;
let localized = Self::new(nanos).rename_index(self.name());
// pandas keeps the freq only for UTC, where no wall time moves.
let freq = self.index.freq.clone().filter(|_| zone == "UTC");
Ok(Self {
index: localized.index.with_tz(Some(zone))?.with_freq(freq),
})
}
}
}
/// pandas' `DatetimeIndex.tz_convert(tz)`: the same instants shown in
/// `tz` (`None`: UTC, naive). Converting a naive index is pandas'
/// TypeError.
pub fn tz_convert(&self, tz: Option<&str>) -> Result<Self, IndexError> {
if self.index.tz().is_none() {
return Err(IndexError::TimeZoneMismatch(
"Cannot convert tz-naive timestamps, use tz_localize to localize".to_owned(),
));
}
Ok(Self {
index: self.index.clone().with_tz(tz)?,
})
}
/// These instants (UTC nanoseconds) shown in `tz` - no conversion: the
/// constructor for an aware index from its instants (`tz_localize`
/// takes wall times, `tz_convert` changes an aware index's zone).
pub fn with_tz(self, tz: Option<&str>) -> Result<Self, IndexError> {
Ok(Self {
index: self.index.with_tz(tz)?,
})
}
/// `nanos` - instants taken, sorted, filtered or moved by a duration from
/// this index's - as an index with its name and zone.
fn with_instants(&self, nanos: Vec<i64>) -> Self {
let mut out = Self::new(nanos).rename_index(self.name());
out.index.tz.clone_from(&self.index.tz);
out
}
/// `nanos` from a set operation of this index with `other`: pandas keeps
/// a shared name and zone (two zones meet in UTC).
fn with_joined_instants(&self, other: &Self, nanos: Vec<i64>) -> Self {
let mut out = Self::new(nanos);
if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
out = out.set_name(name);
}
out.index.tz = joined_tz(&self.index, &other.index);
out
}
/// The labels as the wall clock shows them: a tz-aware index's UTC
/// instants moved into its zone, which every calendar field reads (a
/// naive index's labels as they are).
fn wall_labels(&self) -> Cow<'_, [IndexLabel]> {
let Some(zone) = self.index.tz() else {
return Cow::Borrowed(self.index.labels());
};
Cow::Owned(
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) => IndexLabel::Datetime64(
fp_types::tz_utc_to_wall_nanos(zone, *nanos).unwrap_or(*nanos),
),
other => other.clone(),
})
.collect(),
)
}
/// The wall-clock times as a naive index (`tz_localize(None)`), the
/// name kept.
fn wall_index(&self) -> Self {
Self {
index: Index::new(self.wall_labels().into_owned()).rename_index(self.name()),
}
}
/// Naive wall-clock times computed from this index placed back in its
/// zone (a naive index's as they are), as pandas re-localizes a
/// rounded or normalized aware index.
fn rezoned(&self, wall: Self) -> Result<Self, IndexError> {
match self.index.tz() {
Some(zone) => wall.tz_localize(Some(zone)),
None => Ok(wall),
}
}
/// Timezone name, matching `pd.DatetimeIndex.tz` (None when naive).
#[must_use]
pub fn tz(&self) -> Option<String> {
self.index.tz().map(str::to_owned)
}
/// Alias for [`tz`](Self::tz), matching `pd.DatetimeIndex.tzinfo`.
#[must_use]
pub fn tzinfo(&self) -> Option<String> {
self.tz()
}
/// The frequency this index was built with, as its freqstr - pandas'
/// `DatetimeIndex.freq` / `freqstr` ('D', '12h', 'W-SUN', 'ME'); None
/// when it has none (it was always None).
#[must_use]
pub fn freq(&self) -> Option<String> {
self.index.freq().map(str::to_owned)
}
/// Alias of [`Self::freq`], matching `pd.DatetimeIndex.freqstr`.
#[must_use]
pub fn freqstr(&self) -> Option<String> {
self.freq()
}
/// This index with `freq` (a freqstr) set or cleared; the caller vouches
/// that the labels follow it.
#[must_use]
pub fn with_freq(self, freq: Option<String>) -> Self {
Self {
index: self.index.with_freq(freq),
}
}
/// pandas' `DatetimeIndex.inferred_freq`: the frequency the labels
/// follow, read from their wall clock (see [`infer_datetime_freq`]);
/// None for fewer than three labels, NaT, repeats or an irregular run
/// (it was always None).
#[must_use]
pub fn inferred_freq(&self) -> Option<String> {
let mut wall = Vec::with_capacity(self.len());
for label in self.wall_labels().iter() {
match label {
IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => wall.push(*nanos),
_ => return None,
}
}
let instants: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(nanos) => Some(*nanos),
_ => None,
})
.collect();
infer_datetime_freq(&wall, &instants)
}
/// Cast to a different storage resolution, matching
/// `pd.DatetimeIndex.as_unit(unit)`. FrankenPandas's storage is fixed
/// at nanoseconds so only `"ns"` is supported as a no-op clone; other
/// units reject with a typed compatibility error.
pub fn as_unit(&self, unit: &str) -> Result<Self, IndexError> {
match unit {
"ns" => Ok(self.clone()),
other => Err(IndexError::InvalidArgument(format!(
"as_unit: only 'ns' is supported by FrankenPandas's Datetime64 storage; got {other:?}"
))),
}
}
/// Storage resolution unit, matching `pd.DatetimeIndex.unit`. Always
/// `"ns"` because FrankenPandas stores Datetime64 as nanoseconds.
#[must_use]
pub fn unit(&self) -> &'static str {
"ns"
}
/// Resolution string, matching `pd.DatetimeIndex.resolution`. Always
/// `"nanosecond"` because the underlying storage is fixed at ns.
#[must_use]
pub fn resolution(&self) -> &'static str {
"nanosecond"
}
/// First position of `value`, matching `pd.DatetimeIndex.get_loc(value)`.
/// Pandas raises KeyError for missing values; this surface mirrors
/// that with [`IndexError::InvalidArgument`].
pub fn get_loc(&self, value: i64) -> Result<usize, IndexError> {
// Delegate to Index::position, which binary-searches a monotonic
// (AscendingDatetime64) index in O(log n) instead of the O(n) linear
// scan, and falls back to the same first-match linear scan when unsorted
// (br-frankenpandas-idxdup). Bit-identical: a Datetime64(value) needle
// matches exactly the labels this scan accepted.
self.index
.position(&IndexLabel::Datetime64(value))
.ok_or_else(|| {
IndexError::InvalidArgument(format!("get_loc: {value} not in DatetimeIndex"))
})
}
/// Set the index name, matching `pd.DatetimeIndex.rename(name)`.
/// Alias for set_name.
#[must_use]
pub fn rename(&self, name: &str) -> Self {
self.set_name(name)
}
/// Reindex against `target`, matching
/// `pd.DatetimeIndex.reindex(target)`. Returns
/// `(target.clone(), indexer)` where indexer is the per-target
/// position from get_indexer (with -1 for missing).
#[must_use]
pub fn reindex(&self, target: &Self) -> (Self, Vec<isize>) {
let labels: Vec<i64> = target
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(n) => Some(*n),
_ => None,
})
.collect();
let indexer = self.get_indexer(&labels);
(target.clone(), indexer)
}
/// Locate every position matching each target, matching
/// `pd.DatetimeIndex.get_indexer_non_unique(targets)`. Returns
/// `(positions, missing)` where `positions` lists every source
/// position matching any target (in target order) and `missing`
/// lists target ordinals that had no match.
#[must_use]
pub fn get_indexer_non_unique(&self, targets: &[i64]) -> (Vec<isize>, Vec<usize>) {
let labels = self.index.labels();
let mut by_value = FxHashMap::<i64, Vec<usize>>::default();
for (i, label) in labels.iter().enumerate() {
if let IndexLabel::Datetime64(n) = label {
by_value.entry(*n).or_default().push(i);
}
}
let mut positions = Vec::<isize>::new();
let mut missing = Vec::<usize>::new();
for (idx, target) in targets.iter().enumerate() {
if let Some(matches) = by_value.get(target) {
positions.extend(
matches
.iter()
.map(|p| isize::try_from(*p).unwrap_or(isize::MAX)),
);
} else {
positions.push(-1);
missing.push(idx);
}
}
(positions, missing)
}
/// Alias for [`get_indexer`](Self::get_indexer), matching
/// `pd.DatetimeIndex.get_indexer_for(targets)`.
#[must_use]
pub fn get_indexer_for(&self, targets: &[i64]) -> Vec<isize> {
self.get_indexer(targets)
}
/// Locate each label in `targets`, matching
/// `pd.DatetimeIndex.get_indexer(targets)`. Returns `Vec<isize>` where
/// `-1` means "missing".
#[must_use]
pub fn get_indexer(&self, targets: &[i64]) -> Vec<isize> {
let labels = self.index.labels();
let mut positions = FxHashMap::<i64, isize>::default();
for (i, label) in labels.iter().enumerate() {
if let IndexLabel::Datetime64(n) = label {
positions
.entry(*n)
.or_insert_with(|| isize::try_from(i).unwrap_or(isize::MAX));
}
}
targets
.iter()
.map(|n| positions.get(n).copied().unwrap_or(-1))
.collect()
}
/// Position of the slice boundary for `label` and `side`, matching
/// `pd.DatetimeIndex.get_slice_bound(label, side)`. Mirrors
/// `searchsorted(label, side)`.
pub fn get_slice_bound(&self, label: i64, side: &str) -> Result<usize, IndexError> {
self.searchsorted(label, side)
}
/// Half-open positional range for a label slice, matching
/// `pd.DatetimeIndex.slice_indexer(start, end)`. Wraps slice_locs
/// in a `std::ops::Range<usize>`.
pub fn slice_indexer(
&self,
start: i64,
end: i64,
) -> Result<std::ops::Range<usize>, IndexError> {
let (left, right) = self.slice_locs(start, end)?;
Ok(left..right)
}
/// Find positions of `[start, end]` for a label slice, matching
/// `pd.DatetimeIndex.slice_locs(start, end)`. Requires the index to
/// be monotonically increasing; non-monotonic input rejects.
pub fn slice_locs(&self, start: i64, end: i64) -> Result<(usize, usize), IndexError> {
if !self.is_monotonic_increasing() {
return Err(IndexError::InvalidArgument(
"slice_locs requires a monotonic increasing DatetimeIndex".to_owned(),
));
}
let left = self.searchsorted(start, "left")?;
let right = self.searchsorted(end, "right")?;
Ok((left, right))
}
/// Convert to a flat [`Index`], matching
/// `pd.DatetimeIndex.to_flat_index()`. Clone-as-Index because the
/// underlying storage is already a flat Index of Datetime64 labels.
#[must_use]
pub fn to_flat_index(&self) -> Index {
self.index.clone()
}
/// String accessor for the flat datetime labels.
#[must_use]
pub fn r#str(&self) -> IndexStringAccessor<'_> {
IndexStringAccessor::owned(self.to_flat_index())
}
/// One-column row materialization, matching `pd.DatetimeIndex.to_frame(index=False)`.
#[must_use]
pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
self.to_flat_index().to_frame()
}
/// Series-shaped materialization using datetime labels as both index and values.
#[must_use]
pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
self.to_flat_index().to_series()
}
/// Whether any datetime label coerces to true.
#[must_use]
pub fn any(&self) -> bool {
self.to_flat_index().any()
}
/// Whether all datetime labels coerce to true.
#[must_use]
pub fn all(&self) -> bool {
self.to_flat_index().all()
}
/// Get labels for a level. DatetimeIndex is flat and only accepts level 0.
pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
self.to_flat_index().get_level_values(level)
}
/// Drop a level. DatetimeIndex is flat, so removing its only level is invalid.
pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
self.to_flat_index().droplevel(level)
}
/// Group equal datetime labels into position buckets.
#[must_use]
pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
self.to_flat_index().groupby()
}
/// Apply a function to each datetime label, returning a flat Index.
#[must_use]
pub fn map<F>(&self, func: F) -> Index
where
F: Fn(&IndexLabel) -> IndexLabel,
{
self.to_flat_index().map(func)
}
/// Cast datetime labels to a pandas dtype string, returning a flat Index.
pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
self.to_flat_index().astype(dtype)
}
/// Nearest preceding-or-equal datetime label lookup.
#[must_use]
pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
self.to_flat_index().asof(key)
}
/// Locate nearest preceding-or-equal datetime positions for each target label.
#[must_use]
pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
self.to_flat_index().asof_locs(where_index, mask)
}
/// Drop datetime labels, returning a flat Index.
#[must_use]
pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
self.to_flat_index().drop(labels_to_drop)
}
/// Join datetime labels with another flat Index.
pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
self.to_flat_index().join(other, how)
}
/// Sort datetime labels and return the positional sorter.
#[must_use]
pub fn sortlevel(&self) -> (Index, Vec<usize>) {
self.to_flat_index().sortlevel()
}
/// Returns a clone, matching `pd.DatetimeIndex.view()`. FrankenPandas
/// owns its label storage so view materializes a fresh clone instead
/// of an aliasing reference.
#[must_use]
pub fn view(&self) -> Self {
self.clone()
}
/// Identity transpose for a 1D index, matching
/// `pd.DatetimeIndex.transpose()`.
#[must_use]
pub fn transpose(&self) -> Self {
self.clone()
}
/// Alias for `transpose`, matching `pd.DatetimeIndex.T`.
#[allow(non_snake_case)]
#[must_use]
pub fn T(&self) -> Self {
self.transpose()
}
/// Flatten labels to nanoseconds-since-epoch with NAT preserved,
/// matching `pd.DatetimeIndex.ravel()`.
#[must_use]
pub fn ravel(&self) -> Vec<Option<i64>> {
self.values()
}
/// Number of levels in this Index, matching `pd.DatetimeIndex.nlevels`.
/// Always `1` because DatetimeIndex is a single-level index.
#[must_use]
pub fn nlevels(&self) -> usize {
1
}
/// Identity dtype-reinference for typed indexes, matching
/// `pd.DatetimeIndex.infer_objects()`.
#[must_use]
pub fn infer_objects(&self) -> Self {
self.clone()
}
/// Drop NAT labels, matching `pd.DatetimeIndex.dropna()`. Non-datetime
/// labels (which the wrapper rejects on construction) and `i64::MIN`
/// sentinels are removed; surviving labels keep their order.
pub fn dropna(&self) -> Self {
let surviving: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => Some(*nanos),
_ => None,
})
.collect();
self.with_instants(surviving)
}
#[must_use]
pub fn year(&self) -> Vec<Option<i32>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.year())
}
#[must_use]
pub fn month(&self) -> Vec<Option<u32>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.month())
}
#[must_use]
pub fn day(&self) -> Vec<Option<u32>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.day())
}
/// Hour of day per label (0..=23), matching `pd.DatetimeIndex.hour`.
#[must_use]
pub fn hour(&self) -> Vec<Option<u32>> {
use chrono::Timelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.hour())
}
/// Minute of hour per label (0..=59), matching `pd.DatetimeIndex.minute`.
#[must_use]
pub fn minute(&self) -> Vec<Option<u32>> {
use chrono::Timelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.minute())
}
/// Second of minute per label (0..=59), matching `pd.DatetimeIndex.second`.
#[must_use]
pub fn second(&self) -> Vec<Option<u32>> {
use chrono::Timelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.second())
}
/// Microsecond component (0..=999_999), matching `pd.DatetimeIndex.microsecond`.
/// Computed from the within-second nanosecond bucket: `nanos / 1_000`.
#[must_use]
pub fn microsecond(&self) -> Vec<Option<u32>> {
use chrono::Timelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.nanosecond() / 1_000)
}
/// Nanosecond component (0..=999), matching `pd.DatetimeIndex.nanosecond`.
/// Computed from the within-second nanosecond bucket: `nanos % 1_000`.
#[must_use]
pub fn nanosecond(&self) -> Vec<Option<u32>> {
use chrono::Timelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.nanosecond() % 1_000)
}
/// Integer positions whose clock time equals `time`, matching
/// `pd.DatetimeIndex.indexer_at_time(time)`.
pub fn indexer_at_time(&self, time: &str) -> Result<Vec<usize>, IndexError> {
let target = parse_time_of_day_nanos(time, "DatetimeIndex.indexer_at_time")?;
Ok(self
.wall_labels()
.iter()
.enumerate()
.filter_map(|(position, label)| {
(datetime_label_time_nanos(label) == Some(target)).then_some(position)
})
.collect())
}
/// Integer positions whose clock time falls between `start_time` and
/// `end_time`, matching `pd.DatetimeIndex.indexer_between_time`.
/// Ranges that cross midnight use pandas' wrap-around semantics.
pub fn indexer_between_time(
&self,
start_time: &str,
end_time: &str,
include_start: bool,
include_end: bool,
) -> Result<Vec<usize>, IndexError> {
let start =
parse_time_of_day_nanos(start_time, "DatetimeIndex.indexer_between_time start_time")?;
let end = parse_time_of_day_nanos(end_time, "DatetimeIndex.indexer_between_time end_time")?;
Ok(self
.wall_labels()
.iter()
.enumerate()
.filter_map(|(position, label)| {
datetime_label_time_nanos(label)
.filter(|time| {
time_nanos_in_between(*time, start, end, include_start, include_end)
})
.map(|_| position)
})
.collect())
}
/// ISO 8601 week-of-year (1..=53).
///
/// ⚠️ NOT DEPRECATED -- REMOVED. `pd.DatetimeIndex.week` raises
/// `AttributeError` on pandas 2.2.3 (measured), as does `.weekofyear`; both
/// went in pandas 2.0. The pandas replacement is [`isocalendar`](Self::isocalendar),
/// below. FP keeps this as a SUPERSET for pandas 1.x callers, not as parity.
///
/// ⚠️ Do NOT generalize the removal to PeriodIndex: `pd.PeriodIndex.week`
/// and `.weekofyear` both SURVIVE on 2.2.3, so the PeriodIndex docs in this
/// file are correct as written.
#[must_use]
pub fn week(&self) -> Vec<Option<u32>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.iso_week().week())
}
/// ISO calendar `(year, week, weekday)` triples, matching
/// `pd.DatetimeIndex.isocalendar()`. Weekday uses pandas' Monday=1
/// through Sunday=7 convention.
#[must_use]
pub fn isocalendar(&self) -> Vec<Option<(i32, u32, u32)>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| {
let iso = dt.iso_week();
(iso.year(), iso.week(), dt.weekday().number_from_monday())
})
}
/// Alias for [`week`](Self::week).
///
/// ⚠️ `pd.DatetimeIndex.weekofyear` was REMOVED in pandas 2.0 (measured:
/// `AttributeError` on 2.2.3). Superset, not parity -- see [`week`](Self::week).
#[must_use]
pub fn weekofyear(&self) -> Vec<Option<u32>> {
self.week()
}
/// Day of year (1..=366), matching `pd.DatetimeIndex.dayofyear`.
#[must_use]
pub fn dayofyear(&self) -> Vec<Option<u32>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.ordinal())
}
/// Alias for [`dayofyear`](Self::dayofyear), matching `pd.DatetimeIndex.day_of_year`.
#[must_use]
pub fn day_of_year(&self) -> Vec<Option<u32>> {
self.dayofyear()
}
/// Weekday number (Monday=0..Sunday=6), matching
/// `pd.DatetimeIndex.dayofweek`.
#[must_use]
pub fn dayofweek(&self) -> Vec<Option<u32>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| {
dt.weekday().num_days_from_monday()
})
}
/// Alias for [`dayofweek`](Self::dayofweek), matching `pd.DatetimeIndex.day_of_week`.
#[must_use]
pub fn day_of_week(&self) -> Vec<Option<u32>> {
self.dayofweek()
}
/// Alias for [`dayofweek`](Self::dayofweek), matching `pd.DatetimeIndex.weekday`.
#[must_use]
pub fn weekday(&self) -> Vec<Option<u32>> {
self.dayofweek()
}
/// Calendar quarter (1..=4), matching `pd.DatetimeIndex.quarter`.
#[must_use]
pub fn quarter(&self) -> Vec<Option<u32>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| (dt.month() - 1) / 3 + 1)
}
/// Whether the year is a leap year, matching
/// `pd.DatetimeIndex.is_leap_year`.
#[must_use]
pub fn is_leap_year(&self) -> Vec<Option<bool>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| {
chrono::NaiveDate::from_ymd_opt(dt.year(), 1, 1).is_some_and(|d| d.leap_year())
})
}
/// Number of days in the calendar month of each label,
/// matching `pd.DatetimeIndex.days_in_month`.
#[must_use]
pub fn days_in_month(&self) -> Vec<Option<u32>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| {
days_in_calendar_month(dt.year(), dt.month())
})
}
/// Alias for [`days_in_month`](Self::days_in_month), matching `pd.DatetimeIndex.daysinmonth`.
#[must_use]
pub fn daysinmonth(&self) -> Vec<Option<u32>> {
self.days_in_month()
}
/// Whether the day is the first of the month, matching
/// `pd.DatetimeIndex.is_month_start`.
#[must_use]
pub fn is_month_start(&self) -> Vec<Option<bool>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.day() == 1)
}
/// Whether the day is the last of the month, matching
/// `pd.DatetimeIndex.is_month_end`.
#[must_use]
pub fn is_month_end(&self) -> Vec<Option<bool>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| {
dt.day() == days_in_calendar_month(dt.year(), dt.month())
})
}
/// Whether the timestamp is the first day of a quarter, matching
/// `pd.DatetimeIndex.is_quarter_start`. Quarter starts: Jan/Apr/Jul/Oct day 1.
#[must_use]
pub fn is_quarter_start(&self) -> Vec<Option<bool>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| {
matches!(dt.month(), 1 | 4 | 7 | 10) && dt.day() == 1
})
}
/// Whether the timestamp is the last day of a quarter, matching
/// `pd.DatetimeIndex.is_quarter_end`. Quarter ends: Mar/Jun/Sep/Dec last day.
#[must_use]
pub fn is_quarter_end(&self) -> Vec<Option<bool>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| {
matches!(dt.month(), 3 | 6 | 9 | 12)
&& dt.day() == days_in_calendar_month(dt.year(), dt.month())
})
}
/// Whether the timestamp is January 1, matching
/// `pd.DatetimeIndex.is_year_start`.
#[must_use]
pub fn is_year_start(&self) -> Vec<Option<bool>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.month() == 1 && dt.day() == 1)
}
/// Whether the timestamp is December 31, matching
/// `pd.DatetimeIndex.is_year_end`.
#[must_use]
pub fn is_year_end(&self) -> Vec<Option<bool>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| dt.month() == 12 && dt.day() == 31)
}
/// Full English month name, matching `pd.DatetimeIndex.month_name()`.
#[must_use]
pub fn month_name(&self) -> Vec<Option<String>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| {
month_name_english(dt.month()).to_owned()
})
}
/// Full English weekday name, matching `pd.DatetimeIndex.day_name()`.
#[must_use]
pub fn day_name(&self) -> Vec<Option<String>> {
use chrono::Datelike;
map_datetime_labels(&self.wall_labels(), |dt| {
weekday_name_english(dt.weekday()).to_owned()
})
}
/// Truncate every timestamp to its wall-clock midnight, matching
/// `pd.DatetimeIndex.normalize()`: a tz-aware index's midnights are back
/// in its zone (a midnight a DST change skips is an error, as pandas).
/// NAT labels propagate.
pub fn normalize(&self) -> Result<Self, IndexError> {
let nanos: Vec<i64> = self
.wall_labels()
.iter()
.map(|label| match label {
IndexLabel::Datetime64(nanos) if *nanos != i64::MIN => {
let secs_per_day: i64 = 86_400;
let nanos_per_day: i64 = secs_per_day * 1_000_000_000;
nanos.div_euclid(nanos_per_day) * nanos_per_day
}
_ => i64::MIN,
})
.collect();
let mut normalized = Self::new(nanos);
if let Some(name) = self.name() {
normalized = normalized.set_name(name);
}
// pandas infers the freq of the midnights (then localizes, which
// keeps it only in UTC).
let freq = normalized.inferred_freq();
self.rezoned(normalized.with_freq(freq))
}
/// Whether every label is at its wall-clock midnight (NAT counts as
/// normalized), matching `pd.DatetimeIndex.is_normalized`.
#[must_use]
pub fn is_normalized(&self) -> bool {
let nanos_per_day: i64 = 86_400 * 1_000_000_000;
self.wall_labels().iter().all(|label| match label {
IndexLabel::Datetime64(nanos) => {
*nanos == i64::MIN || nanos.rem_euclid(nanos_per_day) == 0
}
_ => true,
})
}
}
fn month_name_english(month: u32) -> &'static str {
match month {
1 => "January",
2 => "February",
3 => "March",
4 => "April",
5 => "May",
6 => "June",
7 => "July",
8 => "August",
9 => "September",
10 => "October",
11 => "November",
12 => "December",
_ => "",
}
}
fn weekday_name_english(weekday: chrono::Weekday) -> &'static str {
match weekday {
chrono::Weekday::Mon => "Monday",
chrono::Weekday::Tue => "Tuesday",
chrono::Weekday::Wed => "Wednesday",
chrono::Weekday::Thu => "Thursday",
chrono::Weekday::Fri => "Friday",
chrono::Weekday::Sat => "Saturday",
chrono::Weekday::Sun => "Sunday",
}
}
fn days_in_calendar_month(year: i32, month: u32) -> u32 {
let next_month = if month == 12 { 1 } else { month + 1 };
let next_year = if month == 12 { year + 1 } else { year };
let first_of_next = chrono::NaiveDate::from_ymd_opt(next_year, next_month, 1);
let first_of_this = chrono::NaiveDate::from_ymd_opt(year, month, 1);
match (first_of_next, first_of_this) {
(Some(next), Some(this)) => (next - this).num_days() as u32,
_ => 0,
}
}
/// Public pandas-style timedelta index wrapper.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimedeltaIndex {
index: Index,
}
impl TimedeltaIndex {
#[must_use]
pub fn new(nanos: Vec<i64>) -> Self {
Self {
index: Index::from_timedelta64(nanos),
}
}
pub fn from_index(index: Index) -> Result<Self, IndexError> {
ensure_index_kind(&index, LabelKinds::TIMEDELTA64, "TimedeltaIndex")?;
Ok(Self { index })
}
#[must_use]
pub fn as_index(&self) -> &Index {
&self.index
}
#[must_use]
pub fn into_index(self) -> Index {
self.index
}
#[must_use]
pub fn len(&self) -> usize {
self.index.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.index.is_empty()
}
#[must_use]
pub fn name(&self) -> Option<&LabelName> {
self.index.name()
}
#[must_use]
pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
Self {
index: self.index.set_name(name),
}
}
#[must_use]
pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
Self {
index: self.index.set_names(name),
}
}
#[must_use]
pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
self.set_names(name)
}
#[must_use]
pub fn names(&self) -> Vec<Option<String>> {
self.index.names()
}
#[must_use]
pub fn copy(&self) -> Self {
self.clone()
}
#[must_use]
pub fn shape(&self) -> (usize,) {
self.index.shape()
}
#[must_use]
pub fn size(&self) -> usize {
self.index.size()
}
#[must_use]
pub fn empty(&self) -> bool {
self.index.empty()
}
#[must_use]
pub fn dtype(&self) -> &'static str {
"timedelta64[ns]"
}
#[must_use]
pub fn dtypes(&self) -> Vec<&'static str> {
vec![self.dtype()]
}
#[must_use]
pub fn memory_usage(&self, deep: bool) -> usize {
self.index.memory_usage(deep)
}
#[must_use]
pub fn nbytes(&self) -> usize {
self.index.nbytes()
}
#[must_use]
pub fn hasnans(&self) -> bool {
self.index.hasnans()
}
#[must_use]
pub fn isna(&self) -> Vec<bool> {
self.index.isna()
}
#[must_use]
pub fn notna(&self) -> Vec<bool> {
self.index.notna()
}
#[must_use]
pub fn is_unique(&self) -> bool {
self.index.is_unique()
}
#[must_use]
pub fn has_duplicates(&self) -> bool {
self.index.has_duplicates()
}
#[must_use]
pub fn is_monotonic_increasing(&self) -> bool {
self.index.is_monotonic_increasing()
}
#[must_use]
pub fn is_monotonic(&self) -> bool {
self.index.is_monotonic()
}
#[must_use]
pub fn is_monotonic_decreasing(&self) -> bool {
self.index.is_monotonic_decreasing()
}
#[must_use]
pub fn nunique(&self) -> usize {
self.index.nunique()
}
#[must_use]
pub fn nunique_with_dropna(&self, dropna: bool) -> usize {
self.index.nunique_with_dropna(dropna)
}
#[must_use]
pub fn ndim(&self) -> usize {
self.index.ndim()
}
pub fn item(&self) -> Result<Option<i64>, IndexError> {
match self.index.item()? {
IndexLabel::Timedelta64(nanos) if nanos != Timedelta::NAT => Ok(Some(nanos)),
IndexLabel::Timedelta64(_) => Ok(None),
label => Err(IndexError::InvalidArgument(format!(
"TimedeltaIndex item must be timedelta64, got {label}"
))),
}
}
#[must_use]
pub fn is_(&self, other: &Self) -> bool {
std::ptr::eq(self, other)
}
#[must_use]
pub fn equals(&self, other: &Self) -> bool {
self.index.equals(&other.index)
}
#[must_use]
pub fn identical(&self, other: &Self) -> bool {
self.index.identical(&other.index)
}
#[must_use]
pub fn holds_integer(&self) -> bool {
false
}
#[must_use]
pub fn inferred_type(&self) -> &'static str {
"timedelta64"
}
#[must_use]
pub fn is_boolean(&self) -> bool {
false
}
#[must_use]
pub fn is_categorical(&self) -> bool {
false
}
#[must_use]
pub fn is_floating(&self) -> bool {
false
}
#[must_use]
pub fn is_integer(&self) -> bool {
false
}
#[must_use]
pub fn is_interval(&self) -> bool {
false
}
#[must_use]
pub fn is_numeric(&self) -> bool {
false
}
#[must_use]
pub fn is_object(&self) -> bool {
false
}
#[must_use]
pub fn nanos(&self) -> Vec<Option<i64>> {
map_timedelta_labels(self.index.labels(), |nanos| nanos)
}
#[must_use]
pub fn values(&self) -> Vec<Option<i64>> {
self.nanos()
}
#[must_use]
pub fn to_list(&self) -> Vec<Option<i64>> {
self.nanos()
}
#[must_use]
pub fn tolist(&self) -> Vec<Option<i64>> {
self.to_list()
}
#[must_use]
pub fn to_numpy(&self) -> Vec<Option<i64>> {
self.nanos()
}
#[must_use]
pub fn array(&self) -> Vec<Option<i64>> {
self.nanos()
}
#[must_use]
pub fn days(&self) -> Vec<Option<i64>> {
map_timedelta_labels(self.index.labels(), |nanos| {
nanos.div_euclid(Timedelta::NANOS_PER_DAY)
})
}
#[must_use]
pub fn seconds(&self) -> Vec<Option<i64>> {
map_timedelta_labels(self.index.labels(), |nanos| {
nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC
})
}
#[must_use]
pub fn total_seconds(&self) -> Vec<Option<f64>> {
map_timedelta_labels(self.index.labels(), Timedelta::total_seconds)
}
/// Calendar-style component rows, matching `pd.TimedeltaIndex.components`.
/// NAT propagates as `None`.
#[must_use]
pub fn components(&self) -> Vec<Option<TimedeltaComponents>> {
map_timedelta_labels(self.index.labels(), timedelta_components_for_index)
}
/// Underlying nanosecond duration, matching `pd.TimedeltaIndex.asi8`.
/// `Timedelta::NAT` is preserved at the sentinel value.
#[must_use]
pub fn asi8(&self) -> Vec<i64> {
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(nanos) => *nanos,
IndexLabel::Int64(_)
| IndexLabel::Float64(_)
| IndexLabel::Bool(_)
| IndexLabel::Utf8(_)
| IndexLabel::Datetime64(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_) => Timedelta::NAT,
})
.collect()
}
/// Microseconds-within-second component (0..=999_999), matching
/// `pd.TimedeltaIndex.microseconds`.
#[must_use]
pub fn microseconds(&self) -> Vec<Option<i64>> {
map_timedelta_labels(self.index.labels(), |nanos| {
nanos.rem_euclid(Timedelta::NANOS_PER_SEC) / 1_000
})
}
/// Nanoseconds-within-microsecond component (0..=999), matching
/// `pd.TimedeltaIndex.nanoseconds`.
#[must_use]
pub fn nanoseconds(&self) -> Vec<Option<i64>> {
map_timedelta_labels(self.index.labels(), |nanos| nanos.rem_euclid(1_000))
}
/// Position of the maximum label, matching `pd.TimedeltaIndex.argmax()`.
/// Skips NAT and returns the first-tied position to match pandas
/// `skipna=True` default.
pub fn argmax(&self) -> Result<usize, IndexError> {
let labels = self.index.labels();
let mut best: Option<usize> = None;
for (i, label) in labels.iter().enumerate() {
let nanos = match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => *n,
_ => continue,
};
best = Some(match best {
Some(b) => match labels[b] {
IndexLabel::Timedelta64(prev) if nanos > prev => i,
_ => b,
},
None => i,
});
}
best.ok_or_else(|| {
IndexError::InvalidArgument("attempt to get argmax of an empty sequence".to_owned())
})
}
/// Position of the minimum label, matching `pd.TimedeltaIndex.argmin()`.
pub fn argmin(&self) -> Result<usize, IndexError> {
let labels = self.index.labels();
let mut best: Option<usize> = None;
for (i, label) in labels.iter().enumerate() {
let nanos = match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => *n,
_ => continue,
};
best = Some(match best {
Some(b) => match labels[b] {
IndexLabel::Timedelta64(prev) if nanos < prev => i,
_ => b,
},
None => i,
});
}
best.ok_or_else(|| {
IndexError::InvalidArgument("attempt to get argmin of an empty sequence".to_owned())
})
}
/// Positions that would sort the labels ascending, matching
/// `pd.TimedeltaIndex.argsort()`.
#[must_use]
pub fn argsort(&self) -> Vec<usize> {
self.index.argsort()
}
/// First-seen unique labels, matching `pd.TimedeltaIndex.unique()`.
pub fn unique(&self) -> Result<Self, IndexError> {
Self::from_index(self.index.unique())
}
/// Factorization, matching `pd.TimedeltaIndex.factorize()`. NAT inputs
/// receive `-1` codes; uniques excludes NAT.
pub fn factorize(&self) -> Result<(Vec<isize>, Self), IndexError> {
let (codes, uniques) = self.index.factorize();
Ok((codes, Self::from_index(uniques)?))
}
/// Value counts, matching `pd.TimedeltaIndex.value_counts()`. NAT is
/// dropped by default to match pandas.
#[must_use]
pub fn value_counts(&self) -> Vec<(IndexLabel, usize)> {
self.index.value_counts()
}
/// Duplicate mask per position, matching
/// `pd.TimedeltaIndex.duplicated(keep)`.
#[must_use]
pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
self.index.duplicated(keep)
}
/// Drop duplicate labels, matching `pd.TimedeltaIndex.drop_duplicates()`.
pub fn drop_duplicates(&self) -> Result<Self, IndexError> {
Self::from_index(self.index.drop_duplicates())
}
/// Replace positions where `cond` is `false` with `other`, matching
/// `pd.TimedeltaIndex.where(cond, other)`. Pass `Timedelta::NAT` to
/// insert NAT.
pub fn r#where(&self, cond: &[bool], other: i64) -> Result<Self, IndexError> {
let labels = self.index.labels();
if cond.len() != labels.len() {
return Err(IndexError::LengthMismatch {
expected: labels.len(),
actual: cond.len(),
context: "where: cond length must match index length".to_owned(),
});
}
let nanos: Vec<i64> = labels
.iter()
.zip(cond.iter())
.map(|(label, &keep)| {
if keep {
match label {
IndexLabel::Timedelta64(n) => *n,
_ => Timedelta::NAT,
}
} else {
other
}
})
.collect();
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
/// Replace positions where `mask` is `true` with `value`, matching
/// `pd.TimedeltaIndex.putmask(mask, value)`.
pub fn putmask(&self, mask: &[bool], value: i64) -> Result<Self, IndexError> {
let labels = self.index.labels();
if mask.len() != labels.len() {
return Err(IndexError::LengthMismatch {
expected: labels.len(),
actual: mask.len(),
context: "putmask: mask length must match index length".to_owned(),
});
}
let nanos: Vec<i64> = labels
.iter()
.zip(mask.iter())
.map(|(label, &replace)| {
if replace {
value
} else {
match label {
IndexLabel::Timedelta64(n) => *n,
_ => Timedelta::NAT,
}
}
})
.collect();
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
/// Binary-search insertion position, matching
/// `pd.TimedeltaIndex.searchsorted(value, side)`. The needle is a
/// nanosecond duration; NAT needles raise.
pub fn searchsorted(&self, value: i64, side: &str) -> Result<usize, IndexError> {
self.index
.searchsorted(&IndexLabel::Timedelta64(value), side)
}
/// Insert `value` at position `loc`, matching
/// `pd.TimedeltaIndex.insert(loc, value)`. `loc == len()` appends;
/// `loc > len()` raises [`IndexError::OutOfBounds`].
pub fn insert(&self, loc: usize, value: i64) -> Result<Self, IndexError> {
let labels = self.index.labels();
if loc > labels.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: labels.len(),
});
}
let mut nanos: Vec<i64> = labels
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
})
.collect();
nanos.insert(loc, value);
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
/// Stringify each label, matching `pd.TimedeltaIndex.format()`.
/// Non-NAT labels render as a signed nanosecond integer; NAT renders
/// as the `NaT` literal.
#[must_use]
pub fn format(&self) -> Vec<String> {
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(nanos) if *nanos != Timedelta::NAT => nanos.to_string(),
_ => "NaT".to_owned(),
})
.collect()
}
/// Replace NAT positions with `value`, matching
/// `pd.TimedeltaIndex.fillna(value)`. Preserves the index name.
#[must_use]
pub fn fillna(&self, value: i64) -> Self {
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => *n,
_ => value,
})
.collect();
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
out
}
/// Alias for [`isna`](Self::isna), matching `pd.TimedeltaIndex.isnull()`.
#[must_use]
pub fn isnull(&self) -> Vec<bool> {
self.isna()
}
/// Alias for [`notna`](Self::notna), matching `pd.TimedeltaIndex.notnull()`.
#[must_use]
pub fn notnull(&self) -> Vec<bool> {
self.notna()
}
/// Convert each label to a `chrono::Duration`, matching
/// `pd.TimedeltaIndex.to_pytimedelta()`. NAT propagates as `None`.
#[must_use]
pub fn to_pytimedelta(&self) -> Vec<Option<chrono::Duration>> {
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(nanos) if *nanos != Timedelta::NAT => {
Some(chrono::Duration::nanoseconds(*nanos))
}
_ => None,
})
.collect()
}
/// The frequency this index was built with, as its freqstr - pandas'
/// `TimedeltaIndex.freq` / `freqstr` ('h', '30min', 'D'); None when it
/// has none (it was always None).
#[must_use]
pub fn freq(&self) -> Option<String> {
self.index.freq().map(str::to_owned)
}
/// Alias of [`Self::freq`], matching `pd.TimedeltaIndex.freqstr`.
#[must_use]
pub fn freqstr(&self) -> Option<String> {
self.freq()
}
/// This index with `freq` (a freqstr) set or cleared; the caller vouches
/// that the labels follow it.
#[must_use]
pub fn with_freq(self, freq: Option<String>) -> Self {
Self {
index: self.index.with_freq(freq),
}
}
/// pandas' `TimedeltaIndex.inferred_freq`: the tick every step is (a
/// count of D / h / min / s / ms / us / ns, negative for a decreasing
/// run); None for fewer than three durations, NaT, repeats or an uneven
/// step (it was always None).
#[must_use]
pub fn inferred_freq(&self) -> Option<String> {
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(nanos) if *nanos != i64::MIN => Some(*nanos),
_ => None,
})
.collect::<Option<_>>()?;
if nanos.len() < 3 {
return None;
}
let steps = freq_unique_deltas(&nanos);
let [step] = steps.as_slice() else {
return None;
};
if *step == 0 {
return None;
}
// pandas' daily rule reads a whole-week step as weekly, naming the
// weekday the first duration falls on as an instant after the epoch
// (7 days -> 1970-01-08, a Thursday: 'W-THU').
const WEEK: i64 = 7 * 86_400_000_000_000;
if step % WEEK == 0 {
let weekday = Timestamp::from_nanos(nanos[0]).dayofweek()?;
let code = FREQ_WEEKDAY_CODES.get(usize::try_from(weekday).ok()?)?;
return Some(freq_with_count(step / WEEK, &format!("W-{code}")));
}
[
(86_400_000_000_000, "D"),
(3_600_000_000_000, "h"),
(60_000_000_000, "min"),
(1_000_000_000, "s"),
(1_000_000, "ms"),
(1_000, "us"),
(1, "ns"),
]
.into_iter()
.find(|(unit, _)| step % unit == 0)
.map(|(unit, rule)| freq_with_count(step / unit, rule))
}
/// Cast to a different storage resolution, matching
/// `pd.TimedeltaIndex.as_unit(unit)`. Only `"ns"` is supported.
pub fn as_unit(&self, unit: &str) -> Result<Self, IndexError> {
match unit {
"ns" => Ok(self.clone()),
other => Err(IndexError::InvalidArgument(format!(
"as_unit: only 'ns' is supported by FrankenPandas's Timedelta64 storage; got {other:?}"
))),
}
}
/// Storage resolution unit, matching `pd.TimedeltaIndex.unit`. Always
/// `"ns"`.
#[must_use]
pub fn unit(&self) -> &'static str {
"ns"
}
/// Resolution string. Always `"nanosecond"`.
///
/// ⚠️ TWO ways this is not parity. (a) `pd.TimedeltaIndex.resolution` does
/// NOT exist (measured 2.2.3: `AttributeError`) even though
/// `pd.DatetimeIndex.resolution` DOES. (b) Where pandas has a `resolution`,
/// it describes the DATA, not the storage unit: `resolution` on a
/// `DatetimeIndex` of day-aligned labels returns `'day'`. The fixed
/// `"nanosecond"` here answers a different question, and the class-level
/// `pd.Timedelta.resolution` is a `Timedelta` of 1ns, not a string.
#[must_use]
pub fn resolution(&self) -> &'static str {
"nanosecond"
}
/// First position of `value`, matching `pd.TimedeltaIndex.get_loc(value)`.
pub fn get_loc(&self, value: i64) -> Result<usize, IndexError> {
// Binary-search a monotonic (AscendingTimedelta64) index via
// Index::position; same first-match linear fallback when unsorted
// (br-frankenpandas-idxdup).
self.index
.position(&IndexLabel::Timedelta64(value))
.ok_or_else(|| {
IndexError::InvalidArgument(format!("get_loc: {value} not in TimedeltaIndex"))
})
}
/// Set the index name, matching `pd.TimedeltaIndex.rename(name)`.
#[must_use]
pub fn rename(&self, name: &str) -> Self {
self.set_name(name)
}
/// Reindex against `target`, matching
/// `pd.TimedeltaIndex.reindex(target)`.
#[must_use]
pub fn reindex(&self, target: &Self) -> (Self, Vec<isize>) {
let labels: Vec<i64> = target
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
})
.collect();
let indexer = self.get_indexer(&labels);
(target.clone(), indexer)
}
/// Locate every position matching each target, matching
/// `pd.TimedeltaIndex.get_indexer_non_unique(targets)`.
#[must_use]
pub fn get_indexer_non_unique(&self, targets: &[i64]) -> (Vec<isize>, Vec<usize>) {
let labels = self.index.labels();
let mut by_value = FxHashMap::<i64, Vec<usize>>::default();
for (i, label) in labels.iter().enumerate() {
if let IndexLabel::Timedelta64(n) = label {
by_value.entry(*n).or_default().push(i);
}
}
let mut positions = Vec::<isize>::new();
let mut missing = Vec::<usize>::new();
for (idx, target) in targets.iter().enumerate() {
if let Some(matches) = by_value.get(target) {
positions.extend(
matches
.iter()
.map(|p| isize::try_from(*p).unwrap_or(isize::MAX)),
);
} else {
positions.push(-1);
missing.push(idx);
}
}
(positions, missing)
}
/// Alias for [`get_indexer`](Self::get_indexer), matching
/// `pd.TimedeltaIndex.get_indexer_for(targets)`.
#[must_use]
pub fn get_indexer_for(&self, targets: &[i64]) -> Vec<isize> {
self.get_indexer(targets)
}
/// Locate each label in `targets`, matching
/// `pd.TimedeltaIndex.get_indexer(targets)`.
#[must_use]
pub fn get_indexer(&self, targets: &[i64]) -> Vec<isize> {
let labels = self.index.labels();
let mut positions = FxHashMap::<i64, isize>::default();
for (i, label) in labels.iter().enumerate() {
if let IndexLabel::Timedelta64(n) = label {
positions
.entry(*n)
.or_insert_with(|| isize::try_from(i).unwrap_or(isize::MAX));
}
}
targets
.iter()
.map(|n| positions.get(n).copied().unwrap_or(-1))
.collect()
}
/// Position of the slice boundary for `label` and `side`, matching
/// `pd.TimedeltaIndex.get_slice_bound(label, side)`. Mirrors
/// `searchsorted(label, side)`.
pub fn get_slice_bound(&self, label: i64, side: &str) -> Result<usize, IndexError> {
self.searchsorted(label, side)
}
/// Half-open positional range for a label slice, matching
/// `pd.TimedeltaIndex.slice_indexer(start, end)`.
pub fn slice_indexer(
&self,
start: i64,
end: i64,
) -> Result<std::ops::Range<usize>, IndexError> {
let (left, right) = self.slice_locs(start, end)?;
Ok(left..right)
}
/// Find positions of `[start, end]` for a label slice, matching
/// `pd.TimedeltaIndex.slice_locs(start, end)`. Requires the index to
/// be monotonically increasing.
pub fn slice_locs(&self, start: i64, end: i64) -> Result<(usize, usize), IndexError> {
if !self.is_monotonic_increasing() {
return Err(IndexError::InvalidArgument(
"slice_locs requires a monotonic increasing TimedeltaIndex".to_owned(),
));
}
let left = self.searchsorted(start, "left")?;
let right = self.searchsorted(end, "right")?;
Ok((left, right))
}
/// Convert to a flat [`Index`], matching
/// `pd.TimedeltaIndex.to_flat_index()`.
#[must_use]
pub fn to_flat_index(&self) -> Index {
self.index.clone()
}
/// String accessor for the flat timedelta labels.
#[must_use]
pub fn r#str(&self) -> IndexStringAccessor<'_> {
IndexStringAccessor::owned(self.to_flat_index())
}
/// One-column row materialization, matching `pd.TimedeltaIndex.to_frame(index=False)`.
#[must_use]
pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
self.to_flat_index().to_frame()
}
/// Series-shaped materialization using timedelta labels as both index and values.
#[must_use]
pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
self.to_flat_index().to_series()
}
/// Whether any timedelta label coerces to true.
#[must_use]
pub fn any(&self) -> bool {
self.to_flat_index().any()
}
/// Whether all timedelta labels coerce to true.
#[must_use]
pub fn all(&self) -> bool {
self.to_flat_index().all()
}
/// Get labels for a level. TimedeltaIndex is flat and only accepts level 0.
pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
self.to_flat_index().get_level_values(level)
}
/// Drop a level. TimedeltaIndex is flat, so removing its only level is invalid.
pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
self.to_flat_index().droplevel(level)
}
/// Group equal timedelta labels into position buckets.
#[must_use]
pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
self.to_flat_index().groupby()
}
/// Apply a function to each timedelta label, returning a flat Index.
#[must_use]
pub fn map<F>(&self, func: F) -> Index
where
F: Fn(&IndexLabel) -> IndexLabel,
{
self.to_flat_index().map(func)
}
/// Cast timedelta labels to a pandas dtype string, returning a flat Index.
pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
self.to_flat_index().astype(dtype)
}
/// Nearest preceding-or-equal timedelta label lookup.
#[must_use]
pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
self.to_flat_index().asof(key)
}
/// Locate nearest preceding-or-equal timedelta positions for each target label.
#[must_use]
pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
self.to_flat_index().asof_locs(where_index, mask)
}
/// Drop timedelta labels, returning a flat Index.
#[must_use]
pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
self.to_flat_index().drop(labels_to_drop)
}
/// Join timedelta labels with another flat Index.
pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
self.to_flat_index().join(other, how)
}
/// Sort timedelta labels and return the positional sorter.
#[must_use]
pub fn sortlevel(&self) -> (Index, Vec<usize>) {
self.to_flat_index().sortlevel()
}
/// Returns a clone, matching `pd.TimedeltaIndex.view()`.
#[must_use]
pub fn view(&self) -> Self {
self.clone()
}
/// Identity transpose for a 1D index, matching
/// `pd.TimedeltaIndex.transpose()`.
#[must_use]
pub fn transpose(&self) -> Self {
self.clone()
}
/// Alias for `transpose`, matching `pd.TimedeltaIndex.T`.
#[allow(non_snake_case)]
#[must_use]
pub fn T(&self) -> Self {
self.transpose()
}
/// Flatten labels to nanosecond durations with NAT preserved,
/// matching `pd.TimedeltaIndex.ravel()`.
#[must_use]
pub fn ravel(&self) -> Vec<Option<i64>> {
self.values()
}
/// Number of levels, matching `pd.TimedeltaIndex.nlevels`. Always `1`.
#[must_use]
pub fn nlevels(&self) -> usize {
1
}
/// Identity dtype-reinference for typed indexes, matching
/// `pd.TimedeltaIndex.infer_objects()`.
#[must_use]
pub fn infer_objects(&self) -> Self {
self.clone()
}
/// Drop NAT labels, matching `pd.TimedeltaIndex.dropna()`.
pub fn dropna(&self) -> Self {
let surviving: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(nanos) if *nanos != Timedelta::NAT => Some(*nanos),
_ => None,
})
.collect();
let mut filtered = Self::new(surviving);
if let Some(name) = self.name() {
filtered = filtered.set_name(name);
}
filtered
}
/// Pick labels at the given positions, matching
/// `pd.TimedeltaIndex.take()`. Out-of-bounds positions raise
/// [`IndexError::OutOfBounds`].
pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
let labels = self.index.labels();
for &p in positions {
if p >= labels.len() {
return Err(IndexError::OutOfBounds {
position: p,
length: labels.len(),
});
}
}
let nanos: Vec<i64> = positions
.iter()
.map(|&p| match labels[p] {
IndexLabel::Timedelta64(n) => n,
_ => Timedelta::NAT,
})
.collect();
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out.with_freq(take_freq(self.freq(), positions)))
}
/// Repeat each label `repeats` times, matching
/// `pd.TimedeltaIndex.repeat()`.
#[must_use]
pub fn repeat(&self, repeats: usize) -> Self {
let mut out = Vec::with_capacity(repeat_output_capacity(self.len(), repeats));
for label in self.index.labels() {
if let IndexLabel::Timedelta64(n) = label {
for _ in 0..repeats {
out.push(*n);
}
}
}
let mut result = Self::new(out);
if let Some(name) = self.name() {
result = result.set_name(name);
}
result
}
/// Per-position membership mask, matching
/// `pd.TimedeltaIndex.isin(values)`. `values` is interpreted as a slice
/// of nanosecond durations; pass `Timedelta::NAT` to test for NAT.
#[must_use]
pub fn isin(&self, values: &[i64]) -> Vec<bool> {
let needle: FxHashSet<i64> = values.iter().copied().collect();
self.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(n) => needle.contains(n),
_ => false,
})
.collect()
}
/// Concatenate with another TimedeltaIndex, matching
/// `pd.TimedeltaIndex.append(other)`. Preserves the index name when both
/// operands share it; otherwise pandas drops the name.
#[must_use]
pub fn append(&self, other: &Self) -> Self {
let mut nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
})
.collect();
nanos.extend(other.index.labels().iter().filter_map(|label| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
}));
let mut out = Self::new(nanos);
if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
out = out.set_name(name);
}
out
}
/// Minimum non-NAT label, matching `pd.TimedeltaIndex.min()`.
#[must_use]
pub fn min(&self) -> Option<i64> {
self.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n),
_ => None,
})
.min()
}
/// Shift each label by `periods` units of `freq_nanos`, matching
/// `pd.TimedeltaIndex.shift(periods, freq)`. NAT propagates as NAT.
#[must_use]
pub fn shift(&self, periods: i64, freq_nanos: i64) -> Self {
let delta = periods.saturating_mul(freq_nanos);
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => n.saturating_add(delta),
_ => Timedelta::NAT,
})
.collect();
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
out
}
/// Positional first differences, matching `pd.TimedeltaIndex.diff()`.
/// NAT inputs propagate and signed `periods` follows pandas' lookup
/// direction.
#[must_use]
pub fn diff(&self, periods: i64) -> Self {
let labels = self.index.labels();
optional_diffs_to_timedelta_index(
positional_diff(labels.len(), periods, |current, previous| {
match (&labels[current], &labels[previous]) {
(
IndexLabel::Timedelta64(current_nanos),
IndexLabel::Timedelta64(previous_nanos),
) if *current_nanos != Timedelta::NAT && *previous_nanos != Timedelta::NAT => {
current_nanos.checked_sub(*previous_nanos)
}
_ => None,
}
}),
self.name(),
)
}
fn round_fixed_freq(&self, freq: &str, mode: TemporalRoundMode) -> Result<Self, IndexError> {
let unit_nanos = parse_fixed_temporal_freq(freq, "TimedeltaIndex rounding")?;
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => {
round_nanos_to_unit(*n, unit_nanos, mode)
}
_ => Timedelta::NAT,
})
.collect();
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
/// Round timedeltas down to a fixed pandas frequency.
pub fn floor(&self, freq: &str) -> Result<Self, IndexError> {
self.round_fixed_freq(freq, TemporalRoundMode::Floor)
}
/// Round timedeltas up to a fixed pandas frequency.
pub fn ceil(&self, freq: &str) -> Result<Self, IndexError> {
self.round_fixed_freq(freq, TemporalRoundMode::Ceil)
}
/// Round timedeltas to the nearest fixed pandas frequency, using half-even ties.
pub fn round(&self, freq: &str) -> Result<Self, IndexError> {
self.round_fixed_freq(freq, TemporalRoundMode::Round)
}
/// Average non-NAT label as nanosecond duration, matching
/// `pd.TimedeltaIndex.mean()`. Empty / all-NAT returns `None`.
#[must_use]
pub fn mean(&self) -> Option<i64> {
let mut total: i128 = 0;
let mut count: i128 = 0;
for label in self.index.labels() {
if let IndexLabel::Timedelta64(n) = label
&& *n != Timedelta::NAT
{
total += i128::from(*n);
count += 1;
}
}
if count == 0 {
return None;
}
i64::try_from(total / count).ok()
}
/// Sum of non-NAT labels as nanosecond duration, matching
/// `pd.TimedeltaIndex.sum()`. Returns `Some(0)` for empty inputs to
/// match pandas. Sum is computed in `i128` to avoid overflow before
/// narrowing back to `i64`.
#[must_use]
pub fn sum(&self) -> Option<i64> {
let mut total: i128 = 0;
for label in self.index.labels() {
if let IndexLabel::Timedelta64(n) = label
&& *n != Timedelta::NAT
{
total += i128::from(*n);
}
}
i64::try_from(total).ok()
}
/// Sample variance over non-NAT labels in nanoseconds-squared,
/// matching `pd.TimedeltaIndex.var(ddof=1)`. Returns `None` for
/// fewer than two non-NAT entries.
#[must_use]
pub fn var(&self) -> Option<f64> {
let nanos: Vec<f64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n as f64),
_ => None,
})
.collect();
if nanos.len() < 2 {
return None;
}
let mean = nanos.iter().sum::<f64>() / nanos.len() as f64;
Some(nanos.iter().map(|n| (n - mean).powi(2)).sum::<f64>() / (nanos.len() as f64 - 1.0))
}
/// Sample standard deviation of non-NAT labels in nanoseconds,
/// matching `pd.TimedeltaIndex.std(ddof=1)`. Returns `None` for
/// fewer than two non-NAT entries.
#[must_use]
pub fn std(&self) -> Option<i64> {
let nanos: Vec<f64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n as f64),
_ => None,
})
.collect();
if nanos.len() < 2 {
return None;
}
let mean = nanos.iter().sum::<f64>() / nanos.len() as f64;
let var =
nanos.iter().map(|n| (n - mean).powi(2)).sum::<f64>() / (nanos.len() as f64 - 1.0);
Some(var.sqrt() as i64)
}
/// Median non-NAT label, matching `pd.TimedeltaIndex.median()`.
#[must_use]
pub fn median(&self) -> Option<i64> {
let mut nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n),
_ => None,
})
.collect();
if nanos.is_empty() {
return None;
}
nanos.sort_unstable();
let mid = nanos.len() / 2;
if nanos.len() % 2 == 1 {
Some(nanos[mid])
} else {
let total = i128::from(nanos[mid - 1]) + i128::from(nanos[mid]);
i64::try_from(total / 2).ok()
}
}
/// Maximum non-NAT label, matching `pd.TimedeltaIndex.max()`.
#[must_use]
pub fn max(&self) -> Option<i64> {
self.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) if *n != Timedelta::NAT => Some(*n),
_ => None,
})
.max()
}
/// Labels present in both indexes, matching
/// `pd.TimedeltaIndex.intersection(other)`.
#[must_use]
pub fn intersection(&self, other: &Self) -> Self {
let other_set: FxHashSet<i64> = other
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
})
.collect();
let mut seen = FxHashSet::<i64>::default();
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) if other_set.contains(n) && seen.insert(*n) => Some(*n),
_ => None,
})
.collect();
let mut out = Self::new(nanos);
if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
out = out.set_name(name);
}
out
}
/// Labels from self followed by labels from other not already present,
/// matching `pd.TimedeltaIndex.union(other)`.
#[must_use]
pub fn union(&self, other: &Self) -> Self {
let mut seen = FxHashSet::<i64>::default();
let mut nanos: Vec<i64> = Vec::new();
for label in self
.index
.labels()
.iter()
.chain(other.index.labels().iter())
{
if let IndexLabel::Timedelta64(n) = label
&& seen.insert(*n)
{
nanos.push(*n);
}
}
let mut out = Self::new(nanos);
if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
out = out.set_name(name);
}
out
}
/// Labels in self not in other, matching
/// `pd.TimedeltaIndex.difference(other)`.
#[must_use]
pub fn difference(&self, other: &Self) -> Self {
let other_set: FxHashSet<i64> = other
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
})
.collect();
let mut seen = FxHashSet::<i64>::default();
let nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) if !other_set.contains(n) && seen.insert(*n) => Some(*n),
_ => None,
})
.collect();
let mut out = Self::new(nanos);
// Per br-frankenpandas-6r1lq: difference preserves self.name only
// (asymmetric op).
if let Some(name) = self.name() {
out = out.set_name(name);
}
out
}
/// Labels in either but not both, matching
/// `pd.TimedeltaIndex.symmetric_difference(other)`.
#[must_use]
pub fn symmetric_difference(&self, other: &Self) -> Self {
let self_set: FxHashSet<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
})
.collect();
let other_set: FxHashSet<i64> = other
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
})
.collect();
let mut seen = FxHashSet::<i64>::default();
let mut nanos: Vec<i64> = Vec::new();
for label in self.index.labels() {
if let IndexLabel::Timedelta64(n) = label
&& !other_set.contains(n)
&& seen.insert(*n)
{
nanos.push(*n);
}
}
for label in other.index.labels() {
if let IndexLabel::Timedelta64(n) = label
&& !self_set.contains(n)
&& seen.insert(*n)
{
nanos.push(*n);
}
}
let mut out = Self::new(nanos);
if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
out = out.set_name(name);
}
out
}
/// Sort labels ascending, matching `pd.TimedeltaIndex.sort_values()`.
/// NAT sorts first (Timedelta::NAT sentinel) to match pandas
/// `na_position='first'` default.
#[must_use]
pub fn sort_values(&self) -> Self {
let mut nanos: Vec<i64> = self
.index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
})
.collect();
nanos.sort_unstable();
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
out
}
/// Alias for `sort_values`, matching `pd.TimedeltaIndex.sort()`.
#[must_use]
pub fn sort(&self) -> Self {
self.sort_values()
}
/// Remove the label at the given position, matching
/// `pd.TimedeltaIndex.delete(loc)`.
pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
let labels = self.index.labels();
if loc >= labels.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: labels.len(),
});
}
let nanos: Vec<i64> = labels
.iter()
.enumerate()
.filter(|(i, _)| *i != loc)
.filter_map(|(_, label)| match label {
IndexLabel::Timedelta64(n) => Some(*n),
_ => None,
})
.collect();
let mut out = Self::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
}
/// Public pandas-style period index wrapper.
///
/// `Period` already lives in `fp-types`; this wrapper gives callers a typed
/// index container while DataFrame integration can still materialize through
/// string labels until a dedicated Period `IndexLabel` variant lands.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeriodIndex {
values: Vec<Period>,
name: Option<LabelName>,
/// The freq the index was built at, which an empty one has no period to
/// show (period_range(periods=0) was period[unknown];
/// br-frankenpandas-ce86r). A non-empty index's is its periods'.
#[serde(default)]
built_freq: Option<PeriodFreq>,
}
/// Equal periods, name and freq - the periods' own, or for empty indexes
/// the freq each was built at - whichever constructor made them.
impl PartialEq for PeriodIndex {
fn eq(&self, other: &Self) -> bool {
self.values == other.values && self.name == other.name && self.freq() == other.freq()
}
}
impl Eq for PeriodIndex {}
impl PeriodIndex {
#[must_use]
pub fn new(values: Vec<Period>) -> Self {
Self {
values,
name: None,
built_freq: None,
}
}
/// Construct a PeriodIndex from raw ordinal values and a frequency,
/// matching `pd.PeriodIndex.from_ordinals(ordinals, freq)`.
#[must_use]
pub fn from_ordinals(ordinals: &[i64], freq: PeriodFreq) -> Self {
let values: Vec<Period> = ordinals
.iter()
.map(|&ordinal| Period::new(ordinal, freq))
.collect();
Self {
values,
name: None,
built_freq: Some(freq),
}
}
pub fn from_fields(fields: PeriodFields<'_>) -> Result<Self, IndexError> {
validate_period_fields(&fields)?;
let freq = period_fields_freq(&fields)?;
let values = (0..fields.year.len())
.map(|position| period_from_fields_at(&fields, freq, position))
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
values,
name: None,
built_freq: Some(freq),
})
}
#[must_use]
pub fn from_range(start: Period, periods: usize) -> Self {
Self {
values: fp_types::period_range(start, periods),
name: None,
built_freq: Some(start.freq),
}
}
#[must_use]
pub fn values(&self) -> &[Period] {
&self.values
}
#[must_use]
pub fn len(&self) -> usize {
self.values.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
#[must_use]
pub fn name(&self) -> Option<&LabelName> {
self.name.as_ref()
}
#[must_use]
pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
let mut out = self.clone();
out.name = Some(name.into());
out
}
#[must_use]
pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
let mut out = self.clone();
out.name = name.map(Into::into);
out
}
#[must_use]
pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
self.set_names(name)
}
#[must_use]
pub fn names(&self) -> Vec<Option<String>> {
vec![self.name.clone().map(String::from)]
}
#[must_use]
pub fn copy(&self) -> Self {
self.clone()
}
#[must_use]
pub fn shape(&self) -> (usize,) {
(self.len(),)
}
#[must_use]
pub fn size(&self) -> usize {
self.len()
}
#[must_use]
pub fn empty(&self) -> bool {
self.is_empty()
}
#[must_use]
pub fn dtype(&self) -> String {
self.freq().map_or_else(
|| "period[unknown]".to_owned(),
|freq| format!("period[{freq}]"),
)
}
#[must_use]
pub fn dtypes(&self) -> Vec<String> {
vec![self.dtype()]
}
/// Whether any period label is missing (NaT, [`Period::is_nat`]; this
/// was always false, br-frankenpandas-u6p7i).
#[must_use]
pub fn hasnans(&self) -> bool {
self.values.iter().any(Period::is_nat)
}
/// Missing-value mask, matching `pd.PeriodIndex.isna()`.
#[must_use]
pub fn isna(&self) -> Vec<bool> {
self.values.iter().map(Period::is_nat).collect()
}
/// Alias for [`isna`](Self::isna), matching `pd.PeriodIndex.isnull()`.
#[must_use]
pub fn isnull(&self) -> Vec<bool> {
self.isna()
}
/// Non-missing mask, matching `pd.PeriodIndex.notna()`.
#[must_use]
pub fn notna(&self) -> Vec<bool> {
self.values.iter().map(|period| !period.is_nat()).collect()
}
/// Alias for [`notna`](Self::notna), matching `pd.PeriodIndex.notnull()`.
#[must_use]
pub fn notnull(&self) -> Vec<bool> {
self.notna()
}
/// Drop missing labels, matching `pd.PeriodIndex.dropna()`.
///
/// With no native Period NaT sentinel, this is a name-preserving clone.
#[must_use]
pub fn dropna(&self) -> Self {
self.clone()
}
#[must_use]
pub fn memory_usage(&self, deep: bool) -> usize {
let name_bytes = if deep {
self.name.as_ref().map_or(0, |name| name.len())
} else {
0
};
fixed_width_label_memory_usage(self.values.len(), std::mem::size_of::<Period>())
.saturating_add(name_bytes)
}
#[must_use]
pub fn nbytes(&self) -> usize {
self.memory_usage(false)
}
fn compare_periods(left: &Period, right: &Period) -> std::cmp::Ordering {
left.cmp_same_freq(right).unwrap_or_else(|| {
left.freq
.cmp(&right.freq)
.then(left.ordinal.cmp(&right.ordinal))
})
}
#[must_use]
pub fn is_unique(&self) -> bool {
let mut direction = std::cmp::Ordering::Equal;
for pair in self.values.windows(2) {
let ordering = Self::compare_periods(&pair[0], &pair[1]);
if ordering.is_eq() {
return false;
}
if direction.is_eq() {
direction = ordering;
} else if ordering != direction {
let unique: FxHashSet<&Period> = self.values.iter().collect();
return unique.len() == self.values.len();
}
}
true
}
#[must_use]
pub fn has_duplicates(&self) -> bool {
!self.is_unique()
}
#[must_use]
pub fn is_monotonic_increasing(&self) -> bool {
self.values
.windows(2)
.all(|window| Self::compare_periods(&window[0], &window[1]).is_le())
}
#[must_use]
pub fn is_monotonic(&self) -> bool {
self.is_monotonic_increasing()
}
#[must_use]
pub fn is_monotonic_decreasing(&self) -> bool {
self.values
.windows(2)
.all(|window| Self::compare_periods(&window[0], &window[1]).is_ge())
}
#[must_use]
pub fn nunique(&self) -> usize {
self.values.iter().collect::<FxHashSet<_>>().len()
}
#[must_use]
pub fn ndim(&self) -> usize {
1
}
pub fn item(&self) -> Result<Period, IndexError> {
if self.values.len() == 1 {
Ok(self.values[0])
} else {
Err(IndexError::InvalidArgument(format!(
"item requires exactly one label, got {}",
self.values.len()
)))
}
}
#[must_use]
pub fn is_(&self, other: &Self) -> bool {
std::ptr::eq(self, other)
}
#[must_use]
pub fn equals(&self, other: &Self) -> bool {
self.values == other.values
}
#[must_use]
pub fn identical(&self, other: &Self) -> bool {
self.equals(other) && self.name == other.name
}
#[must_use]
pub fn holds_integer(&self) -> bool {
false
}
#[must_use]
pub fn inferred_type(&self) -> &'static str {
"period"
}
#[must_use]
pub fn is_boolean(&self) -> bool {
false
}
#[must_use]
pub fn is_categorical(&self) -> bool {
false
}
#[must_use]
pub fn is_floating(&self) -> bool {
false
}
#[must_use]
pub fn is_integer(&self) -> bool {
false
}
#[must_use]
pub fn is_interval(&self) -> bool {
false
}
#[must_use]
pub fn is_numeric(&self) -> bool {
false
}
#[must_use]
pub fn is_object(&self) -> bool {
false
}
#[must_use]
pub fn freq(&self) -> Option<PeriodFreq> {
self.values
.first()
.map(|period| period.freq)
.or(self.built_freq)
}
/// Raw period ordinals, matching `pd.PeriodIndex.asi8`.
#[must_use]
pub fn asi8(&self) -> Vec<i64> {
self.values.iter().map(|period| period.ordinal).collect()
}
#[must_use]
pub fn to_list(&self) -> Vec<Period> {
self.values.clone()
}
#[must_use]
pub fn tolist(&self) -> Vec<Period> {
self.to_list()
}
#[must_use]
pub fn to_numpy(&self) -> Vec<Period> {
self.values.clone()
}
#[must_use]
pub fn array(&self) -> Vec<Period> {
self.values.clone()
}
#[must_use]
pub fn to_index(&self) -> Index {
// Period labels, so a Series / DataFrame on this index keeps it (it
// was their text; 45fzr).
Index::new(
self.values
.iter()
.copied()
.map(IndexLabel::Period)
.collect(),
)
.set_names(self.name.clone())
}
/// The PeriodIndex `index` holds: its labels periods of one freq (NaT
/// among them), or None for any other label (45fzr).
#[must_use]
pub fn from_index(index: &Index) -> Option<Self> {
let mut freq = None;
let values = index
.labels()
.iter()
.map(|label| match label {
IndexLabel::Period(period) if freq.is_none_or(|freq| freq == period.freq) => {
freq = Some(period.freq);
Some(*period)
}
_ => None,
})
.collect::<Option<Vec<_>>>()?;
Some(Self {
values,
name: index.name().cloned(),
built_freq: freq,
})
}
/// First-seen unique periods, matching `pd.PeriodIndex.unique()`.
/// Preserves the index name.
#[must_use]
pub fn unique(&self) -> Self {
let mut seen = FxHashSet::<&Period>::default();
let mut uniques = Vec::<Period>::new();
for period in &self.values {
if seen.insert(period) {
uniques.push(*period);
}
}
Self {
values: uniques,
name: self.name.clone(),
built_freq: self.built_freq,
}
}
/// Per-position duplicate mask, matching
/// `pd.PeriodIndex.duplicated(keep)`.
#[must_use]
pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
let mut result = vec![false; self.values.len()];
match keep {
DuplicateKeep::First => {
let mut seen = FxHashSet::<&Period>::default();
for (i, period) in self.values.iter().enumerate() {
if !seen.insert(period) {
result[i] = true;
}
}
}
DuplicateKeep::Last => {
let mut seen = FxHashSet::<&Period>::default();
for (i, period) in self.values.iter().enumerate().rev() {
if !seen.insert(period) {
result[i] = true;
}
}
}
DuplicateKeep::None => {
let mut counts = FxHashMap::<&Period, usize>::default();
for period in &self.values {
*counts.entry(period).or_insert(0) += 1;
}
for (i, period) in self.values.iter().enumerate() {
if counts.get(period).copied().unwrap_or(0) > 1 {
result[i] = true;
}
}
}
}
result
}
/// Drop duplicate periods (keep first), matching
/// `pd.PeriodIndex.drop_duplicates()`.
#[must_use]
pub fn drop_duplicates(&self) -> Self {
self.unique()
}
/// Value counts, matching `pd.PeriodIndex.value_counts()`. Pandas
/// sorts descending by count.
#[must_use]
pub fn value_counts(&self) -> Vec<(Period, usize)> {
let mut order = Vec::<&Period>::new();
let mut counts = FxHashMap::<&Period, usize>::default();
for period in &self.values {
let entry = counts.entry(period).or_insert_with(|| {
order.push(period);
0
});
*entry += 1;
}
let mut pairs: Vec<(Period, usize)> = order.iter().map(|p| (**p, counts[*p])).collect();
pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
pairs
}
/// Pick periods at the given positions, matching
/// `pd.PeriodIndex.take()`. Out-of-bounds positions raise
/// [`IndexError::OutOfBounds`].
pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
for &p in positions {
if p >= self.values.len() {
return Err(IndexError::OutOfBounds {
position: p,
length: self.values.len(),
});
}
}
let taken: Vec<Period> = positions.iter().map(|&p| self.values[p]).collect();
Ok(Self {
values: taken,
name: self.name.clone(),
built_freq: self.freq(),
})
}
/// Repeat each period `repeats` times, matching
/// `pd.PeriodIndex.repeat()`.
#[must_use]
pub fn repeat(&self, repeats: usize) -> Self {
let mut out = Vec::with_capacity(repeat_output_capacity(self.values.len(), repeats));
for &period in &self.values {
for _ in 0..repeats {
out.push(period);
}
}
Self {
values: out,
name: self.name.clone(),
built_freq: self.freq(),
}
}
/// Positional first differences in period-frequency units.
///
/// Pandas returns frequency offset objects for `PeriodIndex.diff()`. The
/// Rust surface exposes the same semantic payload as ordinal deltas while
/// preserving null slots for positions without a comparison partner or
/// mixed-frequency pairs.
#[must_use]
pub fn diff(&self, periods: i64) -> Vec<Option<i64>> {
positional_diff(self.values.len(), periods, |current, previous| {
self.values[current].diff(&self.values[previous])
})
}
/// Convert periods to a new frequency using pandas' default end boundary.
///
/// Matches `pd.PeriodIndex.asfreq(freq)` for supported target frequencies.
pub fn asfreq(&self, freq: &str) -> Result<Self, IndexError> {
self.asfreq_with_how(freq, "end")
}
/// Convert periods to a new frequency at the requested boundary.
///
/// Supported `how` values mirror pandas' common aliases:
/// `start` / `s` / `begin` and `end` / `e` / `finish`.
pub fn asfreq_with_how(&self, freq: &str, how: &str) -> Result<Self, IndexError> {
let target_freq = PeriodFreq::parse(freq).ok_or_else(|| {
IndexError::InvalidArgument(format!("asfreq: unsupported frequency '{freq}'"))
})?;
let boundary = parse_period_boundary_how(how, "asfreq")?;
let values = self
.values
.iter()
.copied()
.map(|period| {
// NaT stays NaT at the new frequency.
if period.ordinal == i64::MIN {
return Ok(Period::new(i64::MIN, target_freq));
}
let nanos = period_boundary_nanos(period, boundary)?;
datetime_period_ordinal_at_boundary(nanos, target_freq, boundary)
.map(|ordinal| Period::new(ordinal, target_freq))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
values,
name: self.name.clone(),
built_freq: Some(target_freq),
})
}
fn to_timestamp_boundary(&self, boundary: PeriodBoundary) -> Result<DatetimeIndex, IndexError> {
let nanos = self
.values
.iter()
.copied()
.map(|period| period_boundary_nanos(period, boundary))
.collect::<Result<Vec<_>, _>>()?;
let mut out = DatetimeIndex::new(nanos);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
/// Timestamp at each period's start boundary.
///
/// Matches `pd.PeriodIndex.start_time`.
pub fn start_time(&self) -> Result<DatetimeIndex, IndexError> {
self.to_timestamp_boundary(PeriodBoundary::Start)
}
/// Timestamp at each period's inclusive end boundary.
///
/// Matches `pd.PeriodIndex.end_time`.
pub fn end_time(&self) -> Result<DatetimeIndex, IndexError> {
self.to_timestamp_boundary(PeriodBoundary::End)
}
/// Convert periods to timestamp labels at the requested boundary.
///
/// Supported `how` values mirror pandas' common aliases:
/// `start` / `s` / `begin` and `end` / `e` / `finish`.
pub fn to_timestamp(&self, how: &str) -> Result<DatetimeIndex, IndexError> {
match how.trim().to_ascii_lowercase().as_str() {
"" | "s" | "start" | "begin" | "b" => self.start_time(),
"e" | "end" | "finish" => self.end_time(),
other => Err(IndexError::InvalidArgument(format!(
"to_timestamp how must be 'start' or 'end', got {other:?}"
))),
}
}
/// Fiscal year for each period's ending boundary.
///
/// For the currently supported unanchored frequencies this is the
/// calendar year of `end_time`, matching pandas' `PeriodIndex.qyear`.
pub fn qyear(&self) -> Result<Vec<i32>, IndexError> {
self.values
.iter()
.copied()
.map(period_qyear)
.collect::<Result<Vec<_>, _>>()
}
// ── Per br-frankenpandas-qigpe: date-part accessors (19 methods) ──
/// The instant each period's fields read, as pandas' `get_date_info`
/// reads them: the period's END date at midnight - a month's day is its
/// last (31), a quarter's month its third, a week's year that of its
/// Sunday - and a sub-daily period its own start (the hour it is). NaT
/// stays NaT. The fields read the start (day 1, month 1 of a quarter).
fn field_instants(&self) -> Result<DatetimeIndex, IndexError> {
const DAY: i64 = 86_400_000_000_000;
let nanos = self
.values
.iter()
.map(|&period| {
if period.ordinal == i64::MIN {
return Ok(i64::MIN);
}
match period.freq {
PeriodFreq::Hourly
| PeriodFreq::Minutely
| PeriodFreq::Secondly
| PeriodFreq::Milliseconds
| PeriodFreq::Microseconds
| PeriodFreq::Nanoseconds => period_start_nanos(period),
_ => period_end_nanos(period).map(|end| end - end.rem_euclid(DAY)),
}
})
.collect::<Result<Vec<_>, _>>()?;
Ok(DatetimeIndex::new(nanos))
}
/// Year component for each period, matching `pd.PeriodIndex.year`.
pub fn year(&self) -> Result<Vec<Option<i32>>, IndexError> {
Ok(self.field_instants()?.year())
}
/// Month component (1-12), matching `pd.PeriodIndex.month`.
pub fn month(&self) -> Result<Vec<Option<u32>>, IndexError> {
Ok(self.field_instants()?.month())
}
/// Day of month (1-31), matching `pd.PeriodIndex.day`.
pub fn day(&self) -> Result<Vec<Option<u32>>, IndexError> {
Ok(self.field_instants()?.day())
}
/// Hour (0-23), matching `pd.PeriodIndex.hour`.
pub fn hour(&self) -> Result<Vec<Option<u32>>, IndexError> {
Ok(self.field_instants()?.hour())
}
/// Minute (0-59), matching `pd.PeriodIndex.minute`.
pub fn minute(&self) -> Result<Vec<Option<u32>>, IndexError> {
Ok(self.field_instants()?.minute())
}
/// Second (0-59), matching `pd.PeriodIndex.second`.
pub fn second(&self) -> Result<Vec<Option<u32>>, IndexError> {
Ok(self.field_instants()?.second())
}
/// Quarter (1-4), matching `pd.PeriodIndex.quarter`: a quarterly
/// period's fiscal quarter (Q-JAN's 2025Q1 is quarter 1 though it ends
/// in April), any other the calendar quarter of its end date.
pub fn quarter(&self) -> Result<Vec<Option<u32>>, IndexError> {
let calendar = self.field_instants()?.quarter();
Ok(self
.values
.iter()
.zip(calendar)
.map(|(period, calendar)| match period.freq {
PeriodFreq::Quarterly(_) if period.ordinal != i64::MIN => {
u32::try_from(period.ordinal.rem_euclid(4) + 1).ok()
}
_ => calendar,
})
.collect())
}
/// Day of week (0=Monday, 6=Sunday), matching `pd.PeriodIndex.weekday`.
pub fn weekday(&self) -> Result<Vec<Option<u32>>, IndexError> {
Ok(self.field_instants()?.weekday())
}
/// Day of week (0=Monday, 6=Sunday), alias for weekday.
/// Matches `pd.PeriodIndex.dayofweek`.
pub fn dayofweek(&self) -> Result<Vec<Option<u32>>, IndexError> {
self.weekday()
}
/// Day of week (0=Monday, 6=Sunday), alias for weekday.
/// Matches `pd.PeriodIndex.day_of_week`.
pub fn day_of_week(&self) -> Result<Vec<Option<u32>>, IndexError> {
self.weekday()
}
/// Day of year (1-366), matching `pd.PeriodIndex.dayofyear`.
pub fn dayofyear(&self) -> Result<Vec<Option<u32>>, IndexError> {
Ok(self.field_instants()?.dayofyear())
}
/// Day of year (1-366), alias for dayofyear.
/// Matches `pd.PeriodIndex.day_of_year`.
pub fn day_of_year(&self) -> Result<Vec<Option<u32>>, IndexError> {
self.dayofyear()
}
/// Days in month (28-31), matching `pd.PeriodIndex.days_in_month`.
pub fn days_in_month(&self) -> Result<Vec<Option<u32>>, IndexError> {
Ok(self.field_instants()?.daysinmonth())
}
/// Days in month (28-31), alias for days_in_month.
/// Matches `pd.PeriodIndex.daysinmonth`.
pub fn daysinmonth(&self) -> Result<Vec<Option<u32>>, IndexError> {
self.days_in_month()
}
/// ISO week number (1-53), matching `pd.PeriodIndex.week`.
pub fn week(&self) -> Result<Vec<Option<u32>>, IndexError> {
Ok(self.field_instants()?.week())
}
/// ISO week number (1-53), alias for week.
/// Matches `pd.PeriodIndex.weekofyear`.
pub fn weekofyear(&self) -> Result<Vec<Option<u32>>, IndexError> {
self.week()
}
/// Whether year is a leap year, matching `pd.PeriodIndex.is_leap_year`.
pub fn is_leap_year(&self) -> Result<Vec<Option<bool>>, IndexError> {
Ok(self.field_instants()?.is_leap_year())
}
/// Frequency resolution string, matching `pd.PeriodIndex.resolution`.
///
/// `None` for an empty index, and also for the two frequencies whose pandas
/// offsets have no resolution to report -- see [`PeriodFreq::resolution`].
#[must_use]
pub fn resolution(&self) -> Option<&'static str> {
self.values.first().and_then(|p| p.freq.resolution())
}
/// Format each period as a string with strftime, matching `pd.PeriodIndex.strftime`.
pub fn strftime(&self, fmt: &str) -> Result<Vec<Option<String>>, IndexError> {
Ok(self.field_instants()?.strftime(fmt))
}
fn ensure_homogeneous_freq(&self) -> Result<Option<PeriodFreq>, IndexError> {
let mut iter = self.values.iter();
let Some(first) = iter.next() else {
return Ok(None);
};
for period in iter {
if period.freq != first.freq {
return Err(IndexError::InvalidArgument(format!(
"PeriodIndex has mixed frequencies: {:?} and {:?}",
first.freq, period.freq
)));
}
}
Ok(Some(first.freq))
}
fn ensure_compatible_freq(&self, other: &Self) -> Result<(), IndexError> {
if let (Some(left), Some(right)) = (self.values.first(), other.values.first())
&& left.freq != right.freq
{
return Err(IndexError::InvalidArgument(format!(
"set operation: incompatible frequencies {:?} vs {:?}",
left.freq, right.freq
)));
}
self.ensure_homogeneous_freq()?;
other.ensure_homogeneous_freq()?;
Ok(())
}
/// Periods present in both, matching
/// `pd.PeriodIndex.intersection(other)`. Mixed-freq rejects.
pub fn intersection(&self, other: &Self) -> Result<Self, IndexError> {
self.ensure_compatible_freq(other)?;
let other_set: FxHashSet<&Period> = other.values.iter().collect();
let mut seen = FxHashSet::<&Period>::default();
let values: Vec<Period> = self
.values
.iter()
.filter(|p| other_set.contains(p) && seen.insert(p))
.copied()
.collect();
Ok(Self {
values,
name: if self.name == other.name {
self.name.clone()
} else {
None
},
built_freq: self.freq(),
})
}
/// Self periods then other periods not seen, matching
/// `pd.PeriodIndex.union(other)`. Mixed-freq rejects.
pub fn union(&self, other: &Self) -> Result<Self, IndexError> {
self.ensure_compatible_freq(other)?;
let mut seen = FxHashSet::<Period>::default();
let values: Vec<Period> = self
.values
.iter()
.chain(other.values.iter())
.filter(|p| seen.insert(**p))
.copied()
.collect();
Ok(Self {
values,
name: if self.name == other.name {
self.name.clone()
} else {
None
},
built_freq: self.freq(),
})
}
/// Self periods not in other, matching
/// `pd.PeriodIndex.difference(other)`. Mixed-freq rejects.
pub fn difference(&self, other: &Self) -> Result<Self, IndexError> {
self.ensure_compatible_freq(other)?;
let other_set: FxHashSet<&Period> = other.values.iter().collect();
let mut seen = FxHashSet::<&Period>::default();
let values: Vec<Period> = self
.values
.iter()
.filter(|p| !other_set.contains(p) && seen.insert(p))
.copied()
.collect();
Ok(Self {
values,
name: if self.name == other.name {
self.name.clone()
} else {
None
},
built_freq: self.freq(),
})
}
/// Periods in either but not both, matching
/// `pd.PeriodIndex.symmetric_difference(other)`. Mixed-freq rejects.
pub fn symmetric_difference(&self, other: &Self) -> Result<Self, IndexError> {
self.ensure_compatible_freq(other)?;
let self_set: FxHashSet<&Period> = self.values.iter().collect();
let other_set: FxHashSet<&Period> = other.values.iter().collect();
let mut seen = FxHashSet::<Period>::default();
let mut values = Vec::<Period>::new();
for p in &self.values {
if !other_set.contains(p) && seen.insert(*p) {
values.push(*p);
}
}
for p in &other.values {
if !self_set.contains(p) && seen.insert(*p) {
values.push(*p);
}
}
Ok(Self {
values,
name: if self.name == other.name {
self.name.clone()
} else {
None
},
built_freq: self.freq(),
})
}
/// Sort periods by ordinal ascending, matching
/// `pd.PeriodIndex.sort_values()`. Mixed-frequency rejects.
pub fn sort_values(&self) -> Result<Self, IndexError> {
self.ensure_homogeneous_freq()?;
let mut periods = self.values.clone();
periods.sort_by_key(|period| period.ordinal);
Ok(Self {
values: periods,
name: self.name.clone(),
built_freq: self.freq(),
})
}
/// Alias for `sort_values`, matching `pd.PeriodIndex.sort()`.
pub fn sort(&self) -> Result<Self, IndexError> {
self.sort_values()
}
/// Position of the maximum ordinal, matching
/// `pd.PeriodIndex.argmax()`. Mixed-freq input rejects; empty
/// raises pandas-style "attempt to get argmax of an empty
/// sequence".
pub fn argmax(&self) -> Result<usize, IndexError> {
self.ensure_homogeneous_freq()?;
if self.values.is_empty() {
return Err(IndexError::InvalidArgument(
"attempt to get argmax of an empty sequence".to_owned(),
));
}
let mut best = 0;
for (i, period) in self.values.iter().enumerate().skip(1) {
if period.ordinal > self.values[best].ordinal {
best = i;
}
}
Ok(best)
}
/// Position of the minimum ordinal, matching
/// `pd.PeriodIndex.argmin()`. Mixed-freq input rejects; empty
/// raises pandas-style "attempt to get argmin of an empty
/// sequence".
pub fn argmin(&self) -> Result<usize, IndexError> {
self.ensure_homogeneous_freq()?;
if self.values.is_empty() {
return Err(IndexError::InvalidArgument(
"attempt to get argmin of an empty sequence".to_owned(),
));
}
let mut best = 0;
for (i, period) in self.values.iter().enumerate().skip(1) {
if period.ordinal < self.values[best].ordinal {
best = i;
}
}
Ok(best)
}
/// Positions that would sort the index by ordinal ascending,
/// matching `pd.PeriodIndex.argsort()`. Mixed-freq input rejects.
pub fn argsort(&self) -> Result<Vec<usize>, IndexError> {
self.ensure_homogeneous_freq()?;
let mut positions: Vec<usize> = (0..self.values.len()).collect();
positions.sort_by_key(|&i| self.values[i].ordinal);
Ok(positions)
}
/// Period with the mean ordinal, matching `pd.PeriodIndex.mean()`.
/// Mixed-frequency input rejects.
pub fn mean(&self) -> Result<Option<Period>, IndexError> {
let freq = match self.ensure_homogeneous_freq()? {
Some(f) => f,
None => return Ok(None),
};
let total: i128 = self.values.iter().map(|p| i128::from(p.ordinal)).sum();
let count = self.values.len() as i128;
let avg = i64::try_from(total / count)
.map_err(|_| IndexError::InvalidArgument("mean: ordinal overflow".to_owned()))?;
Ok(Some(Period::new(avg, freq)))
}
/// Period with the median ordinal.
///
/// ⚠️ `pd.PeriodIndex.median()` does NOT exist (measured 2.2.3:
/// `AttributeError`). FP superset, not parity.
/// For an even-length subset, returns the period at floor(median) of
/// the two middle ordinals.
pub fn median(&self) -> Result<Option<Period>, IndexError> {
let freq = match self.ensure_homogeneous_freq()? {
Some(f) => f,
None => return Ok(None),
};
let mut ordinals: Vec<i64> = self.values.iter().map(|p| p.ordinal).collect();
ordinals.sort_unstable();
let mid = ordinals.len() / 2;
let median = if ordinals.len() % 2 == 1 {
ordinals[mid]
} else {
let total = i128::from(ordinals[mid - 1]) + i128::from(ordinals[mid]);
i64::try_from(total / 2)
.map_err(|_| IndexError::InvalidArgument("median: ordinal overflow".to_owned()))?
};
Ok(Some(Period::new(median, freq)))
}
/// Period with the smallest ordinal, matching `pd.PeriodIndex.min()`.
/// Mixed-frequency input rejects because pandas requires same-freq
/// comparisons; empty returns `Ok(None)` to mirror the pandas NaT result.
pub fn min(&self) -> Result<Option<Period>, IndexError> {
self.ensure_homogeneous_freq()?;
Ok(self
.values
.iter()
.copied()
.min_by_key(|period| period.ordinal))
}
/// Period with the largest ordinal, matching `pd.PeriodIndex.max()`.
pub fn max(&self) -> Result<Option<Period>, IndexError> {
self.ensure_homogeneous_freq()?;
Ok(self
.values
.iter()
.copied()
.max_by_key(|period| period.ordinal))
}
/// Binary-search insertion position, matching
/// `pd.PeriodIndex.searchsorted(value, side)`. Mixed-frequency lookups
/// reject because pandas requires same-freq comparisons. side must be
/// `"left"` or `"right"`.
pub fn searchsorted(&self, value: Period, side: &str) -> Result<usize, IndexError> {
if side != "left" && side != "right" {
return Err(IndexError::InvalidArgument(format!(
"searchsorted: side must be 'left' or 'right', got {side:?}"
)));
}
if let Some(first) = self.values.first()
&& first.freq != value.freq
{
return Err(IndexError::InvalidArgument(format!(
"searchsorted: needle frequency {:?} does not match index frequency {:?}",
value.freq, first.freq
)));
}
let mut lo = 0usize;
let mut hi = self.values.len();
while lo < hi {
let mid = lo + (hi - lo) / 2;
let cmp = self.values[mid].ordinal.cmp(&value.ordinal);
use std::cmp::Ordering;
let go_right = matches!(
(cmp, side),
(Ordering::Less, _) | (Ordering::Equal, "right")
);
if go_right {
lo = mid + 1;
} else {
hi = mid;
}
}
Ok(lo)
}
/// Half-open positional range for a period slice, matching
/// `pd.PeriodIndex.slice_indexer(start, end)`.
pub fn slice_indexer(
&self,
start: Period,
end: Period,
) -> Result<std::ops::Range<usize>, IndexError> {
let (left, right) = self.slice_locs(start, end)?;
Ok(left..right)
}
/// Find positions of `[start, end]` for a period slice, matching
/// `pd.PeriodIndex.slice_locs(start, end)`. Requires the index to
/// be sorted ascending and the start/end periods to share its
/// frequency.
pub fn slice_locs(&self, start: Period, end: Period) -> Result<(usize, usize), IndexError> {
if !self.is_monotonic_increasing() {
return Err(IndexError::InvalidArgument(
"slice_locs requires a monotonic increasing PeriodIndex".to_owned(),
));
}
let left = self.searchsorted(start, "left")?;
let right = self.searchsorted(end, "right")?;
Ok((left, right))
}
/// First position of `period`, matching
/// `pd.PeriodIndex.get_loc(period)`.
pub fn get_loc(&self, period: Period) -> Result<usize, IndexError> {
self.values
.iter()
.position(|p| *p == period)
.ok_or_else(|| {
IndexError::InvalidArgument(format!("get_loc: period {period} not in PeriodIndex"))
})
}
/// Set the index name, matching `pd.PeriodIndex.rename(name)`.
#[must_use]
pub fn rename(&self, name: &str) -> Self {
self.set_name(name)
}
/// Reindex against `target`, matching
/// `pd.PeriodIndex.reindex(target)`.
#[must_use]
pub fn reindex(&self, target: &Self) -> (Self, Vec<isize>) {
let indexer = self.get_indexer(target.values());
(target.clone(), indexer)
}
/// Locate every position matching each target, matching
/// `pd.PeriodIndex.get_indexer_non_unique(targets)`.
#[must_use]
pub fn get_indexer_non_unique(&self, targets: &[Period]) -> (Vec<isize>, Vec<usize>) {
let mut by_value = FxHashMap::<Period, Vec<usize>>::default();
for (i, period) in self.values.iter().enumerate() {
by_value.entry(*period).or_default().push(i);
}
let mut positions = Vec::<isize>::new();
let mut missing = Vec::<usize>::new();
for (idx, target) in targets.iter().enumerate() {
if let Some(matches) = by_value.get(target) {
positions.extend(
matches
.iter()
.map(|p| isize::try_from(*p).unwrap_or(isize::MAX)),
);
} else {
positions.push(-1);
missing.push(idx);
}
}
(positions, missing)
}
/// Alias for [`get_indexer`](Self::get_indexer), matching
/// `pd.PeriodIndex.get_indexer_for(targets)`.
#[must_use]
pub fn get_indexer_for(&self, targets: &[Period]) -> Vec<isize> {
self.get_indexer(targets)
}
/// Locate each target period in the index, matching
/// `pd.PeriodIndex.get_indexer(targets)`. Returns `Vec<isize>`
/// where `-1` means "missing".
#[must_use]
pub fn get_indexer(&self, targets: &[Period]) -> Vec<isize> {
let mut positions = FxHashMap::<Period, isize>::default();
for (i, period) in self.values.iter().enumerate() {
positions
.entry(*period)
.or_insert_with(|| isize::try_from(i).unwrap_or(isize::MAX));
}
targets
.iter()
.map(|p| positions.get(p).copied().unwrap_or(-1))
.collect()
}
/// Replace positions where `cond` is `false` with `other`, matching
/// `pd.PeriodIndex.where(cond, other)`. The replacement period must
/// share the index frequency.
pub fn r#where(&self, cond: &[bool], other: Period) -> Result<Self, IndexError> {
if cond.len() != self.values.len() {
return Err(IndexError::LengthMismatch {
expected: self.values.len(),
actual: cond.len(),
context: "where: cond length must match index length".to_owned(),
});
}
if let Some(first) = self.values.first()
&& first.freq != other.freq
{
return Err(IndexError::InvalidArgument(format!(
"where: replacement frequency {:?} does not match index frequency {:?}",
other.freq, first.freq
)));
}
let values: Vec<Period> = self
.values
.iter()
.zip(cond.iter())
.map(|(period, &keep)| if keep { *period } else { other })
.collect();
Ok(Self {
values,
name: self.name.clone(),
built_freq: self.freq(),
})
}
/// Replace positions where `mask` is `true` with `value`, matching
/// `pd.PeriodIndex.putmask(mask, value)`.
pub fn putmask(&self, mask: &[bool], value: Period) -> Result<Self, IndexError> {
if mask.len() != self.values.len() {
return Err(IndexError::LengthMismatch {
expected: self.values.len(),
actual: mask.len(),
context: "putmask: mask length must match index length".to_owned(),
});
}
if let Some(first) = self.values.first()
&& first.freq != value.freq
{
return Err(IndexError::InvalidArgument(format!(
"putmask: replacement frequency {:?} does not match index frequency {:?}",
value.freq, first.freq
)));
}
let values: Vec<Period> = self
.values
.iter()
.zip(mask.iter())
.map(|(period, &replace)| if replace { value } else { *period })
.collect();
Ok(Self {
values,
name: self.name.clone(),
built_freq: self.freq(),
})
}
/// Insert `period` at position `loc`, matching
/// `pd.PeriodIndex.insert(loc, period)`.
pub fn insert(&self, loc: usize, period: Period) -> Result<Self, IndexError> {
if loc > self.values.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: self.values.len(),
});
}
let mut periods = self.values.clone();
periods.insert(loc, period);
Ok(Self {
values: periods,
name: self.name.clone(),
built_freq: self.freq(),
})
}
/// Shift each period by `n` units of its own frequency, matching
/// `pd.PeriodIndex.shift(periods)`. Mixed-frequency input rejects
/// via the existing ensure_homogeneous_freq guard.
pub fn shift(&self, n: i64) -> Result<Self, IndexError> {
self.ensure_homogeneous_freq()?;
let values: Vec<Period> = self.values.iter().map(|p| p.shift(n)).collect();
Ok(Self {
values,
name: self.name.clone(),
built_freq: self.freq(),
})
}
/// Period labels are already discrete; pandas PeriodIndex.round returns a clone.
#[must_use]
pub fn round(&self, _freq: &str) -> Self {
self.clone()
}
/// Whether period ordinals form a contiguous run, matching
/// `pd.PeriodIndex.is_full`. Empty and single-element indexes are
/// trivially full. Mixed-frequency input returns `false` because the
/// concept is undefined.
#[must_use]
pub fn is_full(&self) -> bool {
if self.values.len() <= 1 {
return true;
}
// Mixed-freq: not full.
let first_freq = self.values[0].freq;
if self.values.iter().any(|p| p.freq != first_freq) {
return false;
}
let mut sorted: Vec<i64> = self.values.iter().map(|p| p.ordinal).collect();
sorted.sort_unstable();
sorted.windows(2).all(|w| w[1] - w[0] == 1)
}
/// Stringify each period via Display, matching `pd.PeriodIndex.format()`.
#[must_use]
pub fn format(&self) -> Vec<String> {
self.values.iter().map(Period::to_string).collect()
}
/// Frequency alias, matching `pd.PeriodIndex.freqstr`. Returns `None`
/// for an empty index; otherwise the Display form of the freq.
#[must_use]
pub fn freqstr(&self) -> Option<String> {
self.freq().map(|f| f.to_string())
}
/// Inferred frequency.
///
/// ⚠️ `pd.PeriodIndex.inferred_freq` does NOT exist (measured 2.2.3:
/// `AttributeError`), so the behaviour once described here as pandas' was
/// never observed from pandas. `DatetimeIndex`/`TimedeltaIndex` DO have
/// `inferred_freq`; on a PeriodIndex the freq is carried by `.freq`, which
/// is mandatory, so there is nothing to infer. FP returns the freq when all
/// periods share it, otherwise `None`. Mixed
/// frequency is detected via `ensure_homogeneous_freq` (the same guard
/// used by min/max).
#[must_use]
pub fn inferred_freq(&self) -> Option<String> {
match self.ensure_homogeneous_freq() {
Ok(Some(freq)) => Some(freq.to_string()),
Ok(None) | Err(_) => None,
}
}
/// Convert to a flat [`Index`] of period strings, matching
/// `pd.PeriodIndex.to_flat_index()`.
#[must_use]
pub fn to_flat_index(&self) -> Index {
self.to_index()
}
/// String accessor for rendered period labels.
#[must_use]
pub fn r#str(&self) -> IndexStringAccessor<'_> {
IndexStringAccessor::owned(self.to_flat_index())
}
/// One-column row materialization, matching `pd.PeriodIndex.to_frame(index=False)`.
#[must_use]
pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
self.to_flat_index().to_frame()
}
/// Series-shaped materialization using period labels as both index and values.
#[must_use]
pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
self.to_flat_index().to_series()
}
/// Whether any period label coerces to true: the flat index's answer, a
/// NaT being missing there (pandas raises TypeError for either; 45fzr).
#[must_use]
pub fn any(&self) -> bool {
self.to_flat_index().any()
}
/// Whether all period labels coerce to true.
#[must_use]
pub fn all(&self) -> bool {
self.to_flat_index().all()
}
/// Get labels for a level. PeriodIndex is flat and only accepts level 0.
pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
self.to_flat_index().get_level_values(level)
}
/// Drop a level. PeriodIndex is flat, so removing its only level is invalid.
pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
self.to_flat_index().droplevel(level)
}
/// Group equal period labels into position buckets.
#[must_use]
pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
self.to_flat_index().groupby()
}
/// Apply a function to each period label, returning a flat Index.
#[must_use]
pub fn map<F>(&self, func: F) -> Index
where
F: Fn(&IndexLabel) -> IndexLabel,
{
self.to_flat_index().map(func)
}
/// Cast period labels to a pandas dtype string, returning a flat Index.
pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
match dtype {
"int" | "int64" => Ok(Index::from_i64(
self.values.iter().map(|period| period.ordinal).collect(),
)
.set_names(self.name())),
"datetime64[ns]" => Ok(Index::from_datetime64(
self.values
.iter()
.copied()
.map(period_start_nanos)
.collect::<Result<Vec<_>, _>>()?,
)
.set_names(self.name())),
_ => self.to_flat_index().astype(dtype),
}
}
/// Nearest preceding-or-equal period label lookup.
#[must_use]
pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
self.to_flat_index().asof(key)
}
/// Locate nearest preceding-or-equal period positions for each target label.
#[must_use]
pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
self.to_flat_index().asof_locs(where_index, mask)
}
/// Drop period labels, returning a flat Index.
#[must_use]
pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
self.to_flat_index().drop(labels_to_drop)
}
/// Join period labels with another flat Index.
pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
self.to_flat_index().join(other, how)
}
/// Sort period labels and return the positional sorter.
#[must_use]
pub fn sortlevel(&self) -> (Index, Vec<usize>) {
self.to_flat_index().sortlevel()
}
/// Returns a clone, matching `pd.PeriodIndex.view()`.
#[must_use]
pub fn view(&self) -> Self {
self.clone()
}
/// Identity transpose for a 1D index, matching
/// `pd.PeriodIndex.transpose()`.
#[must_use]
pub fn transpose(&self) -> Self {
self.clone()
}
/// Alias for `transpose`, matching `pd.PeriodIndex.T`.
#[allow(non_snake_case)]
#[must_use]
pub fn T(&self) -> Self {
self.transpose()
}
/// Flatten periods to a `Vec<Period>`, matching
/// `pd.PeriodIndex.ravel()`.
#[must_use]
pub fn ravel(&self) -> Vec<Period> {
self.values.clone()
}
/// Number of levels, matching `pd.PeriodIndex.nlevels`. Always `1`.
#[must_use]
pub fn nlevels(&self) -> usize {
1
}
/// Identity dtype-reinference for typed indexes, matching
/// `pd.PeriodIndex.infer_objects()`.
#[must_use]
pub fn infer_objects(&self) -> Self {
self.clone()
}
/// Per-position membership mask, matching `pd.PeriodIndex.isin(values)`.
#[must_use]
pub fn isin(&self, values: &[Period]) -> Vec<bool> {
let needle: FxHashSet<Period> = values.iter().copied().collect();
self.values.iter().map(|p| needle.contains(p)).collect()
}
/// Concatenate with another PeriodIndex, matching
/// `pd.PeriodIndex.append(other)`. Preserves the index name when both
/// operands share it; otherwise the name is dropped.
#[must_use]
pub fn append(&self, other: &Self) -> Self {
let mut periods = self.values.clone();
periods.extend_from_slice(&other.values);
let name = if self.name == other.name {
self.name.clone()
} else {
None
};
Self {
values: periods,
name,
built_freq: self.freq(),
}
}
/// Remove the period at the given position, matching
/// `pd.PeriodIndex.delete(loc)`.
pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
if loc >= self.values.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: self.values.len(),
});
}
let mut periods = self.values.clone();
periods.remove(loc);
Ok(Self {
values: periods,
name: self.name.clone(),
built_freq: self.freq(),
})
}
/// Factorize, matching `pd.PeriodIndex.factorize()`. Returns
/// `(codes, uniques)` with isize codes — Period currently has no
/// missing-value sentinel so all codes are non-negative.
#[must_use]
pub fn factorize(&self) -> (Vec<isize>, Self) {
let mut positions = FxHashMap::<&Period, isize>::default();
let mut uniques = Vec::<Period>::new();
let mut codes = Vec::with_capacity(self.values.len());
for period in &self.values {
if let Some(code) = positions.get(period) {
codes.push(*code);
} else {
let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
positions.insert(period, code);
uniques.push(*period);
codes.push(code);
}
}
(
codes,
Self {
values: uniques,
name: self.name.clone(),
built_freq: self.freq(),
},
)
}
}
/// Public pandas-style range index wrapper.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RangeIndex {
start: i64,
stop: i64,
step: i64,
name: Option<LabelName>,
}
/// Borrowed, lazily evaluated Int64 values of a [`RangeIndex`].
///
/// A `RangeIndex` is an affine sequence, so typed consumers can read its values
/// without first allocating an owned buffer. Use [`Self::to_vec`] only when an
/// owned list is actually required by the receiving API.
#[derive(Clone, Copy, Debug)]
pub struct RangeIndexValues<'a> {
index: &'a RangeIndex,
}
impl RangeIndexValues<'_> {
#[must_use]
pub fn len(&self) -> usize {
self.index.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.index.is_empty()
}
#[must_use]
pub fn get(&self, position: usize) -> Option<i64> {
(position < self.len()).then(|| self.index.value_at(position))
}
#[must_use]
pub fn iter(&self) -> RangeValuesIter {
let len = self.len();
// br-frankenpandas-3gsa7 made this view zero-boxing; it is still
// 0.112x against pandas at 100k because `RangeIndex::value_at` pays
// i128 arithmetic PER ELEMENT — an i128 multiply (no SIMD form on
// x86-64), an i128 add, and a checked narrow back to i64. The proof
// that none of that is needed already existed one function below as
// `i64_position_arithmetic_is_safe`, which establishes ONCE that
// `start + step * (len - 1)` fits in i64. Values are monotone in
// `position` for either sign of `step`, so every intermediate is
// bracketed by `start` and that endpoint and cannot overflow.
// Hoisting the check turns the body into pure i64 affine arithmetic.
RangeValuesIter {
start: self.index.start,
step: self.index.step,
head: 0,
tail: len,
i64_safe: self.index.i64_position_arithmetic_is_safe(len).is_some(),
}
}
#[must_use]
pub fn to_vec(&self) -> Vec<i64> {
self.iter().collect()
}
}
/// Affine iterator over a [`RangeIndex`]'s values.
///
/// `i64_safe` is decided once at construction. It is NOT a correctness switch:
/// both arms yield identical values, and the i128 arm remains a complete
/// implementation for ranges whose endpoint genuinely does not fit in i64.
/// Its only purpose is to let `fold`/`rfold` run a branch-free i64 loop that
/// LLVM can strength-reduce to repeated addition and vectorize.
#[derive(Clone, Copy, Debug)]
pub struct RangeValuesIter {
start: i64,
step: i64,
head: usize,
tail: usize,
i64_safe: bool,
}
impl RangeValuesIter {
#[inline]
fn value_at(&self, position: usize) -> i64 {
if self.i64_safe {
self.start
.wrapping_add(self.step.wrapping_mul(position as i64))
} else {
let value = i128::from(self.start) + (position as i128) * i128::from(self.step);
i64::try_from(value).expect("validated RangeIndex value bounds")
}
}
}
impl Iterator for RangeValuesIter {
type Item = i64;
#[inline]
fn next(&mut self) -> Option<i64> {
if self.head >= self.tail {
return None;
}
let value = self.value_at(self.head);
self.head += 1;
Some(value)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.tail - self.head;
(remaining, Some(remaining))
}
/// Overridden so the `i64_safe` branch is tested ONCE per fold rather than
/// once per element. This is the whole lever: the default `fold` routes
/// through `next()`, which keeps the test inside the loop and blocks
/// vectorisation.
#[inline]
fn fold<B, F>(self, init: B, mut f: F) -> B
where
F: FnMut(B, i64) -> B,
{
let mut acc = init;
if self.i64_safe {
let mut value = self
.start
.wrapping_add(self.step.wrapping_mul(self.head as i64));
for _ in self.head..self.tail {
acc = f(acc, value);
value = value.wrapping_add(self.step);
}
} else {
for position in self.head..self.tail {
acc = f(acc, self.value_at(position));
}
}
acc
}
}
impl DoubleEndedIterator for RangeValuesIter {
#[inline]
fn next_back(&mut self) -> Option<i64> {
if self.head >= self.tail {
return None;
}
self.tail -= 1;
Some(self.value_at(self.tail))
}
#[inline]
fn rfold<B, F>(self, init: B, mut f: F) -> B
where
F: FnMut(B, i64) -> B,
{
let mut acc = init;
if self.i64_safe && self.tail > self.head {
let mut value = self
.start
.wrapping_add(self.step.wrapping_mul((self.tail - 1) as i64));
for _ in self.head..self.tail {
acc = f(acc, value);
value = value.wrapping_sub(self.step);
}
} else {
for position in (self.head..self.tail).rev() {
acc = f(acc, self.value_at(position));
}
}
acc
}
}
impl ExactSizeIterator for RangeValuesIter {
#[inline]
fn len(&self) -> usize {
self.tail - self.head
}
}
impl std::iter::FusedIterator for RangeValuesIter {}
impl RangeIndex {
pub fn new(start: i64, stop: i64, step: i64) -> Result<Self, IndexError> {
if step == 0 {
return Err(IndexError::InvalidArgument(
"RangeIndex step must be non-zero".to_owned(),
));
}
Ok(Self {
start,
stop,
step,
name: None,
})
}
pub fn from_len(len: usize) -> Result<Self, IndexError> {
let stop = i64::try_from(len).map_err(|_| {
IndexError::InvalidArgument("RangeIndex length exceeds i64 range".to_owned())
})?;
Self::new(0, stop, 1)
}
#[must_use]
pub const fn start(&self) -> i64 {
self.start
}
#[must_use]
pub const fn stop(&self) -> i64 {
self.stop
}
#[must_use]
pub const fn step(&self) -> i64 {
self.step
}
#[must_use]
pub fn len(&self) -> usize {
let start = i128::from(self.start);
let stop = i128::from(self.stop);
let step = i128::from(self.step);
let len = if step > 0 {
if start >= stop {
0
} else {
(stop - start + step - 1) / step
}
} else if start <= stop {
0
} else {
let positive_step = -step;
(start - stop + positive_step - 1) / positive_step
};
usize::try_from(len).unwrap_or(usize::MAX)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[must_use]
pub fn name(&self) -> Option<&LabelName> {
self.name.as_ref()
}
#[must_use]
pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
let mut out = self.clone();
out.name = Some(name.into());
out
}
#[must_use]
pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
let mut out = self.clone();
out.name = name.map(Into::into);
out
}
#[must_use]
pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
self.set_names(name)
}
#[must_use]
pub fn names(&self) -> Vec<Option<String>> {
vec![self.name.clone().map(String::from)]
}
#[must_use]
pub fn copy(&self) -> Self {
self.clone()
}
#[must_use]
pub fn shape(&self) -> (usize,) {
(self.len(),)
}
#[must_use]
pub fn size(&self) -> usize {
self.len()
}
#[must_use]
pub fn empty(&self) -> bool {
self.is_empty()
}
#[must_use]
pub fn dtype(&self) -> &'static str {
"int64"
}
#[must_use]
pub fn dtypes(&self) -> Vec<&'static str> {
vec![self.dtype()]
}
#[must_use]
pub fn memory_usage(&self, _deep: bool) -> usize {
self.len().saturating_mul(std::mem::size_of::<i64>())
}
#[must_use]
pub fn nbytes(&self) -> usize {
self.memory_usage(false)
}
#[must_use]
pub fn is_unique(&self) -> bool {
true
}
#[must_use]
pub fn has_duplicates(&self) -> bool {
false
}
#[must_use]
pub fn is_monotonic_increasing(&self) -> bool {
self.len() <= 1 || self.step > 0
}
#[must_use]
pub fn is_monotonic(&self) -> bool {
self.is_monotonic_increasing()
}
#[must_use]
pub fn is_monotonic_decreasing(&self) -> bool {
self.len() <= 1 || self.step < 0
}
#[must_use]
pub fn nunique(&self) -> usize {
self.len()
}
#[must_use]
pub fn ndim(&self) -> usize {
1
}
pub fn item(&self) -> Result<i64, IndexError> {
if self.len() == 1 {
Ok(self.start)
} else {
Err(IndexError::InvalidArgument(format!(
"item requires exactly one label, got {}",
self.len()
)))
}
}
#[must_use]
pub fn is_(&self, other: &Self) -> bool {
std::ptr::eq(self, other)
}
#[must_use]
pub fn equals(&self, other: &Self) -> bool {
let len = self.len();
if len != other.len() {
return false;
}
match len {
0 => true,
1 => self.start == other.start,
_ => self.start == other.start && self.step == other.step,
}
}
#[must_use]
pub fn identical(&self, other: &Self) -> bool {
self.equals(other) && self.name == other.name
}
#[must_use]
pub fn holds_integer(&self) -> bool {
true
}
#[must_use]
pub fn inferred_type(&self) -> &'static str {
if self.is_empty() { "empty" } else { "integer" }
}
#[must_use]
pub fn is_boolean(&self) -> bool {
false
}
#[must_use]
pub fn is_categorical(&self) -> bool {
false
}
#[must_use]
pub fn is_floating(&self) -> bool {
false
}
#[must_use]
pub fn is_integer(&self) -> bool {
true
}
#[must_use]
pub fn is_interval(&self) -> bool {
false
}
#[must_use]
pub fn is_numeric(&self) -> bool {
true
}
#[must_use]
pub fn is_object(&self) -> bool {
false
}
#[must_use]
pub fn to_index(&self) -> Index {
Index::from_range(self.start, self.stop, self.step).set_names(self.name.as_deref())
}
#[must_use]
pub fn values(&self) -> RangeIndexValues<'_> {
RangeIndexValues { index: self }
}
fn value_at(&self, position: usize) -> i64 {
let value = i128::from(self.start) + (position as i128) * i128::from(self.step);
i64::try_from(value).expect("validated RangeIndex value bounds")
}
fn i64_position_arithmetic_is_safe(&self, len: usize) -> Option<()> {
if len == 0 {
return Some(());
}
let last_position = i64::try_from(len.checked_sub(1)?).ok()?;
let span = self.step.checked_mul(last_position)?;
self.start.checked_add(span)?;
Some(())
}
fn fast_i64_values_at_positions(&self, positions: &[usize], len: usize) -> Option<Vec<i64>> {
self.i64_position_arithmetic_is_safe(len)?;
let mut labels = Vec::with_capacity(positions.len());
for &position in positions {
if position >= len {
return None;
}
let position = i64::try_from(position).expect("prevalidated RangeIndex position");
labels.push(self.start + self.step * position);
}
Some(labels)
}
fn fast_i64_repeat_values(&self, len: usize, repeats: usize) -> Option<Vec<i64>> {
self.i64_position_arithmetic_is_safe(len)?;
let mut labels = Vec::with_capacity(repeat_output_capacity(len, repeats));
let mut value = self.start;
for position in 0..len {
match repeats {
0 => {}
1 => labels.push(value),
2 => {
labels.push(value);
labels.push(value);
}
_ => {
for _ in 0..repeats {
labels.push(value);
}
}
}
if position + 1 < len {
value += self.step;
}
}
Some(labels)
}
fn push_i64_position_range(
&self,
len: usize,
start: usize,
end: usize,
labels: &mut Vec<i64>,
) -> Option<()> {
if start > end || end > len {
return None;
}
self.i64_position_arithmetic_is_safe(len)?;
if start == end {
return Some(());
}
let start_position = i64::try_from(start).ok()?;
let span = self.step.checked_mul(start_position)?;
let mut value = self.start.checked_add(span)?;
for position in start..end {
labels.push(value);
if position + 1 < end {
value += self.step;
}
}
Some(())
}
fn i64_position_affine_run(
&self,
len: usize,
start: usize,
end: usize,
) -> Option<Int64AffineLabels> {
if start > end || end > len {
return None;
}
self.i64_position_arithmetic_is_safe(len)?;
let run_len = end - start;
let start_value = if run_len == 0 {
self.start
} else {
let start_position = i64::try_from(start).ok()?;
let span = self.step.checked_mul(start_position)?;
self.start.checked_add(span)?
};
Int64AffineLabels::new(start_value, self.step, run_len)
}
fn fast_i64_insert_values(&self, len: usize, loc: usize, value: i64) -> Option<Vec<i64>> {
let mut labels = Vec::with_capacity(insert_output_capacity(len));
self.push_i64_position_range(len, 0, loc, &mut labels)?;
labels.push(value);
self.push_i64_position_range(len, loc, len, &mut labels)?;
Some(labels)
}
fn fast_i64_append_index(&self, other: &Self, len: usize, other_len: usize) -> Option<Index> {
let first = self.i64_position_affine_run(len, 0, len)?;
let second = other.i64_position_affine_run(other_len, 0, other_len)?;
Index::new_int64_two_affine_runs(first, second)
}
fn fast_i64_append_values(
&self,
other: &Self,
len: usize,
other_len: usize,
) -> Option<Vec<i64>> {
let mut labels = Vec::with_capacity(combined_output_capacity(len, other_len));
self.push_i64_position_range(len, 0, len, &mut labels)?;
other.push_i64_position_range(other_len, 0, other_len, &mut labels)?;
Some(labels)
}
fn fast_i64_delete_index(&self, len: usize, loc: usize) -> Option<Index> {
let first = self.i64_position_affine_run(len, 0, loc)?;
let second = self.i64_position_affine_run(len, loc + 1, len)?;
Index::new_known_unique_int64_two_affine_runs(first, second)
}
fn fast_i64_delete_values(&self, len: usize, loc: usize) -> Option<Vec<i64>> {
let mut labels = Vec::with_capacity(len.saturating_sub(1));
self.push_i64_position_range(len, 0, loc, &mut labels)?;
self.push_i64_position_range(len, loc + 1, len, &mut labels)?;
Some(labels)
}
fn take_arithmetic_positions(&self, positions: &[usize], len: usize) -> Option<Index> {
// Single O(len) pass: verify constant position stride AND in-bounds. The
// result of an affine RangeIndex taken at an arithmetic position sequence
// is again affine (`label_step = step * position_step`), so this returns a
// lazy affine index in O(1) without the separate bounds-check loop + the
// per-element `value_at` gather the materializing fall-back pays — the
// dominant cost in the `range_index_take` hot loop. Any out-of-bounds or
// non-arithmetic positions return `None`, falling through to the
// materializing path which reports the precise out-of-bounds error.
let mut index = match positions {
[] => Index::new_known_unique_int64_affine_range(self.start, self.step, 0)?,
&[position] => {
if position >= len {
return None;
}
let first_label = self.value_at(position);
Index::new_known_unique_int64_affine_range(first_label, self.step, 1)?
}
&[first, second, ..] => {
if first >= len {
return None;
}
// `i64` (not `i128`) stride arithmetic: positions are valid indices
// `< len <= isize::MAX`, so pairwise differences fit `i64`; the
// `i64` windows scan autovectorizes where the `i128` form could not.
let position_step = second as i64 - first as i64;
if position_step == 0 {
return None;
}
if !positions
.windows(2)
.all(|w| w[1] as i64 - w[0] as i64 == position_step)
{
return None;
}
let last = *positions.last().expect("non-empty by match arm");
// Monotone sequence ⇒ all positions lie within `[min, max]`; a
// single endpoint bounds check covers the whole range.
if first.max(last) >= len {
return None;
}
let label_step = self.step.checked_mul(position_step)?;
let first_label = self.value_at(first);
Index::new_known_unique_int64_affine_range(
first_label,
label_step,
positions.len(),
)?
}
};
if let Some(name) = self.name() {
index = index.set_name(name);
}
Some(index)
}
fn affine_span_index(
&self,
first_position: usize,
len: usize,
name: Option<&LabelName>,
) -> Option<Index> {
let start = if len == 0 {
self.start
} else {
self.value_at(first_position)
};
let mut index = Index::new_known_unique_int64_affine_range(start, self.step, len)?;
if let Some(name) = name {
index = index.set_name(name);
}
Some(index)
}
fn matching_step_offset(&self, other: &Self) -> Option<i128> {
if self.step == 0 || self.step != other.step {
return None;
}
let delta = i128::from(other.start) - i128::from(self.start);
let step = i128::from(self.step);
(delta % step == 0).then_some(delta / step)
}
fn same_lattice_overlap_positions(&self, other: &Self) -> Option<Option<(usize, usize)>> {
let self_len = self.len();
let other_len = other.len();
if self_len == 0 || other_len == 0 {
return Some(None);
}
let other_start = self.matching_step_offset(other)?;
let other_end = other_start.checked_add(other_len as i128 - 1)?;
let first = other_start.max(0);
let last = other_end.min(self_len as i128 - 1);
if first > last {
return Some(None);
}
Some(Some((
usize::try_from(first).ok()?,
usize::try_from(last).ok()?,
)))
}
fn single_difference_span_positions(&self, other: &Self) -> Option<Option<(usize, usize)>> {
let self_len = self.len();
match self.same_lattice_overlap_positions(other)? {
None => Some((self_len > 0).then_some((0, self_len))),
Some((first, last)) => {
if first == 0 && last + 1 == self_len {
Some(None)
} else if first == 0 {
Some(Some((last + 1, self_len - last - 1)))
} else if last + 1 == self_len {
Some(Some((0, first)))
} else {
None
}
}
}
}
fn position_of_value(&self, value: i64) -> Option<usize> {
self.position_of_value_with_len(value, self.len())
}
fn position_of_value_with_len(&self, value: i64, len: usize) -> Option<usize> {
self.position_of_value_with_len_and_bounds(value, len, self.position_bounds_for_len(len))
}
fn position_of_value_with_len_and_bounds(
&self,
value: i64,
len: usize,
bounds: Option<(i64, i64)>,
) -> Option<usize> {
if self.step == 0 {
return None;
}
if len == 0 {
return None;
}
if let Some((lower, upper)) = bounds {
if value < lower || value > upper {
return None;
}
if let Some(offset) = value.checked_sub(self.start)
&& let Some(0) = offset.checked_rem(self.step)
&& let Some(position) = offset.checked_div(self.step)
&& position >= 0
{
let position = position as usize;
if position < len {
return Some(position);
}
}
return None;
}
let offset = i128::from(value) - i128::from(self.start);
let step = i128::from(self.step);
if offset % step != 0 {
return None;
}
let position = offset / step;
(position >= 0 && position < len as i128).then_some(position as usize)
}
fn position_bounds_for_len(&self, len: usize) -> Option<(i64, i64)> {
self.first_last_for_len(len)
.map(|(first, last)| (first.min(last), first.max(last)))
}
fn first_last_for_len(&self, len: usize) -> Option<(i64, i64)> {
if len == 0 {
return None;
}
let last_offset = len - 1;
let last = i128::from(self.start) + (last_offset as i128) * i128::from(self.step);
let last = i64::try_from(last).ok()?;
Some((self.start, last))
}
fn range_target_indexer(&self, target: &Self, source_len: usize) -> Option<Vec<isize>> {
let target_len = target.len();
if target_len == 0 {
return Some(Vec::new());
}
if source_len == 0 {
return Some(vec![-1; target_len]);
}
let source_step = i128::from(self.step);
let target_step = i128::from(target.step);
let first_offset = i128::from(target.start) - i128::from(self.start);
if target_step % source_step != 0 {
return None;
}
if first_offset % source_step != 0 {
return Some(vec![-1; target_len]);
}
let mut source_position = first_offset / source_step;
let source_position_step = target_step / source_step;
let source_len = source_len as i128;
let mut indexer = Vec::with_capacity(target_len);
for _ in 0..target_len {
if (0..source_len).contains(&source_position) {
indexer.push(source_position as isize);
} else {
indexer.push(-1);
}
source_position += source_position_step;
}
Some(indexer)
}
fn contains_value(&self, value: i64) -> bool {
self.position_of_value(value).is_some()
}
/// Positional first differences for RangeIndex values.
#[must_use]
pub fn diff(&self, periods: i64) -> Vec<Option<i64>> {
let len = self.len();
if len == 0 {
return Vec::new();
}
if periods == 0 {
return vec![Some(0); len];
}
let Ok(offset) = usize::try_from(periods.unsigned_abs()) else {
return vec![None; len];
};
if offset >= len {
return vec![None; len];
}
let diff = i128::from(self.step) * i128::from(periods);
let diff = i64::try_from(diff).ok();
let mut out = vec![None; len];
if periods > 0 {
out[offset..].fill(diff);
} else {
out[..len - offset].fill(diff);
}
out
}
#[must_use]
pub fn to_list(&self) -> Vec<i64> {
self.values().to_vec()
}
#[must_use]
pub fn tolist(&self) -> Vec<i64> {
self.values().to_vec()
}
#[must_use]
pub fn to_numpy(&self) -> Vec<i64> {
self.values().to_vec()
}
#[must_use]
pub fn array(&self) -> Vec<i64> {
self.values().to_vec()
}
/// Position of the maximum value, matching `pd.RangeIndex.argmax()`.
///
/// `step > 0` makes the last position the maximum; `step < 0` makes
/// position 0 the maximum. Empty ranges raise the same
/// `attempt to get argmax of an empty sequence` error pandas surfaces.
pub fn argmax(&self) -> Result<usize, IndexError> {
if self.is_empty() {
return Err(IndexError::InvalidArgument(
"attempt to get argmax of an empty sequence".to_owned(),
));
}
if self.step > 0 {
Ok(self.len() - 1)
} else {
Ok(0)
}
}
/// Position of the minimum value, matching `pd.RangeIndex.argmin()`.
pub fn argmin(&self) -> Result<usize, IndexError> {
if self.is_empty() {
return Err(IndexError::InvalidArgument(
"attempt to get argmin of an empty sequence".to_owned(),
));
}
if self.step > 0 {
Ok(0)
} else {
Ok(self.len() - 1)
}
}
/// Positions that would sort the index ascending, matching
/// `pd.RangeIndex.argsort()`.
#[must_use]
pub fn argsort(&self) -> Vec<usize> {
let len = self.len();
if self.step >= 0 {
(0..len).collect()
} else {
(0..len).rev().collect()
}
}
/// RangeIndex enforces uniqueness, so every position is reported as a
/// non-duplicate, matching `pd.RangeIndex.duplicated(keep=...)`.
#[must_use]
pub fn duplicated(&self, _keep: DuplicateKeep) -> Vec<bool> {
vec![false; self.len()]
}
/// Drop duplicates, matching `pd.RangeIndex.drop_duplicates()`.
/// Returns a clone because RangeIndex never has duplicates.
#[must_use]
pub fn drop_duplicates(&self) -> Self {
self.clone()
}
/// Per-position missingness mask, matching `pd.RangeIndex.isna()`.
/// Always all-false because RangeIndex is int64-typed.
#[must_use]
pub fn isna(&self) -> Vec<bool> {
vec![false; self.len()]
}
/// Alias for [`isna`](Self::isna), matching `pd.RangeIndex.isnull()`.
#[must_use]
pub fn isnull(&self) -> Vec<bool> {
self.isna()
}
/// Per-position non-missing mask, matching `pd.RangeIndex.notna()`.
#[must_use]
pub fn notna(&self) -> Vec<bool> {
vec![true; self.len()]
}
/// Alias for [`notna`](Self::notna), matching `pd.RangeIndex.notnull()`.
#[must_use]
pub fn notnull(&self) -> Vec<bool> {
self.notna()
}
/// Whether any position is missing, matching `pd.RangeIndex.hasnans`.
#[must_use]
pub fn hasnans(&self) -> bool {
false
}
/// Drop missing positions, matching `pd.RangeIndex.dropna()`.
/// Returns a clone because RangeIndex cannot hold missing values.
#[must_use]
pub fn dropna(&self) -> Self {
self.clone()
}
/// Fill missing positions, matching `pd.RangeIndex.fillna(value)`.
/// Returns a clone — RangeIndex has no missing positions to fill.
#[must_use]
pub fn fillna(&self, _value: i64) -> Self {
self.clone()
}
/// Stringify each value, matching `pd.RangeIndex.format()`.
#[must_use]
pub fn format(&self) -> Vec<String> {
(0..self.len())
.map(|position| self.value_at(position).to_string())
.collect()
}
/// Identity factorization, matching `pd.RangeIndex.factorize()`.
/// Codes are [0..len) because every value is unique; uniques is a
/// clone of `self`.
#[must_use]
pub fn factorize(&self) -> (Vec<usize>, Self) {
((0..self.len()).collect(), self.clone())
}
/// Pick values at the given positions, matching
/// `pd.RangeIndex.take()`. Out-of-bounds positions raise
/// [`IndexError::OutOfBounds`].
pub fn take(&self, positions: &[usize]) -> Result<Index, IndexError> {
let len = self.len();
// Fast path first: a single pass verifies stride + bounds and returns a
// lazy affine index. Only when positions are non-arithmetic (or out of
// bounds) do we run the explicit bounds-check loop + materialize below.
if let Some(idx) = self.take_arithmetic_positions(positions, len) {
return Ok(idx);
}
let labels = if let Some(labels) = self.fast_i64_values_at_positions(positions, len) {
labels
} else {
for &p in positions {
if p >= len {
return Err(IndexError::OutOfBounds {
position: p,
length: len,
});
}
}
positions.iter().map(|&p| self.value_at(p)).collect()
};
let mut idx = Index::from_i64_values(labels);
if let Some(name) = self.name() {
idx = idx.set_name(name);
}
Ok(idx)
}
/// Repeat each value `repeats` times, matching `pd.RangeIndex.repeat()`.
/// Returns a flat [`Index`] because the result is generally not a
/// contiguous range.
#[must_use]
pub fn repeat(&self, repeats: usize) -> Index {
let len = self.len();
let labels = if repeats == 0 {
Vec::new()
} else if let Some(labels) = self.fast_i64_repeat_values(len, repeats) {
labels
} else {
let mut labels = Vec::with_capacity(repeat_output_capacity(len, repeats));
for position in 0..len {
let value = self.value_at(position);
for _ in 0..repeats {
labels.push(value);
}
}
labels
};
let mut idx = Index::from_i64_values(labels);
if let Some(name) = self.name() {
idx = idx.set_name(name);
}
idx
}
/// First and last value as (start, last), or None if empty. Used to
/// power closed-form reductions that don't materialize the full vector.
fn first_last(&self) -> Option<(i64, i64)> {
let len = self.len();
if len == 0 {
return None;
}
let last_offset = len - 1;
let last = i128::from(self.start) + (last_offset as i128) * i128::from(self.step);
let last = i64::try_from(last).ok()?;
Some((self.start, last))
}
/// Sort values ascending, matching `pd.RangeIndex.sort_values()`.
/// Ascending or zero step returns a clone; descending step rebuilds
/// an ascending RangeIndex starting from min with positive step.
/// Empty returns clone of self.
#[must_use]
pub fn sort_values(&self) -> Self {
if self.len() <= 1 || self.step >= 0 {
return self.clone();
}
let len = self.len();
let last = self.start + (len as i64 - 1) * self.step;
let new_step = -self.step;
let new_stop = last + (len as i64) * new_step;
Self {
start: last,
stop: new_stop,
step: new_step,
name: self.name.clone(),
}
}
/// Alias for `sort_values`, matching `pd.RangeIndex.sort()`.
#[must_use]
pub fn sort(&self) -> Self {
self.sort_values()
}
/// Smallest value in the range, matching `pd.RangeIndex.min()`. Closed
/// form on (start, step, len). Empty returns None.
#[must_use]
pub fn min(&self) -> Option<i64> {
let (first, last) = self.first_last()?;
Some(first.min(last))
}
/// Largest value in the range, matching `pd.RangeIndex.max()`.
#[must_use]
pub fn max(&self) -> Option<i64> {
let (first, last) = self.first_last()?;
Some(first.max(last))
}
/// Return whether `value` is present in this RangeIndex, matching `value in pd.RangeIndex`.
#[must_use]
pub fn contains(&self, value: i64) -> bool {
self.contains_value(value)
}
/// Bound for a value slice, matching `pd.RangeIndex.get_slice_bound(value, side)`.
pub fn get_slice_bound(&self, value: i64, side: &str) -> Result<usize, IndexError> {
self.searchsorted(value, side)
}
/// Create a RangeIndex matching `pd.RangeIndex.from_range`.
pub fn from_range(start: i64, stop: i64, step: i64) -> Result<Self, IndexError> {
Self::new(start, stop, step)
}
/// Return unique values, matching `pd.RangeIndex.unique()`.
#[must_use]
pub fn unique(&self) -> Self {
self.clone()
}
/// Median value. Returns `None` for an empty range; for an even-length
/// range, returns the average of the two middle values as f64.
///
/// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
/// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
/// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
/// [`sum`](Self::sum).
#[must_use]
pub fn median(&self) -> Option<f64> {
let len = self.len();
if len == 0 {
return None;
}
let mid = len / 2;
if len % 2 == 1 {
Some(self.value_at(mid) as f64)
} else {
Some((self.value_at(mid - 1) as f64 + self.value_at(mid) as f64) / 2.0)
}
}
/// Sample variance (ddof=1). Returns `None` for fewer than two values.
///
/// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
/// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
/// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
/// [`sum`](Self::sum).
#[must_use]
pub fn var(&self) -> Option<f64> {
let len = self.len();
if len < 2 {
return None;
}
let n = len as f64;
let step = self.step as f64;
Some(step * step * n * (n + 1.0) / 12.0)
}
/// Sample standard deviation (ddof=1).
///
/// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
/// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
/// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
/// [`sum`](Self::sum).
#[must_use]
pub fn std(&self) -> Option<f64> {
self.var().map(f64::sqrt)
}
/// Product of all values. Empty returns 1; saturating to i64 on overflow.
///
/// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
/// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
/// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
/// [`sum`](Self::sum).
#[must_use]
pub fn prod(&self) -> i64 {
if self
.first_last()
.is_some_and(|(first, last)| first > 0 && last > 0)
{
let mut total: i128 = 1;
for position in 0..self.len() {
total *= i128::from(self.value_at(position));
if total > i128::from(i64::MAX) {
return i64::MAX;
}
}
return total as i64;
}
let mut total: i128 = 1;
for position in 0..self.len() {
let v = self.value_at(position);
total = total.saturating_mul(i128::from(v));
}
i64::try_from(total).unwrap_or(if total > 0 { i64::MAX } else { i64::MIN })
}
/// Sum of all values. Closed form via arithmetic-progression:
/// `n * (first + last) / 2` when `n*(first+last)` is even; falls back to a
/// precise i128 path otherwise.
///
/// ⚠️ NOT A PARITY SURFACE: pandas `Index` has NO numeric reductions.
/// Measured on 2.2.3, `pd.RangeIndex(5).sum()` raises `AttributeError`, as
/// do `prod`/`mean`/`median`/`std`/`var`; only `min`/`max`/`argmin`/`argmax`
/// exist on an Index. The pandas spelling is `idx.to_series().sum()`. These
/// six methods are an FP SUPERSET -- do not cite them as parity evidence.
#[must_use]
pub fn sum(&self) -> i64 {
let len = self.len();
if len == 0 {
return 0;
}
let Some((first, last)) = self.first_last() else {
return 0;
};
let n = len as i128;
let total = (i128::from(first) + i128::from(last)) * n / 2;
i64::try_from(total).unwrap_or(if total > 0 { i64::MAX } else { i64::MIN })
}
/// Mean of all values. Returns `None` for an empty range.
///
/// ⚠️ NOT A PARITY SURFACE: pandas `Index` exposes no numeric reductions
/// (measured 2.2.3: `sum`/`prod`/`mean`/`median`/`std`/`var` all raise
/// `AttributeError`; only `min`/`max`/`argmin`/`argmax` exist). See
/// [`sum`](Self::sum).
#[must_use]
pub fn mean(&self) -> Option<f64> {
let len = self.len();
if len == 0 {
return None;
}
let (first, last) = self.first_last()?;
Some((i128::from(first) + i128::from(last)) as f64 / 2.0)
}
/// Binary-search insertion position, matching
/// `pd.RangeIndex.searchsorted(value, side)`. Restricted to
/// ascending ranges (`step > 0`) because searchsorted assumes a
/// monotonically-increasing input; negative-step ranges raise.
pub fn searchsorted(&self, value: i64, side: &str) -> Result<usize, IndexError> {
if side != "left" && side != "right" {
return Err(IndexError::InvalidArgument(format!(
"searchsorted: side must be 'left' or 'right', got {side:?}"
)));
}
if self.step < 0 {
return Err(IndexError::InvalidArgument(
"searchsorted requires a monotonically-increasing RangeIndex".to_owned(),
));
}
let len = self.len();
if len == 0 {
return Ok(0);
}
let start = i128::from(self.start);
let value = i128::from(value);
if value < start {
return Ok(0);
}
let step = i128::from(self.step);
let offset = value - start;
let base = offset / step;
let rem = offset % step;
let insertion = if rem == 0 {
base + i128::from(side == "right")
} else {
base + 1
};
let len_i128 = len as i128;
Ok(if insertion >= len_i128 {
len
} else {
insertion as usize
})
}
/// Convert to a flat [`Index`] of i64 labels, matching
/// `pd.RangeIndex.to_flat_index()`.
#[must_use]
pub fn to_flat_index(&self) -> Index {
let mut idx = Index::from_range(self.start, self.stop, self.step);
if let Some(name) = self.name() {
idx = idx.set_name(name);
}
idx
}
/// String accessor for the flat integer labels.
#[must_use]
pub fn r#str(&self) -> IndexStringAccessor<'_> {
IndexStringAccessor::owned(self.to_flat_index())
}
/// One-column row materialization, matching `pd.RangeIndex.to_frame(index=False)`.
#[must_use]
pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
(0..self.len())
.map(|position| vec![IndexLabel::Int64(self.value_at(position))])
.collect()
}
/// Series-shaped materialization using range labels as both index and values.
#[must_use]
pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
(0..self.len())
.map(|position| {
let label = IndexLabel::Int64(self.value_at(position));
(label.clone(), label)
})
.collect()
}
/// Whether any range label coerces to true.
#[must_use]
pub fn any(&self) -> bool {
let len = self.len();
len != 0 && (len != 1 || self.start != 0)
}
/// Whether all range labels coerce to true.
#[must_use]
pub fn all(&self) -> bool {
!self.contains_value(0)
}
/// Get labels for a level. RangeIndex is flat and only accepts level 0.
pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
if level == 0 {
Ok(self.to_flat_index())
} else {
Err(IndexError::OutOfBounds {
position: level,
length: 1,
})
}
}
/// Drop a level. RangeIndex is flat, so removing its only level is invalid.
pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
if level == 0 {
Err(IndexError::InvalidArgument(
"cannot remove the only level from a flat Index".to_owned(),
))
} else {
Err(IndexError::OutOfBounds {
position: level,
length: 1,
})
}
}
/// Group equal range labels into position buckets.
#[must_use]
pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
let mut groups = HashMap::with_capacity(self.len());
for position in 0..self.len() {
groups.insert(IndexLabel::Int64(self.value_at(position)), vec![position]);
}
groups
}
/// Apply a function to each range label, returning a flat Index.
#[must_use]
pub fn map<F>(&self, func: F) -> Index
where
F: Fn(&IndexLabel) -> IndexLabel,
{
let labels = (0..self.len())
.map(|position| func(&IndexLabel::Int64(self.value_at(position))))
.collect();
let mut out = Index::new(labels);
if let Some(name) = self.name() {
out = out.set_name(name);
}
out
}
/// Cast range labels to a pandas dtype string, returning a flat Index.
pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
match dtype {
"int" | "int64" => Ok(self.to_flat_index()),
"str" | "string" | "object" => {
let labels = (0..self.len())
.map(|position| IndexLabel::Utf8(self.value_at(position).to_string()))
.collect();
let mut out = Index::new(labels);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
"datetime64[ns]" => {
if self.is_empty() {
Ok(self.to_flat_index())
} else {
Err(IndexError::InvalidArgument(
"DatetimeIndex requires homogeneous DatetimeIndex labels".to_owned(),
))
}
}
"timedelta64[ns]" => {
if self.is_empty() {
Ok(self.to_flat_index())
} else {
Err(IndexError::InvalidArgument(
"TimedeltaIndex requires homogeneous TimedeltaIndex labels".to_owned(),
))
}
}
other => Err(IndexError::InvalidArgument(format!(
"unsupported Index.astype dtype {other:?}"
))),
}
}
/// Nearest preceding-or-equal range label lookup.
#[must_use]
pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
if let IndexLabel::Int64(needle) = key
&& self.step > 0
{
let position = self.searchsorted(*needle, "right").ok()?.checked_sub(1)?;
return Some(IndexLabel::Int64(self.value_at(position)));
}
let mut best = None;
for position in 0..self.len() {
let label = IndexLabel::Int64(self.value_at(position));
if label.cmp(key).is_le() {
best = Some(label);
} else {
break;
}
}
best
}
/// Locate nearest preceding-or-equal range positions for each target label.
#[must_use]
pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
if let Some(keys) = where_index.labels.int64_view() {
if mask.is_none() {
if self.step > 0 && keys.windows(2).all(|pair| pair[0] <= pair[1]) {
let len = self.len();
let mut next_position = 0usize;
let mut best = None;
let mut positions = Vec::with_capacity(keys.len());
for &key in keys.iter() {
while next_position < len && self.value_at(next_position) <= key {
best = Some(next_position);
next_position += 1;
}
positions.push(best);
}
return positions;
}
return keys
.iter()
.map(|&key| {
let mut lo = 0usize;
let mut hi = self.len();
while lo < hi {
let mid = lo + (hi - lo) / 2;
if self.value_at(mid) <= key {
lo = mid + 1;
} else {
hi = mid;
}
}
lo.checked_sub(1)
})
.collect();
}
return keys
.iter()
.map(|&key| {
let mut best = None;
for position in 0..self.len() {
if mask
.and_then(|values| values.get(position))
.is_some_and(|include| !include)
{
continue;
}
if self.value_at(position) <= key {
best = Some(position);
} else {
break;
}
}
best
})
.collect();
}
where_index
.labels
.iter()
.map(|key| {
let mut best = None;
for position in 0..self.len() {
if mask
.and_then(|values| values.get(position))
.is_some_and(|include| !include)
{
continue;
}
let label = IndexLabel::Int64(self.value_at(position));
if label.cmp(key).is_le() {
best = Some(position);
} else {
break;
}
}
best
})
.collect()
}
/// Drop range labels, returning a flat Index.
#[must_use]
pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
let len = self.len();
let mut drop_positions = vec![false; len];
for label in labels_to_drop {
if let IndexLabel::Int64(value) = label
&& let Some(position) = self.position_of_value(*value)
{
drop_positions[position] = true;
}
}
let labels = (0..len)
.filter_map(|position| (!drop_positions[position]).then_some(self.value_at(position)))
.collect();
let mut out = Index::from_i64_values(labels);
if let Some(name) = self.name() {
out = out.set_name(name);
}
out
}
fn apply_join_name(&self, other: &Index, mut out: Index) -> Index {
if self.name() == other.name()
&& let Some(name) = self.name()
{
out = out.set_name(name);
}
out
}
fn matching_step_i64_slice_offset(&self, other: &[i64]) -> Option<i128> {
let &first = other.first()?;
let step = i128::from(self.step);
for (position, &value) in other.iter().enumerate() {
let expected = i128::from(first) + (position as i128) * step;
if i128::from(value) != expected {
return None;
}
}
let offset = i128::from(first) - i128::from(self.start);
if offset % step != 0 {
return None;
}
Some(offset / step)
}
fn same_lattice_i64_slice_overlap_positions(
&self,
other: &[i64],
) -> Option<Option<(usize, usize)>> {
if self.is_empty() || other.is_empty() {
return Some(None);
}
let other_start = self.matching_step_i64_slice_offset(other)?;
let other_last = other_start.checked_add(other.len() as i128 - 1)?;
let first = other_start.max(0);
let last = other_last.min(self.len() as i128 - 1);
if first > last {
return Some(None);
}
Some(Some((
usize::try_from(first).ok()?,
usize::try_from(last).ok()?,
)))
}
fn join_outer_i64_affine_slice(&self, other: &[i64]) -> Option<Index> {
let self_len = self.len();
if other.is_empty() {
return self.affine_span_index(0, self_len, None);
}
if self_len == 0 {
self.matching_step_i64_slice_offset(other)?;
return Index::new_known_unique_int64_affine_range(other[0], self.step, other.len());
}
let other_start = self.matching_step_i64_slice_offset(other)?;
if other_start < 0 || other_start > self_len as i128 {
return None;
}
let other_last = other_start.checked_add(other.len() as i128 - 1)?;
let joined_len = (self_len as i128).max(other_last + 1);
self.affine_span_index(0, usize::try_from(joined_len).ok()?, None)
}
fn join_inner_i64(&self, other: &[i64]) -> Index {
if let Some(overlap) = self.same_lattice_i64_slice_overlap_positions(other) {
let (first, len) = match overlap {
Some((first, last)) => (first, last - first + 1),
None => (0, 0),
};
if let Some(index) = self.affine_span_index(first, len, None) {
return index;
}
}
let mut labels = Vec::new();
if other.is_empty() || self.is_empty() {
return Index::from_i64_values(labels);
}
if let Some((min, span)) = Index::i64_dense_span(other) {
let mut bits = vec![0u64; span.div_ceil(64)];
for &value in other {
let slot = (value as i128 - min as i128) as usize;
bits[slot >> 6] |= 1u64 << (slot & 63);
}
for position in 0..self.len() {
let value = self.value_at(position);
let offset = value as i128 - min as i128;
if offset >= 0 && (offset as usize) < span {
let slot = offset as usize;
if (bits[slot >> 6] >> (slot & 63)) & 1 == 1 {
labels.push(value);
}
}
}
} else {
let mut other_set = FxHashSet::<i64>::default();
other_set.reserve(other.len());
for &value in other {
other_set.insert(value);
}
for position in 0..self.len() {
let value = self.value_at(position);
if other_set.contains(&value) {
labels.push(value);
}
}
}
Index::from_i64_values(labels)
}
fn join_outer_i64(&self, other: &[i64]) -> Index {
if let Some(index) = self.join_outer_i64_affine_slice(other) {
return index;
}
let mut labels = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
for position in 0..self.len() {
labels.push(self.value_at(position));
}
if other.is_empty() {
return Index::from_i64_values(labels);
}
// A duplicate-bearing right index uses the same first-key grouping as
// `Index::union_with`. The range itself is unique, but emitting its
// complete physical order and appending surplus right duplicates would
// place a second `6` after `3`, unlike the flat-index oracle.
if Index::has_duplicates_i64(other) {
let mut counts = FxHashMap::<i64, (usize, usize)>::default();
counts.reserve(combined_output_capacity(self.len(), other.len()));
let mut order = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
for position in 0..self.len() {
let value = self.value_at(position);
let entry = counts.entry(value).or_insert((0, 0));
if entry.0 == 0 && entry.1 == 0 {
order.push(value);
}
entry.0 += 1;
}
for &value in other {
let entry = counts.entry(value).or_insert((0, 0));
if entry.0 == 0 && entry.1 == 0 {
order.push(value);
}
entry.1 += 1;
}
let mut grouped = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
for value in order {
let (left_count, right_count) = counts[&value];
grouped.extend(std::iter::repeat_n(value, left_count.max(right_count)));
}
return Index::from_i64_values(grouped);
}
if let Some((min, span)) = Index::i64_dense_span(other) {
let mut seen = vec![0u64; span.div_ceil(64)];
for &value in other {
if self.contains_value(value) {
continue;
}
let slot = (value as i128 - min as i128) as usize;
let bit = 1u64 << (slot & 63);
let word = slot >> 6;
if seen[word] & bit == 0 {
labels.push(value);
seen[word] |= bit;
}
}
} else {
let mut seen = FxHashSet::<i64>::default();
seen.reserve(other.len());
for &value in other {
if !self.contains_value(value) && seen.insert(value) {
labels.push(value);
}
}
}
Index::from_i64_values(labels)
}
/// Join range labels with another flat Index.
pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
match how {
"left" => Ok(self.to_flat_index()),
"right" => Ok(other.clone()),
"inner" => {
if let Some(other_values) = other.labels.int64_view() {
let out = self.join_inner_i64(&other_values);
return Ok(self.apply_join_name(other, out));
}
self.to_flat_index().join(other, how)
}
"outer" => {
if let Some(other_values) = other.labels.int64_view() {
let out = self.join_outer_i64(&other_values);
return Ok(self.apply_join_name(other, out));
}
self.to_flat_index().join(other, how)
}
other => Err(IndexError::InvalidArgument(format!(
"join: how must be 'left', 'right', 'inner', or 'outer', got {other:?}"
))),
}
}
/// Sort range labels and return the positional sorter.
#[must_use]
pub fn sortlevel(&self) -> (Index, Vec<usize>) {
let order = self.argsort();
let labels = order
.iter()
.map(|&position| self.value_at(position))
.collect();
let mut out = Index::from_i64_values(labels);
if let Some(name) = self.name() {
out = out.set_name(name);
}
(out, order)
}
/// Returns a clone, matching `pd.RangeIndex.view()`.
#[must_use]
pub fn view(&self) -> Self {
self.clone()
}
/// Identity transpose for a 1D index, matching
/// `pd.RangeIndex.transpose()`.
#[must_use]
pub fn transpose(&self) -> Self {
self.clone()
}
/// Alias for `transpose`, matching `pd.RangeIndex.T`.
#[allow(non_snake_case)]
#[must_use]
pub fn T(&self) -> Self {
self.transpose()
}
/// Flatten the range to a `Vec<i64>`, matching `pd.RangeIndex.ravel()`.
#[must_use]
pub fn ravel(&self) -> Vec<i64> {
self.values().to_vec()
}
/// Number of levels, matching `pd.RangeIndex.nlevels`. Always `1`.
#[must_use]
pub fn nlevels(&self) -> usize {
1
}
/// Identity dtype-reinference, matching `pd.RangeIndex.infer_objects()`.
#[must_use]
pub fn infer_objects(&self) -> Self {
self.clone()
}
/// Per-position membership mask, matching `pd.RangeIndex.isin(values)`.
#[must_use]
pub fn isin(&self, values: &[i64]) -> Vec<bool> {
let mut mask = vec![false; self.len()];
for &value in values {
if let Some(position) = self.position_of_value(value) {
mask[position] = true;
}
}
mask
}
/// Half-open positional range for a value slice, matching
/// `pd.RangeIndex.slice_indexer(start, end)`.
pub fn slice_indexer(
&self,
start: i64,
end: i64,
) -> Result<std::ops::Range<usize>, IndexError> {
let (left, right) = self.slice_locs(start, end)?;
Ok(left..right)
}
/// Find positions of `[start, end]` for a value slice, matching
/// `pd.RangeIndex.slice_locs(start, end)`. Requires the range to
/// be ascending (`step > 0`).
pub fn slice_locs(&self, start: i64, end: i64) -> Result<(usize, usize), IndexError> {
if self.step < 0 {
return Err(IndexError::InvalidArgument(
"slice_locs requires a monotonic increasing RangeIndex".to_owned(),
));
}
let left = self.searchsorted(start, "left")?;
let right = self.searchsorted(end, "right")?;
Ok((left, right))
}
/// First position of `value`, matching `pd.RangeIndex.get_loc(value)`.
/// Closed-form on (start, step, len).
pub fn get_loc(&self, value: i64) -> Result<usize, IndexError> {
if self.step == 0 {
return Err(IndexError::InvalidArgument(
"get_loc: zero-step RangeIndex is invalid".to_owned(),
));
}
self.position_of_value(value).ok_or_else(|| {
IndexError::InvalidArgument(format!("get_loc: {value} not in RangeIndex"))
})
}
/// Set the index name, matching `pd.RangeIndex.rename(name)`.
#[must_use]
pub fn rename(&self, name: &str) -> Self {
self.set_name(name)
}
/// Reindex against `target`, matching `pd.RangeIndex.reindex(target)`.
/// Returns `(target.clone(), indexer)`.
#[must_use]
pub fn reindex(&self, target: &Self) -> (Self, Vec<isize>) {
let source_len = self.len();
if let Some(indexer) = self.range_target_indexer(target, source_len) {
return (target.clone(), indexer);
}
let bounds = self.position_bounds_for_len(source_len);
let indexer = (0..target.len())
.map(|position| {
match self.position_of_value_with_len_and_bounds(
target.value_at(position),
source_len,
bounds,
) {
Some(position) => position as isize,
None => -1,
}
})
.collect();
(target.clone(), indexer)
}
/// Locate every position matching each target, matching
/// `pd.RangeIndex.get_indexer_non_unique(targets)`. RangeIndex is
/// always unique so each target either matches one position or
/// none.
#[must_use]
pub fn get_indexer_non_unique(&self, targets: &[i64]) -> (Vec<isize>, Vec<usize>) {
let source_len = self.len();
let bounds = self.position_bounds_for_len(source_len);
let mut positions = Vec::<isize>::with_capacity(targets.len());
let mut missing = Vec::<usize>::new();
for (idx, target) in targets.iter().enumerate() {
match self.position_of_value_with_len_and_bounds(*target, source_len, bounds) {
Some(position) => positions.push(position as isize),
None => {
positions.push(-1);
missing.push(idx);
}
}
}
(positions, missing)
}
/// Alias for [`get_indexer`](Self::get_indexer), matching
/// `pd.RangeIndex.get_indexer_for(targets)`.
#[must_use]
pub fn get_indexer_for(&self, targets: &[i64]) -> Vec<isize> {
self.get_indexer(targets)
}
/// Locate each target value, matching
/// `pd.RangeIndex.get_indexer(targets)`. Closed-form per target.
#[must_use]
pub fn get_indexer(&self, targets: &[i64]) -> Vec<isize> {
let source_len = self.len();
let bounds = self.position_bounds_for_len(source_len);
let mut positions = Vec::with_capacity(targets.len());
for &value in targets {
positions.push(
match self.position_of_value_with_len_and_bounds(value, source_len, bounds) {
Some(position) => position as isize,
None => -1,
},
);
}
positions
}
/// Replace positions where `cond` is `false` with `other`, matching
/// `pd.RangeIndex.where(cond, other)`. Returns flat Index because
/// the result is generally not a contiguous range.
pub fn r#where(&self, cond: &[bool], other: i64) -> Result<Index, IndexError> {
let len = self.len();
if cond.len() != len {
return Err(IndexError::LengthMismatch {
expected: len,
actual: cond.len(),
context: "where: cond length must match index length".to_owned(),
});
}
let labels: Vec<i64> = cond
.iter()
.enumerate()
.map(
|(position, &keep)| {
if keep { self.value_at(position) } else { other }
},
)
.collect();
let mut out = Index::from_i64_values(labels);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
/// Replace positions where `mask` is `true` with `value`, matching
/// `pd.RangeIndex.putmask(mask, value)`.
pub fn putmask(&self, mask: &[bool], value: i64) -> Result<Index, IndexError> {
let len = self.len();
if mask.len() != len {
return Err(IndexError::LengthMismatch {
expected: len,
actual: mask.len(),
context: "putmask: mask length must match index length".to_owned(),
});
}
let labels: Vec<i64> = mask
.iter()
.enumerate()
.map(|(position, &replace)| {
if replace {
value
} else {
self.value_at(position)
}
})
.collect();
let mut out = Index::from_i64_values(labels);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
/// Returns an ascending-ordered `RangeIndex` covering the same value set
/// (name preserved). pandas set operations
/// (union/intersection/difference/symmetric_difference) return results
/// sorted ascending under the default `sort=None`, so descending ranges
/// (`step < 0`) are normalized to their ascending equivalent before the
/// set-op logic runs. Ascending or empty ranges are returned unchanged.
/// Falls back to an unchanged clone in the (unrepresentable) case where the
/// ascending `stop` would overflow `i64`.
fn ascending_normalized(&self) -> RangeIndex {
let len = self.len();
if self.step >= 0 || len == 0 {
return self.clone();
}
// Descending: the smallest value is the last element and the step
// magnitude is the ascending step. The ascending range runs
// [last, self.start] inclusive, i.e. stop = self.start + 1.
let last = self.value_at(len - 1);
let asc_step = self.step.wrapping_neg();
match self.start.checked_add(1) {
Some(stop) if asc_step > 0 => RangeIndex {
start: last,
stop,
step: asc_step,
name: self.name.clone(),
},
_ => self.clone(),
}
}
/// Values present in both ranges, matching
/// `pd.RangeIndex.intersection(other)`. Returns flat Index because the
/// result may not be a contiguous range. NB: pandas uses `sort=False` for
/// intersection (unlike union/difference/symmetric_difference, which default
/// to `sort=None`). Its result is ascending EXCEPT when BOTH operands are
/// descending (`step < 0`), where it is descending. (Verified against pandas
/// 2.2.3 over 150k random pairs.) The self-order scan below already yields
/// descending order over a descending range, so both-descending goes through
/// the operands as-is; every other case is routed through ascending-
/// normalized operands so the fast paths and fallback produce ascending.
#[must_use]
pub fn intersection(&self, other: &Self) -> Index {
if self.step < 0 && other.step < 0 {
self.intersection_selforder(other)
} else {
self.ascending_normalized()
.intersection_selforder(&other.ascending_normalized())
}
}
fn intersection_selforder(&self, other: &Self) -> Index {
let shared_name = self.name().filter(|_| self.name() == other.name());
if let Some(overlap) = self.same_lattice_overlap_positions(other) {
let (first, len) = match overlap {
Some((first, last)) => (first, last - first + 1),
None => (0, 0),
};
if let Some(index) = self.affine_span_index(first, len, shared_name) {
return index;
}
}
let mut labels = Vec::with_capacity(self.len().min(other.len()));
for position in 0..self.len() {
let value = self.value_at(position);
if other.contains_value(value) {
labels.push(value);
}
}
let mut idx = Index::from_i64_values(labels);
if let Some(name) = shared_name {
idx = idx.set_name(name);
}
idx
}
/// True when the two ranges enumerate the same value sequence (order
/// included), i.e. `pd.Index.equals`. Used to detect the union passthrough
/// case where pandas returns `self` unchanged rather than sorting.
fn range_values_equal(&self, other: &Self) -> bool {
let len = self.len();
len == other.len()
&& (len == 0
|| (self.value_at(0) == other.value_at(0) && (len == 1 || self.step == other.step)))
}
/// Union of the two ranges, matching `pd.RangeIndex.union(other)`. pandas
/// (`sort=None`) returns the result sorted ascending EXCEPT when an operand
/// is empty or the two are value-equal, where it passes the surviving
/// operand through unchanged (order preserved). fp's existing fast paths
/// already reproduce those passthrough cases, so only the both-non-empty,
/// non-equal case is normalized to ascending.
#[must_use]
pub fn union(&self, other: &Self) -> Index {
if self.is_empty() || other.is_empty() || self.range_values_equal(other) {
return self.union_ascending(other);
}
self.ascending_normalized()
.union_ascending(&other.ascending_normalized())
}
fn union_ascending(&self, other: &Self) -> Index {
let shared_name = self.name().filter(|_| self.name() == other.name());
let self_len = self.len();
let other_len = other.len();
if self_len == 0 {
if let Some(index) = other.affine_span_index(0, other_len, shared_name) {
return index;
}
} else if other_len == 0 {
if let Some(index) = self.affine_span_index(0, self_len, shared_name) {
return index;
}
} else if let Some(other_start) = self.matching_step_offset(other)
&& let Some(other_end) = other_start.checked_add(other_len as i128 - 1)
&& other_start >= 0
&& other_start <= self_len as i128
{
let last = (self_len as i128 - 1).max(other_end);
if let Ok(len) = usize::try_from(last + 1)
&& let Some(index) = self.affine_span_index(0, len, shared_name)
{
return index;
}
}
let mut labels = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
for position in 0..self.len() {
labels.push(self.value_at(position));
}
for position in 0..other.len() {
let value = other.value_at(position);
if !self.contains_value(value) {
labels.push(value);
}
}
// pandas sorts the union result ascending; both operands are already
// ascending here (normalized), so a sort produces the pandas order for
// the non-aligned case where the two lattices interleave.
labels.sort_unstable();
let mut idx = Index::from_i64_values(labels);
if let Some(name) = shared_name {
idx = idx.set_name(name);
}
idx
}
/// Self values not in other, matching `pd.RangeIndex.difference(other)`.
/// pandas (`sort=None`) sorts the result ascending EXCEPT when `other` is
/// empty, where it returns `self` unchanged; both-empty / equal operands
/// yield an empty result. Only the both-non-empty, non-equal case is
/// normalized to ascending.
#[must_use]
pub fn difference(&self, other: &Self) -> Index {
if self.is_empty() || other.is_empty() || self.range_values_equal(other) {
return self.difference_ascending(other);
}
self.ascending_normalized()
.difference_ascending(&other.ascending_normalized())
}
fn difference_ascending(&self, other: &Self) -> Index {
// Per br-frankenpandas-6r1lq: difference preserves self.name (not
// shared_name like union/intersection).
if let Some(span) = self.single_difference_span_positions(other) {
let (first, len) = span.unwrap_or((0, 0));
if let Some(index) = self.affine_span_index(first, len, self.name()) {
return index;
}
}
let mut labels = Vec::with_capacity(self.len());
for position in 0..self.len() {
let value = self.value_at(position);
if !other.contains_value(value) {
labels.push(value);
}
}
let mut idx = Index::from_i64_values(labels);
if let Some(name) = self.name() {
idx = idx.set_name(name);
}
idx
}
/// Values in either but not both, matching
/// `pd.RangeIndex.symmetric_difference(other)`. pandas (`sort=None`) sorts
/// the result ascending EXCEPT when an operand is empty, where it returns
/// the surviving operand unchanged; equal operands yield an empty result.
/// Only the both-non-empty, non-equal case is normalized to ascending.
#[must_use]
pub fn symmetric_difference(&self, other: &Self) -> Index {
if self.is_empty() || other.is_empty() || self.range_values_equal(other) {
return self.symmetric_difference_ascending(other);
}
self.ascending_normalized()
.symmetric_difference_ascending(&other.ascending_normalized())
}
fn symmetric_difference_ascending(&self, other: &Self) -> Index {
let shared_name = self.name().filter(|_| self.name() == other.name());
if let (Some(left_span), Some(right_span)) = (
self.single_difference_span_positions(other),
other.single_difference_span_positions(self),
) {
match (left_span, right_span) {
(None, None) => {
if let Some(index) = self.affine_span_index(0, 0, shared_name) {
return index;
}
}
(Some((first, len)), None) => {
if let Some(index) = self.affine_span_index(first, len, shared_name) {
return index;
}
}
(None, Some((first, len))) => {
if let Some(index) = other.affine_span_index(first, len, shared_name) {
return index;
}
}
(Some((left_first, left_len)), Some((right_first, right_len))) => {
if left_len == 0 {
if let Some(index) =
other.affine_span_index(right_first, right_len, shared_name)
{
return index;
}
} else if right_len == 0 {
if let Some(index) =
self.affine_span_index(left_first, left_len, shared_name)
{
return index;
}
} else {
let left_last = self.value_at(left_first + left_len - 1);
let right_start = other.value_at(right_first);
if left_last
.checked_add(self.step)
.is_some_and(|next| next == right_start)
&& let Some(len) = left_len.checked_add(right_len)
&& let Some(index) =
self.affine_span_index(left_first, len, shared_name)
{
return index;
}
// Only emit [left ++ right] directly when the left run
// is entirely below the right run, so the concatenation
// is ascending (pandas sorts the result). Otherwise fall
// through to the sorted fallback below.
if left_last < right_start
&& let (Some(left_run), Some(right_run)) = (
Int64AffineLabels::new(
self.value_at(left_first),
self.step,
left_len,
),
Int64AffineLabels::new(
other.value_at(right_first),
other.step,
right_len,
),
)
&& let Some(mut index) =
Index::new_known_unique_int64_two_affine_runs(left_run, right_run)
{
if let Some(name) = shared_name {
index = index.set_name(name);
}
return index;
}
}
}
}
}
let mut labels = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
for position in 0..self.len() {
let value = self.value_at(position);
if !other.contains_value(value) {
labels.push(value);
}
}
for position in 0..other.len() {
let value = other.value_at(position);
if !self.contains_value(value) {
labels.push(value);
}
}
// pandas sorts the symmetric-difference result ascending; the two
// single-value runs above are each ascending (operands normalized) but
// interleave when neither range sits wholly below the other, so sort.
labels.sort_unstable();
let mut idx = Index::from_i64_values(labels);
if let Some(name) = shared_name {
idx = idx.set_name(name);
}
idx
}
/// Insert `value` at position `loc`, matching
/// `pd.RangeIndex.insert(loc, value)`. Returns a flat [`Index`]
/// because the result is generally not a contiguous range.
pub fn insert(&self, loc: usize, value: i64) -> Result<Index, IndexError> {
let len = self.len();
if loc > len {
return Err(IndexError::OutOfBounds {
position: loc,
length: len,
});
}
let labels = if let Some(labels) = self.fast_i64_insert_values(len, loc, value) {
labels
} else {
let mut labels = Vec::with_capacity(insert_output_capacity(len));
for position in 0..loc {
labels.push(self.value_at(position));
}
labels.push(value);
for position in loc..len {
labels.push(self.value_at(position));
}
labels
};
let mut out = Index::from_i64_values(labels);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
/// Concatenate with another RangeIndex, matching
/// `pd.RangeIndex.append(other)`. Returns a flat [`Index`] because the
/// resulting values are generally not a contiguous range; preserves
/// the index name when both operands share it.
#[must_use]
pub fn append(&self, other: &Self) -> Index {
let len = self.len();
let other_len = other.len();
if let Some(index) = self.fast_i64_append_index(other, len, other_len) {
let mut out = index;
if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
out = out.set_name(name);
}
return out;
}
let labels = if let Some(labels) = self.fast_i64_append_values(other, len, other_len) {
labels
} else {
let mut labels = Vec::with_capacity(combined_output_capacity(len, other_len));
for position in 0..len {
labels.push(self.value_at(position));
}
for position in 0..other_len {
labels.push(other.value_at(position));
}
labels
};
let mut out = Index::from_i64_values(labels);
if let Some(name) = self.name().filter(|_| self.name() == other.name()) {
out = out.set_name(name);
}
out
}
/// Remove the value at the given position, matching
/// `pd.RangeIndex.delete(loc)`. Returns a flat [`Index`] because the
/// residual values may no longer form a contiguous range.
pub fn delete(&self, loc: usize) -> Result<Index, IndexError> {
let len = self.len();
if loc >= len {
return Err(IndexError::OutOfBounds {
position: loc,
length: len,
});
}
if let Some(index) = self.fast_i64_delete_index(len, loc) {
let mut out = index;
if let Some(name) = self.name() {
out = out.set_name(name);
}
return Ok(out);
}
let labels = if let Some(labels) = self.fast_i64_delete_values(len, loc) {
labels
} else {
let mut labels = Vec::with_capacity(len.saturating_sub(1));
for position in 0..len {
if position != loc {
labels.push(self.value_at(position));
}
}
labels
};
let mut out = Index::from_i64_values(labels);
if let Some(name) = self.name() {
out = out.set_name(name);
}
Ok(out)
}
}
/// Public pandas-style categorical index wrapper: typed labels (text,
/// numbers, dates, intervals, ...) drawn from typed categories, a missing
/// label (NaN) holding no category. They were text only
/// (br-frankenpandas-lztvp).
#[derive(Clone, Serialize, Deserialize)]
pub struct CategoricalIndex {
labels: Vec<IndexLabel>,
categories: Vec<IndexLabel>,
ordered: bool,
name: Option<LabelName>,
#[serde(default, skip_serializing_if = "Option::is_none")]
category_codes: Option<Vec<usize>>,
}
impl std::fmt::Debug for CategoricalIndex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CategoricalIndex")
.field("labels", &self.labels)
.field("categories", &self.categories)
.field("ordered", &self.ordered)
.field("name", &self.name)
.finish()
}
}
impl PartialEq for CategoricalIndex {
fn eq(&self, other: &Self) -> bool {
self.labels == other.labels
&& self.categories == other.categories
&& self.ordered == other.ordered
&& self.name == other.name
}
}
impl Eq for CategoricalIndex {}
fn mark_category_rank(seen_ranks: &mut [u64], rank: usize) -> bool {
let word = rank >> 6;
let bit = 1u64 << (rank & 63);
let is_new = seen_ranks[word] & bit == 0;
if is_new {
seen_ranks[word] |= bit;
}
is_new
}
impl CategoricalIndex {
fn category_codes_for(labels: &[IndexLabel], categories: &[IndexLabel]) -> Option<Vec<usize>> {
let map = {
let mut map: FxHashMap<&IndexLabel, usize> = FxHashMap::default();
for (i, cat) in categories.iter().enumerate() {
map.entry(cat).or_insert(i);
}
map
};
let mut codes = Vec::with_capacity(labels.len());
for label in labels {
codes.push(map.get(label).copied()?);
}
Some(codes)
}
/// A label as the index holds it: any missing one is NaN.
fn held(label: IndexLabel) -> IndexLabel {
if label.is_missing() {
IndexLabel::Null(fp_types::NullKind::NaN)
} else {
label
}
}
fn from_parts(
labels: Vec<IndexLabel>,
categories: Vec<IndexLabel>,
ordered: bool,
name: Option<LabelName>,
) -> Self {
let category_codes = Self::category_codes_for(&labels, &categories);
Self {
labels,
categories,
ordered,
name,
category_codes,
}
}
/// The index of `labels`, its categories the distinct non-missing ones
/// in first-seen order; a missing label is NaN.
#[must_use]
pub fn from_values<L: Into<IndexLabel>>(labels: Vec<L>, ordered: bool) -> Self {
// First-seen dedup in O(n): a side hash set tracks membership while the
// categories Vec preserves insertion order, replacing the O(n·k)
// `categories.contains` linear rescan per label.
let labels: Vec<IndexLabel> = labels
.into_iter()
.map(|label| Self::held(label.into()))
.collect();
let mut categories = Vec::<IndexLabel>::new();
let mut ranks = FxHashMap::<&IndexLabel, usize>::default();
let mut category_codes = Vec::<usize>::with_capacity(labels.len());
for label in &labels {
if label.is_missing() {
continue;
}
let rank = if let Some(rank) = ranks.get(label).copied() {
rank
} else {
let rank = categories.len();
ranks.insert(label, rank);
categories.push(label.clone());
rank
};
category_codes.push(rank);
}
drop(ranks);
let complete = category_codes.len() == labels.len();
Self {
labels,
categories,
ordered,
name: None,
category_codes: complete.then_some(category_codes),
}
}
/// The index of `labels` over `categories`, as pandas' constructor: a
/// label outside the categories (or missing) is NaN - it was refused.
/// Repeated or missing categories are pandas' errors.
pub fn with_categories<L: Into<IndexLabel>, C: Into<IndexLabel>>(
labels: Vec<L>,
categories: Vec<C>,
ordered: bool,
) -> Result<Self, IndexError> {
let categories: Vec<IndexLabel> = categories.into_iter().map(Into::into).collect();
if categories.iter().any(IndexLabel::is_missing) {
return Err(IndexError::InvalidArgument(
"Categorical categories cannot be null".to_owned(),
));
}
// O(n+k) membership: hash the category set once, then place each
// label in original order.
let mut category_map = FxHashMap::<&IndexLabel, usize>::default();
let mut unique = true;
for (rank, category) in categories.iter().enumerate() {
unique &= category_map.insert(category, rank).is_none();
}
if !unique {
return Err(IndexError::InvalidArgument(
"Categorical categories must be unique".to_owned(),
));
}
let mut category_codes = Vec::<usize>::with_capacity(labels.len());
let mut complete = true;
let labels: Vec<IndexLabel> = labels
.into_iter()
.map(|label| {
let label = label.into();
match category_map.get(&label).copied() {
Some(rank) => {
category_codes.push(rank);
label
}
None => {
complete = false;
IndexLabel::Null(fp_types::NullKind::NaN)
}
}
})
.collect();
drop(category_map);
Ok(Self {
labels,
categories,
ordered,
name: None,
category_codes: complete.then_some(category_codes),
})
}
#[must_use]
pub fn labels(&self) -> &[IndexLabel] {
&self.labels
}
#[must_use]
pub fn categories(&self) -> &[IndexLabel] {
&self.categories
}
#[must_use]
pub fn ordered(&self) -> bool {
self.ordered
}
#[must_use]
pub fn len(&self) -> usize {
self.labels.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.labels.is_empty()
}
#[must_use]
pub fn name(&self) -> Option<&LabelName> {
self.name.as_ref()
}
#[must_use]
pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
let mut out = self.clone();
out.name = Some(name.into());
out
}
#[must_use]
pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
let mut out = self.clone();
out.name = name.map(Into::into);
out
}
#[must_use]
pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
self.set_names(name)
}
#[must_use]
pub fn names(&self) -> Vec<Option<String>> {
vec![self.name.clone().map(String::from)]
}
#[must_use]
pub fn copy(&self) -> Self {
self.clone()
}
#[must_use]
pub fn shape(&self) -> (usize,) {
(self.len(),)
}
#[must_use]
pub fn size(&self) -> usize {
self.len()
}
#[must_use]
pub fn empty(&self) -> bool {
self.is_empty()
}
#[must_use]
pub fn dtype(&self) -> &'static str {
"category"
}
#[must_use]
pub fn dtypes(&self) -> Vec<&'static str> {
vec![self.dtype()]
}
#[must_use]
pub fn memory_usage(&self, deep: bool) -> usize {
let fixed = fixed_width_label_memory_usage(
self.labels.len().saturating_add(self.categories.len()),
std::mem::size_of::<String>(),
);
if deep {
let text_len = |label: &IndexLabel| match label {
IndexLabel::Utf8(text) => text.len(),
_ => 0,
};
fixed
.saturating_add(saturating_usize_sum(self.labels.iter().map(text_len)))
.saturating_add(saturating_usize_sum(self.categories.iter().map(text_len)))
.saturating_add(self.name.as_ref().map_or(0, |name| name.len()))
} else {
fixed
}
}
#[must_use]
pub fn nbytes(&self) -> usize {
self.memory_usage(false)
}
/// Which labels are missing (it was all false: no label could be).
#[must_use]
pub fn isna(&self) -> Vec<bool> {
self.labels.iter().map(IndexLabel::is_missing).collect()
}
#[must_use]
pub fn notna(&self) -> Vec<bool> {
self.labels
.iter()
.map(|label| !label.is_missing())
.collect()
}
/// Categorical labels cannot be differenced without converting to a
/// numeric or datetime dtype, matching pandas' fail-closed behavior.
pub fn diff(&self, _periods: i64) -> Result<Vec<Option<i64>>, IndexError> {
Err(IndexError::InvalidArgument(
"Categorical has no 'diff' method; convert to a suitable dtype before calling diff"
.to_owned(),
))
}
#[must_use]
pub fn is_unique(&self) -> bool {
if self.labels.len() <= 1 {
return true;
}
if let Some(codes) = &self.category_codes {
return self.labels_are_unique_by_category_codes(codes);
}
if self.category_rank_unique_scan_is_bounded() {
return self.labels_are_unique_by_category_rank();
}
self.labels_are_unique_by_hash()
}
#[must_use]
pub fn has_duplicates(&self) -> bool {
!self.is_unique()
}
#[must_use]
pub fn is_monotonic_increasing(&self) -> bool {
if let Some(codes) = &self.category_codes {
return self.category_codes_are_monotonic_increasing(codes);
}
self.category_ranks_are_monotonic(|prev, next| prev <= next)
}
#[must_use]
pub fn is_monotonic(&self) -> bool {
self.is_monotonic_increasing()
}
#[must_use]
pub fn is_monotonic_decreasing(&self) -> bool {
if let Some(codes) = &self.category_codes {
return self.category_codes_are_monotonic_decreasing(codes);
}
self.category_ranks_are_monotonic(|prev, next| prev >= next)
}
/// The distinct non-missing labels, as pandas' `nunique()` (dropna).
#[must_use]
pub fn nunique(&self) -> usize {
self.distinct_count()
.saturating_sub(usize::from(self.labels.iter().any(IndexLabel::is_missing)))
}
/// The distinct labels, a missing one (all are NaN) counted once.
fn distinct_count(&self) -> usize {
if self.labels.len() <= 1 {
return self.labels.len();
}
if let Some(codes) = &self.category_codes {
return self.unique_label_count_by_category_codes(codes);
}
if self.category_rank_unique_scan_is_bounded() {
return self.unique_label_count_by_category_rank();
}
self.unique_label_count_by_hash()
}
#[must_use]
pub fn ndim(&self) -> usize {
1
}
pub fn item(&self) -> Result<IndexLabel, IndexError> {
if self.labels.len() == 1 {
Ok(self.labels[0].clone())
} else {
Err(IndexError::InvalidArgument(format!(
"item requires exactly one label, got {}",
self.labels.len()
)))
}
}
#[must_use]
pub fn is_(&self, other: &Self) -> bool {
std::ptr::eq(self, other)
}
#[must_use]
pub fn equals(&self, other: &Self) -> bool {
self.labels == other.labels
&& self.categories == other.categories
&& self.ordered == other.ordered
}
#[must_use]
pub fn identical(&self, other: &Self) -> bool {
self.equals(other) && self.name == other.name
}
#[must_use]
pub fn holds_integer(&self) -> bool {
false
}
#[must_use]
pub fn inferred_type(&self) -> &'static str {
"categorical"
}
#[must_use]
pub fn is_boolean(&self) -> bool {
false
}
#[must_use]
pub fn is_categorical(&self) -> bool {
true
}
#[must_use]
pub fn is_floating(&self) -> bool {
false
}
#[must_use]
pub fn is_integer(&self) -> bool {
false
}
#[must_use]
pub fn is_interval(&self) -> bool {
false
}
#[must_use]
pub fn is_numeric(&self) -> bool {
false
}
#[must_use]
pub fn is_object(&self) -> bool {
false
}
/// First-occurrence category index for each category name, matching the
/// semantics of `categories.iter().position(...)` but built once in O(k).
/// `or_insert` keeps the first index if `categories` somehow has dupes.
fn category_index_map(&self) -> FxHashMap<&IndexLabel, usize> {
let mut map: FxHashMap<&IndexLabel, usize> = FxHashMap::default();
for (i, cat) in self.categories.iter().enumerate() {
map.entry(cat).or_insert(i);
}
map
}
fn category_rank_unique_scan_is_bounded(&self) -> bool {
// Category-rank scans pay O(category_count) metadata work before the
// label pass. Keep this stricter than dense integer span heuristics so
// sparse category universes fall back to the O(label_count) hash path.
self.categories.len() <= self.labels.len().saturating_mul(8)
}
fn labels_are_unique_by_hash(&self) -> bool {
let mut seen: FxHashSet<&IndexLabel> = FxHashSet::default();
for label in &self.labels {
if !seen.insert(label) {
return false;
}
}
true
}
fn unique_label_count_by_hash(&self) -> usize {
self.labels.iter().collect::<FxHashSet<_>>().len()
}
fn labels_are_unique_by_category_rank(&self) -> bool {
let map = self.category_index_map();
let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
for label in &self.labels {
if let Some(rank) = map.get(label).copied() {
if !mark_category_rank(&mut seen_ranks, rank) {
return false;
}
} else if !invalid_seen.insert(label) {
return false;
}
}
true
}
fn labels_are_unique_by_category_codes(&self, category_codes: &[usize]) -> bool {
if category_codes.len() != self.labels.len() {
return self.labels_are_unique_by_category_rank();
}
let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
for &rank in category_codes {
let Some(_) = self.categories.get(rank) else {
return self.labels_are_unique_by_category_rank();
};
if !mark_category_rank(&mut seen_ranks, rank) {
return false;
}
}
true
}
fn unique_label_count_by_category_rank(&self) -> usize {
let map = self.category_index_map();
let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
let mut unique = 0usize;
for label in &self.labels {
if let Some(rank) = map.get(label).copied() {
if mark_category_rank(&mut seen_ranks, rank) {
unique += 1;
}
} else if invalid_seen.insert(label) {
unique += 1;
}
}
unique
}
fn unique_label_count_by_category_codes(&self, category_codes: &[usize]) -> usize {
if category_codes.len() != self.labels.len() {
return self.unique_label_count_by_category_rank();
}
let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
let mut unique = 0usize;
for &rank in category_codes {
let Some(_) = self.categories.get(rank) else {
return self.unique_label_count_by_category_rank();
};
if mark_category_rank(&mut seen_ranks, rank) {
unique += 1;
}
}
unique
}
fn unique_labels_by_hash(&self) -> Vec<IndexLabel> {
let mut seen = FxHashSet::<&IndexLabel>::default();
let mut uniques = Vec::<IndexLabel>::new();
for label in &self.labels {
if seen.insert(label) {
uniques.push(label.clone());
}
}
uniques
}
fn unique_labels_by_category_rank(&self) -> Vec<IndexLabel> {
let map = self.category_index_map();
let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
let mut uniques =
Vec::<IndexLabel>::with_capacity(self.labels.len().min(self.categories.len()));
for label in &self.labels {
if let Some(rank) = map.get(label).copied() {
if mark_category_rank(&mut seen_ranks, rank) {
uniques.push(label.clone());
}
} else if invalid_seen.insert(label) {
uniques.push(label.clone());
}
}
uniques
}
fn unique_by_category_codes(&self, category_codes: &[usize]) -> Self {
if category_codes.len() != self.labels.len() {
return Self::from_parts(
self.unique_labels_by_category_rank(),
self.categories.clone(),
self.ordered,
self.name.clone(),
);
}
let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
let mut unique_labels =
Vec::<IndexLabel>::with_capacity(self.labels.len().min(self.categories.len()));
let mut unique_category_codes =
Vec::<usize>::with_capacity(self.labels.len().min(self.categories.len()));
for &rank in category_codes {
let Some(category) = self.categories.get(rank) else {
return Self::from_parts(
self.unique_labels_by_category_rank(),
self.categories.clone(),
self.ordered,
self.name.clone(),
);
};
if mark_category_rank(&mut seen_ranks, rank) {
unique_labels.push(category.clone());
unique_category_codes.push(rank);
}
}
Self {
labels: unique_labels,
categories: self.categories.clone(),
ordered: self.ordered,
name: self.name.clone(),
category_codes: Some(unique_category_codes),
}
}
fn value_counts_by_hash(&self) -> Vec<(IndexLabel, usize)> {
let mut order = Vec::<&IndexLabel>::new();
let mut counts = FxHashMap::<&IndexLabel, usize>::default();
for label in &self.labels {
let entry = counts.entry(label).or_insert_with(|| {
order.push(label);
0
});
*entry += 1;
}
let mut pairs: Vec<(IndexLabel, usize)> = order
.iter()
.map(|label| ((*label).clone(), counts[label]))
.collect();
pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
pairs
}
fn value_counts_by_category_rank(&self) -> Vec<(IndexLabel, usize)> {
let map = self.category_index_map();
let mut counts = vec![0usize; self.categories.len()];
let mut invalid_counts = FxHashMap::<&IndexLabel, usize>::default();
let mut order = Vec::<&IndexLabel>::new();
for label in &self.labels {
if let Some(rank) = map.get(label).copied() {
if counts[rank] == 0 {
order.push(label);
}
counts[rank] += 1;
} else {
let entry = invalid_counts.entry(label).or_insert_with(|| {
order.push(label);
0
});
*entry += 1;
}
}
let mut pairs = Vec::with_capacity(order.len());
for label in order {
if let Some(rank) = map.get(label).copied() {
pairs.push((self.categories[rank].clone(), counts[rank]));
} else {
pairs.push((label.to_owned(), invalid_counts[label]));
}
}
pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
pairs
}
fn value_counts_by_category_codes(&self, category_codes: &[usize]) -> Vec<(IndexLabel, usize)> {
if category_codes.len() != self.labels.len() {
return self.value_counts_by_category_rank();
}
let mut counts = vec![0usize; self.categories.len()];
let mut order = Vec::<usize>::with_capacity(self.categories.len().min(self.labels.len()));
for &rank in category_codes {
let Some(count) = counts.get_mut(rank) else {
return self.value_counts_by_category_rank();
};
if *count == 0 {
order.push(rank);
}
*count += 1;
}
let mut pairs: Vec<(IndexLabel, usize)> = order
.into_iter()
.map(|rank| (self.categories[rank].clone(), counts[rank]))
.collect();
pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
pairs
}
fn factorize_by_hash(&self) -> (Vec<isize>, Self) {
let mut positions = FxHashMap::<&IndexLabel, isize>::default();
let mut uniques = Vec::<IndexLabel>::new();
let mut codes = Vec::with_capacity(self.labels.len());
for label in &self.labels {
if let Some(code) = positions.get(label) {
codes.push(*code);
} else {
let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
positions.insert(label, code);
uniques.push(label.clone());
codes.push(code);
}
}
let unique_index = Self::from_parts(
uniques,
self.categories.clone(),
self.ordered,
self.name.clone(),
);
(codes, unique_index)
}
fn factorize_by_category_codes(&self, category_codes: &[usize]) -> (Vec<isize>, Self) {
if category_codes.len() != self.labels.len() {
return self.factorize_by_category_rank();
}
let mut rank_codes = vec![-1isize; self.categories.len()];
let mut unique_labels = Vec::<IndexLabel>::new();
let mut unique_category_codes = Vec::<usize>::new();
let mut codes = Vec::with_capacity(category_codes.len());
for &rank in category_codes {
let Some(category) = self.categories.get(rank) else {
return self.factorize_by_category_rank();
};
let mut code = rank_codes[rank];
if code < 0 {
code = isize::try_from(unique_labels.len()).unwrap_or(isize::MAX);
rank_codes[rank] = code;
unique_labels.push(category.clone());
unique_category_codes.push(rank);
}
codes.push(code);
}
let unique_index = Self {
labels: unique_labels,
categories: self.categories.clone(),
ordered: self.ordered,
name: self.name.clone(),
category_codes: Some(unique_category_codes),
};
(codes, unique_index)
}
fn factorize_by_category_rank(&self) -> (Vec<isize>, Self) {
let map = self.category_index_map();
let mut rank_codes = vec![-1isize; self.categories.len()];
let mut invalid_codes = FxHashMap::<&IndexLabel, isize>::default();
let mut uniques = Vec::<IndexLabel>::new();
let mut codes = Vec::with_capacity(self.labels.len());
for label in &self.labels {
if let Some(rank) = map.get(label).copied() {
let mut code = rank_codes[rank];
if code < 0 {
code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
rank_codes[rank] = code;
uniques.push(label.clone());
}
codes.push(code);
} else if let Some(code) = invalid_codes.get(label) {
codes.push(*code);
} else {
let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
invalid_codes.insert(label, code);
uniques.push(label.clone());
codes.push(code);
}
}
let unique_index = Self::from_parts(
uniques,
self.categories.clone(),
self.ordered,
self.name.clone(),
);
(codes, unique_index)
}
fn duplicated_by_hash(&self, keep: DuplicateKeep) -> Vec<bool> {
let n = self.labels.len();
let mut result = vec![false; n];
match keep {
DuplicateKeep::First | DuplicateKeep::Last => {
let mut seen: FxHashSet<&IndexLabel> =
FxHashSet::with_capacity_and_hasher(n, Default::default());
let mut mark = |i: usize| {
if !seen.insert(&self.labels[i]) {
result[i] = true;
}
};
if matches!(keep, DuplicateKeep::First) {
for i in 0..n {
mark(i);
}
} else {
for i in (0..n).rev() {
mark(i);
}
}
}
DuplicateKeep::None => {
let mut counts: FxHashMap<&IndexLabel, u32> =
FxHashMap::with_capacity_and_hasher(n, Default::default());
for label in &self.labels {
*counts.entry(label).or_insert(0) += 1;
}
for (i, label) in self.labels.iter().enumerate() {
result[i] = counts[label] > 1;
}
}
}
result
}
fn duplicated_by_category_rank(&self, keep: DuplicateKeep) -> Vec<bool> {
let n = self.labels.len();
let map = self.category_index_map();
let mut result = vec![false; n];
match keep {
DuplicateKeep::First | DuplicateKeep::Last => {
let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
let mut mark = |i: usize| {
let label = &self.labels[i];
let fresh = if let Some(rank) = map.get(label).copied() {
mark_category_rank(&mut seen_ranks, rank)
} else {
invalid_seen.insert(label)
};
if !fresh {
result[i] = true;
}
};
if matches!(keep, DuplicateKeep::First) {
for i in 0..n {
mark(i);
}
} else {
for i in (0..n).rev() {
mark(i);
}
}
}
DuplicateKeep::None => {
let words = self.categories.len().div_ceil(64);
let mut seen_ranks = vec![0u64; words];
let mut duplicate_ranks = vec![0u64; words];
let mut invalid_seen: FxHashSet<&IndexLabel> = FxHashSet::default();
let mut invalid_duplicates: FxHashSet<&IndexLabel> = FxHashSet::default();
for label in &self.labels {
if let Some(rank) = map.get(label).copied() {
let word = rank >> 6;
let bit = 1u64 << (rank & 63);
if seen_ranks[word] & bit == 0 {
seen_ranks[word] |= bit;
} else {
duplicate_ranks[word] |= bit;
}
} else if !invalid_seen.insert(label) {
invalid_duplicates.insert(label);
}
}
for (i, label) in self.labels.iter().enumerate() {
result[i] = if let Some(rank) = map.get(label).copied() {
let word = rank >> 6;
let bit = 1u64 << (rank & 63);
duplicate_ranks[word] & bit != 0
} else {
invalid_duplicates.contains(label)
};
}
}
}
result
}
fn duplicated_by_category_codes(
&self,
category_codes: &[usize],
keep: DuplicateKeep,
) -> Vec<bool> {
if category_codes.len() != self.labels.len() {
return self.duplicated_by_category_rank(keep);
}
let n = category_codes.len();
let mut result = vec![false; n];
match keep {
DuplicateKeep::First | DuplicateKeep::Last => {
let mut seen_ranks = vec![0u64; self.categories.len().div_ceil(64)];
let mut mark = |i: usize| {
let rank = category_codes[i];
let Some(_) = self.categories.get(rank) else {
result = self.duplicated_by_category_rank(keep);
return false;
};
if !mark_category_rank(&mut seen_ranks, rank) {
result[i] = true;
}
true
};
if matches!(keep, DuplicateKeep::First) {
for i in 0..n {
if !mark(i) {
return result;
}
}
} else {
for i in (0..n).rev() {
if !mark(i) {
return result;
}
}
}
}
DuplicateKeep::None => {
let words = self.categories.len().div_ceil(64);
let mut seen_ranks = vec![0u64; words];
let mut duplicate_ranks = vec![0u64; words];
for &rank in category_codes {
let Some(_) = self.categories.get(rank) else {
return self.duplicated_by_category_rank(keep);
};
let word = rank >> 6;
let bit = 1u64 << (rank & 63);
if seen_ranks[word] & bit == 0 {
seen_ranks[word] |= bit;
} else {
duplicate_ranks[word] |= bit;
}
}
for (i, &rank) in category_codes.iter().enumerate() {
let word = rank >> 6;
let bit = 1u64 << (rank & 63);
result[i] = duplicate_ranks[word] & bit != 0;
}
}
}
result
}
fn category_ranks_are_monotonic(
&self,
mut ordered: impl FnMut(Option<usize>, Option<usize>) -> bool,
) -> bool {
let map = self.category_index_map();
let mut ranks = self.labels.iter().map(|label| map.get(label).copied());
let Some(mut previous) = ranks.next() else {
return true;
};
for rank in ranks {
if !ordered(previous, rank) {
return false;
}
previous = rank;
}
true
}
fn category_codes_are_monotonic_increasing(&self, category_codes: &[usize]) -> bool {
if category_codes.len() != self.labels.len() {
return self.category_ranks_are_monotonic(|prev, next| prev <= next);
}
let Some((&first, rest)) = category_codes.split_first() else {
return true;
};
if first >= self.categories.len() {
return self.category_ranks_are_monotonic(|prev, next| prev <= next);
}
let mut previous = first;
for &rank in rest {
if rank >= self.categories.len() {
return self.category_ranks_are_monotonic(|prev, next| prev <= next);
}
if previous > rank {
return false;
}
previous = rank;
}
true
}
fn category_codes_are_monotonic_decreasing(&self, category_codes: &[usize]) -> bool {
if category_codes.len() != self.labels.len() {
return self.category_ranks_are_monotonic(|prev, next| prev >= next);
}
let Some((&first, rest)) = category_codes.split_first() else {
return true;
};
if first >= self.categories.len() {
return self.category_ranks_are_monotonic(|prev, next| prev >= next);
}
let mut previous = first;
for &rank in rest {
if rank >= self.categories.len() {
return self.category_ranks_are_monotonic(|prev, next| prev >= next);
}
if previous < rank {
return false;
}
previous = rank;
}
true
}
#[must_use]
pub fn codes(&self) -> Vec<Option<usize>> {
if let Some(codes) = &self.category_codes {
return codes.iter().copied().map(Some).collect();
}
// O(n+k): hash category->index once instead of a linear
// `categories.position` scan per label. First-occurrence index
// preserved, so output is bit-identical.
let map = self.category_index_map();
self.labels
.iter()
.map(|label| map.get(label).copied())
.collect()
}
#[must_use]
pub fn values(&self) -> Vec<IndexLabel> {
self.labels.clone()
}
#[must_use]
pub fn to_list(&self) -> Vec<IndexLabel> {
self.labels.clone()
}
#[must_use]
pub fn tolist(&self) -> Vec<IndexLabel> {
self.to_list()
}
#[must_use]
pub fn to_numpy(&self) -> Vec<IndexLabel> {
self.labels.clone()
}
#[must_use]
pub fn array(&self) -> Vec<IndexLabel> {
self.labels.clone()
}
/// The labels as a plain Index (of their own kind: text, numbers,
/// intervals, ...).
#[must_use]
pub fn to_index(&self) -> Index {
Index::new(self.labels.clone()).set_names(self.name.as_deref())
}
/// Stringify each label, matching `pd.CategoricalIndex.format()`.
#[must_use]
pub fn format(&self) -> Vec<String> {
self.labels.iter().map(ToString::to_string).collect()
}
/// Whether `value` may be placed in this index: a category, or missing.
fn placeable(&self, value: &IndexLabel, op: &str) -> Result<IndexLabel, IndexError> {
if value.is_missing() {
return Ok(IndexLabel::Null(fp_types::NullKind::NaN));
}
if !self.categories.contains(value) {
return Err(IndexError::InvalidArgument(format!(
"{op}: replacement {value:?} is not a category"
)));
}
Ok(value.clone())
}
/// Replace positions where `cond` is `false` with `other`, matching
/// `pd.CategoricalIndex.where(cond, other)`. `other` must be a
/// category, or missing (pandas' default).
pub fn r#where(&self, cond: &[bool], other: &IndexLabel) -> Result<Self, IndexError> {
if cond.len() != self.labels.len() {
return Err(IndexError::LengthMismatch {
expected: self.labels.len(),
actual: cond.len(),
context: "where: cond length must match index length".to_owned(),
});
}
let other = self.placeable(other, "where")?;
let labels: Vec<IndexLabel> = self
.labels
.iter()
.zip(cond.iter())
.map(
|(label, &keep)| {
if keep { label.clone() } else { other.clone() }
},
)
.collect();
Ok(Self::from_parts(
labels,
self.categories.clone(),
self.ordered,
self.name.clone(),
))
}
/// Replace positions where `mask` is `true` with `value`, matching
/// `pd.CategoricalIndex.putmask(mask, value)`.
pub fn putmask(&self, mask: &[bool], value: &IndexLabel) -> Result<Self, IndexError> {
if mask.len() != self.labels.len() {
return Err(IndexError::LengthMismatch {
expected: self.labels.len(),
actual: mask.len(),
context: "putmask: mask length must match index length".to_owned(),
});
}
let value = self.placeable(value, "putmask")?;
let labels: Vec<IndexLabel> = self
.labels
.iter()
.zip(mask.iter())
.map(|(label, &replace)| {
if replace {
value.clone()
} else {
label.clone()
}
})
.collect();
Ok(Self::from_parts(
labels,
self.categories.clone(),
self.ordered,
self.name.clone(),
))
}
/// Alias for [`isna`](Self::isna), matching `pd.CategoricalIndex.isnull()`.
#[must_use]
pub fn isnull(&self) -> Vec<bool> {
self.isna()
}
/// Alias for [`notna`](Self::notna), matching `pd.CategoricalIndex.notnull()`.
#[must_use]
pub fn notnull(&self) -> Vec<bool> {
self.notna()
}
/// Whether any label is missing, matching `pd.CategoricalIndex.hasnans`
/// (it was always false: no label could be missing).
#[must_use]
pub fn hasnans(&self) -> bool {
self.labels.iter().any(IndexLabel::is_missing)
}
/// Drop missing positions, matching `pd.CategoricalIndex.dropna()`.
#[must_use]
pub fn dropna(&self) -> Self {
Self::from_parts(
self.labels
.iter()
.filter(|label| !label.is_missing())
.cloned()
.collect(),
self.categories.clone(),
self.ordered,
self.name.clone(),
)
}
/// Fill missing positions with `value`, matching
/// `pd.CategoricalIndex.fillna(value)`: with nothing missing the index is
/// unchanged; otherwise `value` must be a category (it was ignored).
pub fn fillna(&self, value: &IndexLabel) -> Result<Self, IndexError> {
if !self.hasnans() {
return Ok(self.clone());
}
let value = self.placeable(value, "fillna")?;
Ok(Self::from_parts(
self.labels
.iter()
.map(|label| {
if label.is_missing() {
value.clone()
} else {
label.clone()
}
})
.collect(),
self.categories.clone(),
self.ordered,
self.name.clone(),
))
}
/// Mark the categorical as ordered, matching
/// `pd.CategoricalIndex.as_ordered()`.
#[must_use]
pub fn as_ordered(&self) -> Self {
let mut out = self.clone();
out.ordered = true;
out
}
/// Mark the categorical as unordered, matching
/// `pd.CategoricalIndex.as_unordered()`.
#[must_use]
pub fn as_unordered(&self) -> Self {
let mut out = self.clone();
out.ordered = false;
out
}
/// Extend the categories list with new entries, matching
/// `pd.CategoricalIndex.add_categories(new)`. Rejects when any new
/// category is already present.
pub fn add_categories<L: Into<IndexLabel>>(&self, new: Vec<L>) -> Result<Self, IndexError> {
let new: Vec<IndexLabel> = new.into_iter().map(Into::into).collect();
// O(k_existing + k_new): hash the existing categories once instead of a
// linear `categories.contains` scan per new entry. First clashing entry
// (in `new` order) is still the one reported.
let existing: FxHashSet<&IndexLabel> = self.categories.iter().collect();
for cat in &new {
if existing.contains(cat) {
return Err(IndexError::InvalidArgument(format!(
"add_categories: {cat:?} is already a category"
)));
}
}
let mut categories = self.categories.clone();
categories.extend(new);
Ok(Self::from_parts(
self.labels.clone(),
categories,
self.ordered,
self.name.clone(),
))
}
/// Drop categories from the list, matching
/// `pd.CategoricalIndex.remove_categories(removals)`: each must be a
/// category, and a label of a removed one becomes NaN (it was refused,
/// no label could be missing; lztvp).
pub fn remove_categories(&self, removals: &[IndexLabel]) -> Result<Self, IndexError> {
let category_set: FxHashSet<&IndexLabel> = self.categories.iter().collect();
for cat in removals {
if !category_set.contains(cat) {
return Err(IndexError::InvalidArgument(format!(
"remove_categories: {cat:?} is not a category"
)));
}
}
let removals_set: FxHashSet<&IndexLabel> = removals.iter().collect();
let categories: Vec<IndexLabel> = self
.categories
.iter()
.filter(|cat| !removals_set.contains(cat))
.cloned()
.collect();
Ok(self.recategorized(categories, self.ordered))
}
/// This index over `categories`: a label no longer among them is NaN,
/// as pandas' `set_categories` / `remove_categories`.
fn recategorized(&self, categories: Vec<IndexLabel>, ordered: bool) -> Self {
let kept: FxHashSet<&IndexLabel> = categories.iter().collect();
let labels: Vec<IndexLabel> = self
.labels
.iter()
.map(|label| {
if kept.contains(label) {
label.clone()
} else {
IndexLabel::Null(fp_types::NullKind::NaN)
}
})
.collect();
drop(kept);
Self::from_parts(labels, categories, ordered, self.name.clone())
}
/// Narrow categories to the set of labels actually present, matching
/// `pd.CategoricalIndex.remove_unused_categories()`.
#[must_use]
pub fn remove_unused_categories(&self) -> Self {
let used: FxHashSet<&IndexLabel> = self.labels.iter().collect();
let categories: Vec<IndexLabel> = self
.categories
.iter()
.filter(|cat| used.contains(cat))
.cloned()
.collect();
Self::from_parts(
self.labels.clone(),
categories,
self.ordered,
self.name.clone(),
)
}
/// Replace the categories list, matching
/// `pd.CategoricalIndex.set_categories(new_categories)`: a label not
/// among the new categories becomes NaN (it was refused; lztvp).
pub fn set_categories<L: Into<IndexLabel>>(
&self,
new_categories: Vec<L>,
) -> Result<Self, IndexError> {
let new_categories: Vec<IndexLabel> = new_categories.into_iter().map(Into::into).collect();
let mut seen = FxHashSet::<&IndexLabel>::default();
if !new_categories.iter().all(|cat| seen.insert(cat)) {
return Err(IndexError::InvalidArgument(
"Categorical categories must be unique".to_owned(),
));
}
drop(seen);
Ok(self.recategorized(new_categories, self.ordered))
}
/// Rename categories pos-by-pos, matching
/// `pd.CategoricalIndex.rename_categories(new)`. Rejects when the
/// new list has a different length; a missing label stays missing.
pub fn rename_categories<L: Into<IndexLabel>>(&self, new: Vec<L>) -> Result<Self, IndexError> {
let new: Vec<IndexLabel> = new.into_iter().map(Into::into).collect();
if new.len() != self.categories.len() {
return Err(IndexError::InvalidArgument(format!(
"rename_categories: expected {} new names, got {}",
self.categories.len(),
new.len()
)));
}
let mapping: FxHashMap<&IndexLabel, &IndexLabel> =
self.categories.iter().zip(new.iter()).collect();
let labels: Vec<IndexLabel> = self
.labels
.iter()
.map(|label| {
mapping
.get(label)
.map_or_else(|| label.clone(), |to| (*to).clone())
})
.collect();
drop(mapping);
Ok(Self::from_parts(
labels,
new,
self.ordered,
self.name.clone(),
))
}
/// Reorder the categories list, matching
/// `pd.CategoricalIndex.reorder_categories(new, ordered)`. Rejects
/// when the new list is not a permutation of the existing categories.
pub fn reorder_categories<L: Into<IndexLabel>>(
&self,
new: Vec<L>,
ordered: bool,
) -> Result<Self, IndexError> {
let new: Vec<IndexLabel> = new.into_iter().map(Into::into).collect();
if new.len() != self.categories.len() {
return Err(IndexError::InvalidArgument(format!(
"reorder_categories: expected {} categories, got {}",
self.categories.len(),
new.len()
)));
}
let existing: FxHashSet<&IndexLabel> = self.categories.iter().collect();
for cat in &new {
if !existing.contains(cat) {
return Err(IndexError::InvalidArgument(format!(
"reorder_categories: {cat:?} is not an existing category"
)));
}
}
let new_set: FxHashSet<&IndexLabel> = new.iter().collect();
if new_set.len() != new.len() {
return Err(IndexError::InvalidArgument(
"reorder_categories: new categories contain duplicates".to_owned(),
));
}
Ok(Self::from_parts(
self.labels.clone(),
new,
ordered,
self.name.clone(),
))
}
/// Convert to a flat [`Index`] of utf8 labels, matching
/// `pd.CategoricalIndex.to_flat_index()`.
#[must_use]
pub fn to_flat_index(&self) -> Index {
self.to_index()
}
/// String accessor for categorical string labels.
#[must_use]
pub fn r#str(&self) -> IndexStringAccessor<'_> {
IndexStringAccessor::owned(self.to_flat_index())
}
/// One-column row materialization, matching `pd.CategoricalIndex.to_frame(index=False)`.
#[must_use]
pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
self.to_flat_index().to_frame()
}
/// Series-shaped materialization using category labels as both index and values.
#[must_use]
pub fn to_series(&self) -> Vec<(IndexLabel, IndexLabel)> {
self.to_flat_index().to_series()
}
/// Whether any category label coerces to true.
#[must_use]
pub fn any(&self) -> bool {
self.to_flat_index().any()
}
/// Whether all category labels coerce to true.
#[must_use]
pub fn all(&self) -> bool {
self.to_flat_index().all()
}
/// Get labels for a level. CategoricalIndex is flat and only accepts level 0.
pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
self.to_flat_index().get_level_values(level)
}
/// Drop a level. CategoricalIndex is flat, so removing its only level is invalid.
pub fn droplevel(&self, level: usize) -> Result<Index, IndexError> {
self.to_flat_index().droplevel(level)
}
/// Group equal category labels into position buckets.
#[must_use]
pub fn groupby(&self) -> HashMap<IndexLabel, Vec<usize>> {
self.to_flat_index().groupby()
}
/// Apply a function to each category label, returning a flat Index.
#[must_use]
pub fn map<F>(&self, func: F) -> Index
where
F: Fn(&IndexLabel) -> IndexLabel,
{
self.to_flat_index().map(func)
}
/// Cast category labels to a pandas dtype string, returning a flat Index.
pub fn astype(&self, dtype: &str) -> Result<Index, IndexError> {
self.to_flat_index().astype(dtype)
}
/// Nearest preceding-or-equal category label lookup.
#[must_use]
pub fn asof(&self, key: &IndexLabel) -> Option<IndexLabel> {
self.to_flat_index().asof(key)
}
/// Locate nearest preceding-or-equal category positions for each target label.
#[must_use]
pub fn asof_locs(&self, where_index: &Index, mask: Option<&[bool]>) -> Vec<Option<usize>> {
self.to_flat_index().asof_locs(where_index, mask)
}
/// Drop category labels, returning a flat Index.
#[must_use]
pub fn drop(&self, labels_to_drop: &[IndexLabel]) -> Index {
self.to_flat_index().drop(labels_to_drop)
}
/// Join category labels with another flat Index.
pub fn join(&self, other: &Index, how: &str) -> Result<Index, IndexError> {
self.to_flat_index().join(other, how)
}
/// Sort category labels and return the positional sorter.
#[must_use]
pub fn sortlevel(&self) -> (Index, Vec<usize>) {
self.to_flat_index().sortlevel()
}
/// Set the index name, matching `pd.CategoricalIndex.rename(name)`.
#[must_use]
pub fn rename(&self, name: &str) -> Self {
self.set_name(name)
}
/// Returns a clone, matching `pd.CategoricalIndex.view()`.
#[must_use]
pub fn view(&self) -> Self {
self.clone()
}
/// Identity transpose for a 1D index, matching
/// `pd.CategoricalIndex.transpose()`.
#[must_use]
pub fn transpose(&self) -> Self {
self.clone()
}
/// Alias for `transpose`, matching `pd.CategoricalIndex.T`.
#[allow(non_snake_case)]
#[must_use]
pub fn T(&self) -> Self {
self.transpose()
}
/// Flatten the labels, matching `pd.CategoricalIndex.ravel()`.
#[must_use]
pub fn ravel(&self) -> Vec<IndexLabel> {
self.labels.clone()
}
/// Number of levels, matching `pd.CategoricalIndex.nlevels`. Always `1`.
#[must_use]
pub fn nlevels(&self) -> usize {
1
}
/// Identity dtype-reinference, matching
/// `pd.CategoricalIndex.infer_objects()`.
#[must_use]
pub fn infer_objects(&self) -> Self {
self.clone()
}
/// Binary-search insertion position, matching
/// `pd.CategoricalIndex.searchsorted(value, side)`. Forwarded through
/// the labels' flat Index.
pub fn searchsorted(&self, value: &IndexLabel, side: &str) -> Result<usize, IndexError> {
self.to_index().searchsorted(value, side)
}
/// Find positions of `[start, end]` for a label slice, matching
/// `pd.CategoricalIndex.slice_locs(start, end)`. Requires labels to
/// be sorted (so the searchsorted result lines up with the slice
/// boundary).
pub fn slice_locs(
&self,
start: &IndexLabel,
end: &IndexLabel,
) -> Result<(usize, usize), IndexError> {
let labels_sorted = self.labels.windows(2).all(|w| w[0] <= w[1]);
if !labels_sorted {
return Err(IndexError::InvalidArgument(
"slice_locs requires a CategoricalIndex with labels sorted lexicographically"
.to_owned(),
));
}
let left = self.searchsorted(start, "left")?;
let right = self.searchsorted(end, "right")?;
Ok((left, right))
}
/// Half-open positional range for a label slice, matching
/// `pd.CategoricalIndex.slice_indexer(start, end)`.
pub fn slice_indexer(
&self,
start: &IndexLabel,
end: &IndexLabel,
) -> Result<std::ops::Range<usize>, IndexError> {
let (l, r) = self.slice_locs(start, end)?;
Ok(l..r)
}
fn set_op_via_string<F>(&self, other: &Self, op: F) -> Self
where
F: FnOnce(Vec<&IndexLabel>, Vec<&IndexLabel>) -> Vec<IndexLabel>,
{
let labels = op(self.labels.iter().collect(), other.labels.iter().collect());
// Dedup the union of categories with a seen-set instead of an O(k)
// `Vec::contains` per label (O(n·k) for high-cardinality categoricals).
// `seen` borrows self.categories + labels (both stable) — never the
// growing `categories` Vec — so a label is pushed iff it is neither an
// existing category nor already pushed this pass: identical first-seen
// order and dedup to the linear scan.
let mut categories: Vec<IndexLabel> = self.categories.clone();
let mut seen: FxHashSet<&IndexLabel> = self.categories.iter().collect();
for label in &labels {
if !label.is_missing() && seen.insert(label) {
categories.push(label.clone());
}
}
Self::from_parts(
labels,
categories,
self.ordered,
if self.name == other.name {
self.name.clone()
} else {
None
},
)
}
/// Labels in both indexes (first-seen order from self), matching
/// `pd.CategoricalIndex.intersection(other)`.
#[must_use]
pub fn intersection(&self, other: &Self) -> Self {
self.set_op_via_string(other, |left, right| {
let right_set: FxHashSet<&&IndexLabel> = right.iter().collect();
let mut seen = FxHashSet::<&IndexLabel>::default();
left.into_iter()
.filter(|label| right_set.contains(label) && seen.insert(label))
.cloned()
.collect()
})
}
/// Self labels then other labels not seen, matching
/// `pd.CategoricalIndex.union(other)`.
#[must_use]
pub fn union(&self, other: &Self) -> Self {
self.set_op_via_string(other, |left, right| {
let mut seen = FxHashSet::<&IndexLabel>::default();
left.into_iter()
.chain(right)
.filter(|label| seen.insert(label))
.cloned()
.collect()
})
}
/// Labels in either but not both, matching
/// `pd.CategoricalIndex.symmetric_difference(other)`.
#[must_use]
pub fn symmetric_difference(&self, other: &Self) -> Self {
self.set_op_via_string(other, |left, right| {
let left_set: FxHashSet<&&IndexLabel> = left.iter().collect();
let right_set: FxHashSet<&&IndexLabel> = right.iter().collect();
let mut seen = FxHashSet::<&IndexLabel>::default();
let mut out = Vec::<IndexLabel>::new();
for label in &left {
if !right_set.contains(label) && seen.insert(*label) {
out.push((*label).clone());
}
}
for label in &right {
if !left_set.contains(label) && seen.insert(*label) {
out.push((*label).clone());
}
}
out
})
}
/// Self labels not in other, matching
/// `pd.CategoricalIndex.difference(other)`.
#[must_use]
pub fn difference(&self, other: &Self) -> Self {
// Per br-frankenpandas-6r1lq: difference preserves self.name (not
// shared_name like set_op_via_string applies for union/intersection).
let mut out = self.set_op_via_string(other, |left, right| {
let right_set: FxHashSet<&&IndexLabel> = right.iter().collect();
let mut seen = FxHashSet::<&IndexLabel>::default();
left.into_iter()
.filter(|label| !right_set.contains(label) && seen.insert(label))
.cloned()
.collect()
});
out.name = self.name.clone();
out
}
/// Sort labels ascending, matching `pd.CategoricalIndex.sort_values()`.
/// `ordered=true` sorts by category position; `ordered=false` sorts
/// lexicographically. Categories list and ordered flag are preserved.
#[must_use]
pub fn sort_values(&self) -> Self {
let positions = self.argsort();
let labels: Vec<IndexLabel> = positions.iter().map(|&p| self.labels[p].clone()).collect();
Self::from_parts(
labels,
self.categories.clone(),
self.ordered,
self.name.clone(),
)
}
/// Alias for `sort_values`, matching `pd.CategoricalIndex.sort()`.
#[must_use]
pub fn sort(&self) -> Self {
self.sort_values()
}
/// Positions that would sort labels ascending, matching
/// `pd.CategoricalIndex.argsort()`.
///
/// pandas sorts a Categorical by its **category codes** — the position of
/// each label within `categories` — for both ordered and unordered
/// categoricals (`Categorical._values_for_argsort` returns `self.codes`),
/// NOT lexicographically by the label text. So categories `[b, a, c]` sort
/// before-`a` because `b` has code 0. The sort is stable, so equal-code
/// ties keep their original order; a missing label (no code) sorts last,
/// as pandas' na_position='last'.
#[must_use]
pub fn argsort(&self) -> Vec<usize> {
let map = self.category_index_map();
let mut positions: Vec<usize> = (0..self.labels.len()).collect();
positions.sort_by_key(|&i| map.get(&self.labels[i]).copied().unwrap_or(usize::MAX));
positions
}
/// Concatenate with another CategoricalIndex, matching
/// `pd.CategoricalIndex.append(other)`. Categories merge
/// (other-only categories are appended) and the index name is
/// preserved when both operands share it.
#[must_use]
pub fn append(&self, other: &Self) -> Self {
let mut labels = self.labels.clone();
labels.extend_from_slice(&other.labels);
// Union categories with a seen-set, not O(k) `Vec::contains` per entry
// (see set_op_via_string). `seen` borrows self/other categories, never
// the growing `categories` Vec; identical first-seen order + dedup.
let mut categories = self.categories.clone();
let mut seen: FxHashSet<&IndexLabel> = self.categories.iter().collect();
for cat in &other.categories {
if seen.insert(cat) {
categories.push(cat.clone());
}
}
let name = if self.name == other.name {
self.name.clone()
} else {
None
};
Self::from_parts(labels, categories, self.ordered && other.ordered, name)
}
/// Remove the label at the given position, matching
/// `pd.CategoricalIndex.delete(loc)`. OOB raises.
pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
if loc >= self.labels.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: self.labels.len(),
});
}
let mut labels = self.labels.clone();
labels.remove(loc);
Ok(Self::from_parts(
labels,
self.categories.clone(),
self.ordered,
self.name.clone(),
))
}
/// Insert `value` at position `loc`, matching
/// `pd.CategoricalIndex.insert(loc, value)`. The value must be a
/// category or missing; OOB and not-a-category raise.
pub fn insert(&self, loc: usize, value: &IndexLabel) -> Result<Self, IndexError> {
if loc > self.labels.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: self.labels.len(),
});
}
let value = self.placeable(value, "insert")?;
let mut labels = self.labels.clone();
labels.insert(loc, value);
Ok(Self::from_parts(
labels,
self.categories.clone(),
self.ordered,
self.name.clone(),
))
}
/// Repeat each label `repeats` times, matching
/// `pd.CategoricalIndex.repeat(repeats)`.
#[must_use]
pub fn repeat(&self, repeats: usize) -> Self {
let mut labels = Vec::with_capacity(repeat_output_capacity(self.labels.len(), repeats));
for label in &self.labels {
for _ in 0..repeats {
labels.push(label.clone());
}
}
Self::from_parts(
labels,
self.categories.clone(),
self.ordered,
self.name.clone(),
)
}
/// Pick labels at the given positions, matching
/// `pd.CategoricalIndex.take(positions)`. Out-of-bounds positions
/// raise [`IndexError::OutOfBounds`].
pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
for &p in positions {
if p >= self.labels.len() {
return Err(IndexError::OutOfBounds {
position: p,
length: self.labels.len(),
});
}
}
let labels: Vec<IndexLabel> = positions.iter().map(|&p| self.labels[p].clone()).collect();
Ok(Self::from_parts(
labels,
self.categories.clone(),
self.ordered,
self.name.clone(),
))
}
/// Per-position membership mask, matching
/// `pd.CategoricalIndex.isin(values)`.
#[must_use]
pub fn isin(&self, values: &[IndexLabel]) -> Vec<bool> {
let needle: FxHashSet<&IndexLabel> = values.iter().collect();
self.labels.iter().map(|l| needle.contains(l)).collect()
}
/// Locate every position matching each target, matching
/// `pd.CategoricalIndex.get_indexer_non_unique(targets)`.
#[must_use]
pub fn get_indexer_non_unique(&self, targets: &[IndexLabel]) -> (Vec<isize>, Vec<usize>) {
let mut by_value = FxHashMap::<&IndexLabel, Vec<usize>>::default();
for (i, label) in self.labels.iter().enumerate() {
by_value.entry(label).or_default().push(i);
}
let mut positions = Vec::<isize>::new();
let mut missing = Vec::<usize>::new();
for (idx, target) in targets.iter().enumerate() {
if let Some(matches) = by_value.get(target) {
positions.extend(
matches
.iter()
.map(|p| isize::try_from(*p).unwrap_or(isize::MAX)),
);
} else {
positions.push(-1);
missing.push(idx);
}
}
(positions, missing)
}
/// Locate each label in `targets`, matching
/// `pd.CategoricalIndex.get_indexer(targets)`.
#[must_use]
pub fn get_indexer(&self, targets: &[IndexLabel]) -> Vec<isize> {
let mut positions = FxHashMap::<&IndexLabel, isize>::default();
for (i, label) in self.labels.iter().enumerate() {
positions
.entry(label)
.or_insert_with(|| isize::try_from(i).unwrap_or(isize::MAX));
}
targets
.iter()
.map(|t| positions.get(t).copied().unwrap_or(-1))
.collect()
}
/// Alias for [`get_indexer`](Self::get_indexer), matching
/// `pd.CategoricalIndex.get_indexer_for(targets)`.
#[must_use]
pub fn get_indexer_for(&self, targets: &[IndexLabel]) -> Vec<isize> {
self.get_indexer(targets)
}
/// First position of `value`, matching
/// `pd.CategoricalIndex.get_loc(value)`.
pub fn get_loc(&self, value: &IndexLabel) -> Result<usize, IndexError> {
self.labels.iter().position(|l| l == value).ok_or_else(|| {
IndexError::InvalidArgument(format!("get_loc: {value:?} not in CategoricalIndex"))
})
}
/// Position of the maximum label, matching
/// `pd.CategoricalIndex.argmax()`. ordered=true uses category
/// position; unordered uses lexicographic ordering. Empty raises
/// pandas-style "attempt to get argmax of an empty sequence".
pub fn argmax(&self) -> Result<usize, IndexError> {
if self.labels.is_empty() {
return Err(IndexError::InvalidArgument(
"attempt to get argmax of an empty sequence".to_owned(),
));
}
self.extreme_position(true).ok_or_else(|| {
IndexError::InvalidArgument("attempt to get argmax of an empty sequence".to_owned())
})
}
/// The position of the first largest (`largest`) or smallest label,
/// missing labels skipped: by category position when ordered, by the
/// labels themselves otherwise. None when no label is present.
fn extreme_position(&self, largest: bool) -> Option<usize> {
let map = self.category_index_map();
let mut best: Option<usize> = None;
for (i, label) in self.labels.iter().enumerate() {
if label.is_missing() {
continue;
}
let better = best.is_none_or(|at| {
let current = &self.labels[at];
let order = if self.ordered {
map.get(label).cmp(&map.get(current))
} else {
label.cmp(current)
};
if largest {
order.is_gt()
} else {
order.is_lt()
}
});
if better {
best = Some(i);
}
}
best
}
/// Position of the minimum label, matching
/// `pd.CategoricalIndex.argmin()`. Same ordering rules as argmax.
pub fn argmin(&self) -> Result<usize, IndexError> {
if self.labels.is_empty() {
return Err(IndexError::InvalidArgument(
"attempt to get argmin of an empty sequence".to_owned(),
));
}
self.extreme_position(false).ok_or_else(|| {
IndexError::InvalidArgument("attempt to get argmin of an empty sequence".to_owned())
})
}
/// Smallest label in category order when ordered, by the labels
/// themselves when unordered, matching `pd.CategoricalIndex.min()`
/// (missing labels skipped). None when no label is present.
#[must_use]
pub fn min(&self) -> Option<&IndexLabel> {
self.extreme_position(false).map(|at| &self.labels[at])
}
/// Largest label, matching `pd.CategoricalIndex.max()`.
#[must_use]
pub fn max(&self) -> Option<&IndexLabel> {
self.extreme_position(true).map(|at| &self.labels[at])
}
/// First-seen unique labels, matching `pd.CategoricalIndex.unique()`.
/// Categories are preserved (not narrowed to seen labels) and the
/// ordered flag rolls through. The result keeps the index name.
#[must_use]
pub fn unique(&self) -> Self {
if let Some(codes) = &self.category_codes
&& self.category_rank_unique_scan_is_bounded()
{
return self.unique_by_category_codes(codes);
}
let labels = if self.category_rank_unique_scan_is_bounded() {
self.unique_labels_by_category_rank()
} else {
self.unique_labels_by_hash()
};
Self::from_parts(
labels,
self.categories.clone(),
self.ordered,
self.name.clone(),
)
}
/// Per-position duplicate mask, matching
/// `pd.CategoricalIndex.duplicated(keep)`.
#[must_use]
pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
if let Some(codes) = &self.category_codes {
if self.category_rank_unique_scan_is_bounded() {
return self.duplicated_by_category_codes(codes, keep);
}
return self.duplicated_by_hash(keep);
}
if self.category_rank_unique_scan_is_bounded() {
return self.duplicated_by_category_rank(keep);
}
self.duplicated_by_hash(keep)
}
/// Drop duplicate labels (keep first), matching
/// `pd.CategoricalIndex.drop_duplicates()`. Categories and ordered
/// flag are preserved.
#[must_use]
pub fn drop_duplicates(&self) -> Self {
self.unique()
}
/// Value counts, matching `pd.CategoricalIndex.value_counts()`: the
/// present labels' counts, missing ones left out (dropna).
#[must_use]
pub fn value_counts(&self) -> Vec<(IndexLabel, usize)> {
let mut pairs = if let Some(codes) = &self.category_codes {
self.value_counts_by_category_codes(codes)
} else if self.category_rank_unique_scan_is_bounded() {
self.value_counts_by_category_rank()
} else {
self.value_counts_by_hash()
};
pairs.retain(|(label, _)| !label.is_missing());
pairs
}
/// Factorize, matching `pd.CategoricalIndex.factorize()`. Returns
/// `(codes, uniques)` where `uniques` is a CategoricalIndex with
/// the same categories list; a missing label's code is -1, and it is
/// no unique.
#[must_use]
pub fn factorize(&self) -> (Vec<isize>, Self) {
let (mut codes, mut uniques) = if let Some(codes) = &self.category_codes {
self.factorize_by_category_codes(codes)
} else if self.category_rank_unique_scan_is_bounded() {
self.factorize_by_category_rank()
} else {
self.factorize_by_hash()
};
if let Some(missing) = uniques.labels.iter().position(IndexLabel::is_missing) {
let missing = isize::try_from(missing).unwrap_or(isize::MAX);
for code in &mut codes {
if *code == missing {
*code = -1;
} else if *code > missing {
*code -= 1;
}
}
uniques = uniques.dropna();
}
(codes, uniques)
}
}
// ── IntervalIndex ──────────────────────────────────────────────────────────
/// An index of `Interval` objects (`pd.IntervalIndex`).
///
/// An immutable index of half-open, closed, or open intervals.
/// Backed by float64 endpoints with configurable closed semantics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IntervalIndex {
values: Vec<Interval>,
closed: IntervalClosed,
name: Option<LabelName>,
}
impl IntervalIndex {
/// Construct a new `IntervalIndex` from a vector of `Interval`s.
#[must_use]
pub fn new(values: Vec<Interval>) -> Self {
let closed = values.first().map_or(IntervalClosed::Right, |iv| iv.closed);
Self {
values,
closed,
name: None,
}
}
/// Construct a new `IntervalIndex` with explicit closed policy and name.
#[must_use]
pub fn new_with_options(
values: Vec<Interval>,
closed: IntervalClosed,
name: Option<String>,
) -> Self {
Self {
values,
closed,
name: name.map(LabelName::from),
}
}
/// Construct an `IntervalIndex` from endpoint breaks (`pd.IntervalIndex.from_breaks`).
///
/// # Errors
/// Returns `IndexError::InvalidArgument` if breaks has fewer than 2 elements.
pub fn from_breaks(breaks: &[f64], closed: IntervalClosed) -> Result<Self, IndexError> {
if breaks.len() < 2 {
return Err(IndexError::InvalidArgument(
"breaks must have at least 2 elements".to_string(),
));
}
let mut values = Vec::with_capacity(breaks.len() - 1);
for i in 0..(breaks.len() - 1) {
values.push(Interval::new(breaks[i], breaks[i + 1], closed));
}
Ok(Self {
values,
closed,
name: None,
})
}
/// Construct an `IntervalIndex` from (left, right) tuples (`pd.IntervalIndex.from_tuples`).
#[must_use]
pub fn from_tuples(tuples: &[(f64, f64)], closed: IntervalClosed) -> Self {
let mut values = Vec::with_capacity(tuples.len());
for &(left, right) in tuples {
values.push(Interval::new(left, right, closed));
}
Self {
values,
closed,
name: None,
}
}
/// Construct an `IntervalIndex` from separate left and right arrays (`pd.IntervalIndex.from_arrays`).
///
/// # Errors
/// Returns `IndexError::LengthMismatch` if left and right arrays have different lengths.
pub fn from_arrays(
left: &[f64],
right: &[f64],
closed: IntervalClosed,
) -> Result<Self, IndexError> {
if left.len() != right.len() {
return Err(IndexError::LengthMismatch {
expected: left.len(),
actual: right.len(),
context: "IntervalIndex.from_arrays left and right arrays must have equal length"
.to_string(),
});
}
let mut values = Vec::with_capacity(left.len());
for (&l, &r) in left.iter().zip(right.iter()) {
values.push(Interval::new(l, r, closed));
}
Ok(Self {
values,
closed,
name: None,
})
}
/// Construct an `IntervalIndex` from a range specification (`pd.interval_range`).
///
/// # Errors
/// Returns `IndexError::InvalidArgument` if parameters are invalid.
pub fn from_range(
start: Option<f64>,
end: Option<f64>,
periods: Option<usize>,
freq: Option<f64>,
closed: Option<IntervalClosed>,
) -> Result<Self, IndexError> {
let closed_val = closed.unwrap_or(IntervalClosed::Right);
let values = interval_range(start, end, periods, freq, closed)
.map_err(|e| IndexError::InvalidArgument(e.to_string()))?;
Ok(Self {
values,
closed: closed_val,
name: None,
})
}
#[must_use]
pub fn values(&self) -> &[Interval] {
&self.values
}
#[must_use]
pub fn len(&self) -> usize {
self.values.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
#[must_use]
pub fn closed(&self) -> IntervalClosed {
self.closed
}
#[must_use]
pub fn name(&self) -> Option<&LabelName> {
self.name.as_ref()
}
#[must_use]
pub fn set_name<N: Into<LabelName>>(&self, name: N) -> Self {
let mut out = self.clone();
out.name = Some(name.into());
out
}
#[must_use]
pub fn set_names<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
let mut out = self.clone();
out.name = name.map(Into::into);
out
}
#[must_use]
pub fn rename_index<N: Into<LabelName>>(&self, name: Option<N>) -> Self {
self.set_names(name)
}
#[must_use]
pub fn names(&self) -> Vec<Option<String>> {
vec![self.name.clone().map(String::from)]
}
#[must_use]
pub fn copy(&self) -> Self {
self.clone()
}
#[must_use]
pub fn shape(&self) -> (usize,) {
(self.len(),)
}
#[must_use]
pub fn size(&self) -> usize {
self.len()
}
#[must_use]
pub fn empty(&self) -> bool {
self.is_empty()
}
#[must_use]
pub fn dtype(&self) -> String {
format!("interval[float64, {}]", self.closed)
}
#[must_use]
pub fn dtypes(&self) -> Vec<String> {
vec![self.dtype()]
}
#[must_use]
pub fn hasnans(&self) -> bool {
false
}
#[must_use]
pub fn isna(&self) -> Vec<bool> {
vec![false; self.len()]
}
#[must_use]
pub fn isnull(&self) -> Vec<bool> {
self.isna()
}
#[must_use]
pub fn notna(&self) -> Vec<bool> {
vec![true; self.len()]
}
#[must_use]
pub fn notnull(&self) -> Vec<bool> {
self.notna()
}
#[must_use]
pub fn dropna(&self) -> Self {
self.clone()
}
/// Return an `Index` containing the left endpoints of each interval.
#[must_use]
pub fn left(&self) -> Index {
let labels = self
.values
.iter()
.map(|iv| IndexLabel::Float64(OrderedF64(iv.left)))
.collect();
Index::new(labels)
}
/// Return an `Index` containing the right endpoints of each interval.
#[must_use]
pub fn right(&self) -> Index {
let labels = self
.values
.iter()
.map(|iv| IndexLabel::Float64(OrderedF64(iv.right)))
.collect();
Index::new(labels)
}
/// Return an `Index` containing the midpoint `(left + right) / 2` of each interval.
#[must_use]
pub fn mid(&self) -> Index {
let labels = self
.values
.iter()
.map(|iv| IndexLabel::Float64(OrderedF64(iv.mid())))
.collect();
Index::new(labels)
}
/// Return an `Index` containing the length `right - left` of each interval.
#[must_use]
pub fn length(&self) -> Index {
let labels = self
.values
.iter()
.map(|iv| IndexLabel::Float64(OrderedF64(iv.length())))
.collect();
Index::new(labels)
}
/// True if any two intervals in the index overlap.
#[must_use]
pub fn is_overlapping(&self) -> bool {
let len = self.values.len();
if len < 2 {
return false;
}
for i in 0..len {
for j in (i + 1)..len {
if self.values[i].overlaps(&self.values[j]) {
return true;
}
}
}
false
}
/// Check if each interval overlaps with the given interval.
#[must_use]
pub fn overlaps(&self, other: &Interval) -> Vec<bool> {
self.values.iter().map(|iv| iv.overlaps(other)).collect()
}
/// Check if each interval contains the given scalar point.
#[must_use]
pub fn contains(&self, point: f64) -> Vec<bool> {
self.values.iter().map(|iv| iv.contains(point)).collect()
}
/// Return the integer position of the interval containing the query scalar point.
///
/// # Errors
/// Returns `IndexError::InvalidArgument` if no interval contains `point`, or if
/// multiple overlapping intervals contain `point`.
pub fn get_loc(&self, point: f64) -> Result<usize, IndexError> {
let mut found = None;
for (i, iv) in self.values.iter().enumerate() {
if iv.contains(point) {
if found.is_some() {
return Err(IndexError::InvalidArgument(format!(
"point {point} overlaps multiple intervals"
)));
}
found = Some(i);
}
}
found.ok_or_else(|| {
IndexError::InvalidArgument(format!("point {point} not found in IntervalIndex"))
})
}
/// Return the integer position of an exact matching `Interval`.
///
/// # Errors
/// Returns `IndexError::InvalidArgument` if target interval is not in the index.
pub fn get_loc_interval(&self, target: &Interval) -> Result<usize, IndexError> {
self.values
.iter()
.position(|iv| {
OrderedF64(iv.left) == OrderedF64(target.left)
&& OrderedF64(iv.right) == OrderedF64(target.right)
&& iv.closed == target.closed
})
.ok_or_else(|| {
IndexError::InvalidArgument(format!(
"interval {target:?} not found in IntervalIndex"
))
})
}
/// Compute positional indexer for target points.
#[must_use]
pub fn get_indexer(&self, target: &[f64]) -> Vec<Option<usize>> {
target.iter().map(|&pt| self.get_loc(pt).ok()).collect()
}
/// Return a new `IntervalIndex` with specified `closed` semantics.
#[must_use]
pub fn set_closed(&self, closed: IntervalClosed) -> Self {
let values = self
.values
.iter()
.map(|iv| Interval::new(iv.left, iv.right, closed))
.collect();
Self {
values,
closed,
name: self.name.clone(),
}
}
/// Convert to a standard `Index` with string representations.
#[must_use]
pub fn to_index(&self) -> Index {
let labels = self
.values
.iter()
.map(|iv| IndexLabel::Utf8(format!("{iv}")))
.collect();
let mut idx = Index::new(labels);
if let Some(name) = &self.name {
idx = idx.set_name(name);
}
idx
}
#[must_use]
pub fn is_unique(&self) -> bool {
let len = self.values.len();
if len < 2 {
return true;
}
for i in 0..len {
for j in (i + 1)..len {
if OrderedF64(self.values[i].left) == OrderedF64(self.values[j].left)
&& OrderedF64(self.values[i].right) == OrderedF64(self.values[j].right)
&& self.values[i].closed == self.values[j].closed
{
return false;
}
}
}
true
}
#[must_use]
pub fn is_monotonic_increasing(&self) -> bool {
if self.values.len() < 2 {
return true;
}
for w in self.values.windows(2) {
let left_cmp = OrderedF64(w[0].left).cmp(&OrderedF64(w[1].left));
if left_cmp.is_gt() {
return false;
}
if left_cmp.is_eq() && OrderedF64(w[0].right).cmp(&OrderedF64(w[1].right)).is_gt() {
return false;
}
}
true
}
#[must_use]
pub fn is_monotonic_decreasing(&self) -> bool {
if self.values.len() < 2 {
return true;
}
for w in self.values.windows(2) {
let left_cmp = OrderedF64(w[0].left).cmp(&OrderedF64(w[1].left));
if left_cmp.is_lt() {
return false;
}
if left_cmp.is_eq() && OrderedF64(w[0].right).cmp(&OrderedF64(w[1].right)).is_lt() {
return false;
}
}
true
}
/// Get interval at integer position (supports negative indexing).
///
/// # Errors
/// Returns `IndexError::OutOfBounds` if `idx` is out of range.
pub fn get_item(&self, idx: isize) -> Result<Interval, IndexError> {
let len = self.values.len() as isize;
let pos = if idx < 0 { idx + len } else { idx };
if pos < 0 || pos >= len {
return Err(IndexError::OutOfBounds {
position: if idx < 0 {
idx.unsigned_abs()
} else {
idx as usize
},
length: self.values.len(),
});
}
Ok(self.values[pos as usize])
}
#[must_use]
pub fn slice(&self, start: usize, end: usize) -> Self {
let end = end.min(self.values.len());
let start = start.min(end);
Self {
values: self.values[start..end].to_vec(),
closed: self.closed,
name: self.name.clone(),
}
}
#[must_use]
pub fn head(&self, n: usize) -> Self {
self.slice(0, n)
}
#[must_use]
pub fn tail(&self, n: usize) -> Self {
let len = self.values.len();
let start = len.saturating_sub(n);
self.slice(start, len)
}
/// Take values at indices.
///
/// # Errors
/// Returns `IndexError::OutOfBounds` if any index is out of bounds.
pub fn take(&self, indices: &[usize]) -> Result<Self, IndexError> {
let mut values = Vec::with_capacity(indices.len());
for &idx in indices {
if idx >= self.values.len() {
return Err(IndexError::OutOfBounds {
position: idx,
length: self.values.len(),
});
}
values.push(self.values[idx]);
}
Ok(Self {
values,
closed: self.closed,
name: self.name.clone(),
})
}
/// Check whether intervals are closed on the left endpoint (`pd.IntervalIndex.closed_left`).
#[must_use]
pub fn closed_left(&self) -> bool {
self.closed.left_closed()
}
/// Check whether intervals are closed on the right endpoint (`pd.IntervalIndex.closed_right`).
#[must_use]
pub fn closed_right(&self) -> bool {
self.closed.right_closed()
}
/// Check whether intervals are open on the left endpoint (`pd.IntervalIndex.open_left`).
#[must_use]
pub fn open_left(&self) -> bool {
!self.closed.left_closed()
}
/// Check whether intervals are open on the right endpoint (`pd.IntervalIndex.open_right`).
#[must_use]
pub fn open_right(&self) -> bool {
!self.closed.right_closed()
}
/// Return a boolean whether the IntervalIndex is non-overlapping and monotonic (`pd.IntervalIndex.is_non_overlapping_monotonic`).
#[must_use]
pub fn is_non_overlapping_monotonic(&self) -> bool {
(self.is_monotonic_increasing() || self.is_monotonic_decreasing()) && !self.is_overlapping()
}
/// Return intervals as a vector of (left, right) tuples (`pd.IntervalIndex.to_tuples`).
#[must_use]
pub fn to_tuples(&self) -> Vec<(f64, f64)> {
self.values.iter().map(|iv| (iv.left, iv.right)).collect()
}
/// Return intervals as a vector of `Interval` values.
#[must_use]
pub fn to_list(&self) -> Vec<Interval> {
self.values.clone()
}
/// Alias for `to_list`.
#[must_use]
pub fn tolist(&self) -> Vec<Interval> {
self.to_list()
}
}
impl From<IntervalIndex> for Index {
fn from(ii: IntervalIndex) -> Self {
ii.to_index()
}
}
impl From<&IntervalIndex> for Index {
fn from(ii: &IntervalIndex) -> Self {
ii.to_index()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlignmentPlan {
pub union_index: Index,
pub left_positions: Vec<Option<usize>>,
pub right_positions: Vec<Option<usize>>,
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum IndexError {
#[error("alignment vectors must have equal lengths")]
InvalidAlignmentVectors,
#[error("position {position} out of bounds for length {length}")]
OutOfBounds { position: usize, length: usize },
#[error("length mismatch: expected {expected}, got {actual} ({context})")]
LengthMismatch {
expected: usize,
actual: usize,
context: String,
},
#[error("invalid argument: {0}")]
InvalidArgument(String),
/// A label the index does not hold where it must: pandas'
/// `KeyError(label)`.
#[error("{0}")]
LabelNotFound(IndexLabel),
/// pandas' `KeyError(message)`.
#[error("{0}")]
KeyError(String),
/// An unknown zone, or a wall time a DST change skips or repeats.
#[error(transparent)]
TimeZone(#[from] fp_types::TimeZoneError),
/// Mixing tz-aware and tz-naive datetimes where pandas refuses to
/// (localizing an aware index, converting a naive one, joining the two):
/// pandas' `TypeError`.
#[error("{0}")]
TimeZoneMismatch(String),
}
/// Alignment mode for index-level join semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlignMode {
/// Only labels present in both indexes.
Inner,
/// All left labels; right fills with None for missing.
Left,
/// All right labels; left fills with None for missing.
Right,
/// All labels from both indexes (union). Default for arithmetic.
Outer,
}
fn index_position_groups(index: &Index) -> FxHashMap<IndexLabel, Vec<usize>> {
let mut groups: FxHashMap<IndexLabel, Vec<usize>> = FxHashMap::default();
for (pos, label) in index.labels().iter().enumerate() {
groups.entry(label.clone()).or_default().push(pos);
}
groups
}
fn align_non_unique(left: &Index, right: &Index, mode: AlignMode) -> AlignmentPlan {
let left_groups = index_position_groups(left);
let right_groups = index_position_groups(right);
let mut out_labels = Vec::new();
let mut left_positions = Vec::new();
let mut right_positions = Vec::new();
match mode {
AlignMode::Inner => {
for (left_pos, label) in left.labels().iter().enumerate() {
if let Some(right_hits) = right_groups.get(label) {
for &right_pos in right_hits {
out_labels.push(label.clone());
left_positions.push(Some(left_pos));
right_positions.push(Some(right_pos));
}
}
}
}
AlignMode::Left => {
for (left_pos, label) in left.labels().iter().enumerate() {
match right_groups.get(label) {
Some(right_hits) if !right_hits.is_empty() => {
for &right_pos in right_hits {
out_labels.push(label.clone());
left_positions.push(Some(left_pos));
right_positions.push(Some(right_pos));
}
}
_ => {
out_labels.push(label.clone());
left_positions.push(Some(left_pos));
right_positions.push(None);
}
}
}
}
AlignMode::Right => {
for (right_pos, label) in right.labels().iter().enumerate() {
match left_groups.get(label) {
Some(left_hits) if !left_hits.is_empty() => {
for &left_pos in left_hits {
out_labels.push(label.clone());
left_positions.push(Some(left_pos));
right_positions.push(Some(right_pos));
}
}
_ => {
out_labels.push(label.clone());
left_positions.push(None);
right_positions.push(Some(right_pos));
}
}
}
}
AlignMode::Outer => {
for (left_pos, label) in left.labels().iter().enumerate() {
match right_groups.get(label) {
Some(right_hits) if !right_hits.is_empty() => {
for &right_pos in right_hits {
out_labels.push(label.clone());
left_positions.push(Some(left_pos));
right_positions.push(Some(right_pos));
}
}
_ => {
out_labels.push(label.clone());
left_positions.push(Some(left_pos));
right_positions.push(None);
}
}
}
for (right_pos, label) in right.labels().iter().enumerate() {
if !left_groups.contains_key(label) {
out_labels.push(label.clone());
left_positions.push(None);
right_positions.push(Some(right_pos));
}
}
}
}
let mut union_index = Index::new(out_labels);
match mode {
AlignMode::Left => {
union_index.name = left.name.clone();
union_index.tz.clone_from(&left.tz);
}
AlignMode::Right => {
union_index.name = right.name.clone();
union_index.tz.clone_from(&right.tz);
}
AlignMode::Inner | AlignMode::Outer => union_index.tz = joined_tz(left, right),
}
AlignmentPlan {
union_index,
left_positions,
right_positions,
}
}
/// The zone of an index joining two aware indexes, as pandas: a shared zone
/// is kept and two different zones meet in UTC (the labels are instants
/// either way). None when either side is naive - joining an aware index with
/// a naive one is pandas' TypeError, which [`check_tz_compatible`] reports.
#[must_use]
pub fn joined_tz(left: &Index, right: &Index) -> Option<String> {
match (left.tz(), right.tz()) {
(Some(l), Some(r)) if l == r => Some(l.to_owned()),
(Some(_), Some(_)) => Some("UTC".to_owned()),
_ => None,
}
}
/// pandas refuses to join a tz-aware datetime index with a tz-naive one
/// ("Cannot join tz-naive with tz-aware DatetimeIndex"); callers that align
/// two indexes check this first.
pub fn check_tz_compatible(left: &Index, right: &Index) -> Result<(), IndexError> {
if left.tz().is_some() != right.tz().is_some()
&& left.holds_only_datetimes()
&& right.holds_only_datetimes()
&& !left.is_empty()
&& !right.is_empty()
{
return Err(IndexError::TimeZoneMismatch(
"Cannot join tz-naive with tz-aware DatetimeIndex".to_owned(),
));
}
Ok(())
}
/// Align two indexes using the specified join mode.
///
/// Returns an `AlignmentPlan` whose `union_index` contains the output index
/// (which may be an intersection, left-only, right-only, or union depending on mode).
pub fn align(left: &Index, right: &Index, mode: AlignMode) -> AlignmentPlan {
if left.has_duplicates() || right.has_duplicates() {
return align_non_unique(left, right, mode);
}
match mode {
AlignMode::Inner => align_inner(left, right),
AlignMode::Left => align_left(left, right),
AlignMode::Right => {
let plan = align_left(right, left);
AlignmentPlan {
union_index: plan.union_index,
left_positions: plan.right_positions,
right_positions: plan.left_positions,
}
}
AlignMode::Outer => align_union(left, right),
}
}
/// Inner alignment: only labels present in both indexes.
///
/// For non-unique labels, emits cartesian matches preserving left order.
pub fn align_inner(left: &Index, right: &Index) -> AlignmentPlan {
if left.has_duplicates() || right.has_duplicates() {
return align_non_unique(left, right, AlignMode::Inner);
}
// Typed all-Int64 fast path: inline `i64` right-position map instead of the
// pointer-keyed `FxHashMap<&IndexLabel>`. Bit-identical: left-order matches
// present in right, with their (left, right) positions.
if let (Some(left_vals), Some(right_vals)) =
(left.labels.int64_view(), right.labels.int64_view())
{
let mut right_pos: FxHashMap<i64, usize> =
FxHashMap::with_capacity_and_hasher(right_vals.len(), Default::default());
for (i, &v) in right_vals.iter().enumerate() {
right_pos.entry(v).or_insert(i);
}
let mut out_vals = Vec::new();
let mut left_positions = Vec::new();
let mut right_positions = Vec::new();
for (left_pos, &v) in left_vals.iter().enumerate() {
if let Some(&rp) = right_pos.get(&v) {
out_vals.push(v);
left_positions.push(Some(left_pos));
right_positions.push(Some(rp));
}
}
let shared_name = if left.name() == right.name() {
left.name().cloned()
} else {
None
};
let mut union_index = Index::from_i64(out_vals);
union_index.name = shared_name;
return AlignmentPlan {
union_index,
left_positions,
right_positions,
};
}
let right_map = right.position_map_first_ref();
let mut output_labels = Vec::new();
let mut left_positions = Vec::new();
let mut right_positions = Vec::new();
for (left_pos, label) in left.labels.iter().enumerate() {
if let Some(&right_pos) = right_map.get(label) {
output_labels.push(label.clone());
left_positions.push(Some(left_pos));
right_positions.push(Some(right_pos));
}
}
// Per br-frankenpandas-m2i5n: pandas inner alignment preserves the
// shared index name (preserved when both operands agree, None when
// they differ). Mirrors align_non_unique handling.
let shared_name = if left.name() == right.name() {
left.name().cloned()
} else {
None
};
let mut union_index = Index::new(output_labels);
union_index.name = shared_name;
union_index.tz = joined_tz(left, right);
AlignmentPlan {
union_index,
left_positions,
right_positions,
}
}
/// Left alignment: all left labels preserved, right fills with None for missing.
pub fn align_left(left: &Index, right: &Index) -> AlignmentPlan {
if left.has_duplicates() || right.has_duplicates() {
return align_non_unique(left, right, AlignMode::Left);
}
// Typed all-Int64 fast path: inline `i64` right-position map instead of the
// pointer-keyed `FxHashMap<&IndexLabel>`. The union is `left` unchanged, and
// `left_positions` is the identity `0..n` — only `right_positions` needs a
// lookup. Bit-identical.
if let (Some(left_vals), Some(right_vals)) =
(left.labels.int64_view(), right.labels.int64_view())
{
let mut right_pos: FxHashMap<i64, usize> =
FxHashMap::with_capacity_and_hasher(right_vals.len(), Default::default());
for (i, &v) in right_vals.iter().enumerate() {
right_pos.entry(v).or_insert(i);
}
let n = left_vals.len();
let left_positions: Vec<Option<usize>> = (0..n).map(Some).collect();
let right_positions: Vec<Option<usize>> = left_vals
.iter()
.map(|v| right_pos.get(v).copied())
.collect();
return AlignmentPlan {
union_index: left.clone(),
left_positions,
right_positions,
};
}
let right_map = right.position_map_first_ref();
let mut left_positions = Vec::with_capacity(left.len());
let mut right_positions = Vec::with_capacity(left.len());
for (left_pos, label) in left.labels.iter().enumerate() {
left_positions.push(Some(left_pos));
right_positions.push(right_map.get(label).copied());
}
AlignmentPlan {
union_index: left.clone(),
left_positions,
right_positions,
}
}
/// Typed all-Int64 union alignment over raw `i64` keys (both inputs unique, per
/// the `align_union` `has_duplicates` guard). Produces the SAME union order as
/// the generic path — left labels in order, then right-only labels in right
/// order — and the same per-side position vectors, but with INLINE `i64` map
/// keys instead of `FxHashMap<&IndexLabel>` pointers into the enum vector (two
/// position maps + two position lookups per union label, each otherwise paying
/// a pointer-chase cache miss). Returns `(union_values, left_positions,
/// right_positions)`.
#[allow(clippy::type_complexity)]
fn align_union_i64(
left_vals: &[i64],
right_vals: &[i64],
) -> (Vec<i64>, Vec<Option<usize>>, Vec<Option<usize>>) {
// `left` is unique, so its labels occupy union positions `0..n` in order:
// `left_positions[i] = Some(i)` there and `None` for the right-only tail —
// no map lookup needed. A membership SET of `left` filters the right tail;
// a `right` position MAP serves `right_positions`.
let mut left_set: FxHashSet<i64> =
FxHashSet::with_capacity_and_hasher(left_vals.len(), Default::default());
for &v in left_vals {
left_set.insert(v);
}
let mut right_pos: FxHashMap<i64, usize> =
FxHashMap::with_capacity_and_hasher(right_vals.len(), Default::default());
for (i, &v) in right_vals.iter().enumerate() {
right_pos.entry(v).or_insert(i);
}
let mut union_vals =
Vec::with_capacity(combined_output_capacity(left_vals.len(), right_vals.len()));
union_vals.extend_from_slice(left_vals);
for &v in right_vals {
if !left_set.contains(&v) {
union_vals.push(v);
}
}
let n = left_vals.len();
let mut left_positions = Vec::with_capacity(union_vals.len());
left_positions.extend((0..n).map(Some));
left_positions.extend(std::iter::repeat_n(None, union_vals.len() - n));
let right_positions = union_vals
.iter()
.map(|v| right_pos.get(v).copied())
.collect();
(union_vals, left_positions, right_positions)
}
pub fn align_union(left: &Index, right: &Index) -> AlignmentPlan {
if left.has_duplicates() || right.has_duplicates() {
return align_non_unique(left, right, AlignMode::Outer);
}
// Typed all-Int64 fast path: inline `i64` position maps instead of the
// pointer-keyed `FxHashMap<&IndexLabel>`. Bit-identical union order and
// position vectors; the union index keeps the typed Int64 backing.
if let (Some(left_vals), Some(right_vals)) =
(left.labels.int64_view(), right.labels.int64_view())
{
let (union_vals, left_positions, right_positions) =
align_union_i64(&left_vals, &right_vals);
let shared_name = if left.name() == right.name() {
left.name().cloned()
} else {
None
};
let mut union_index = Index::from_i64(union_vals);
union_index.name = shared_name;
return AlignmentPlan {
union_index,
left_positions,
right_positions,
};
}
let left_positions_map = left.position_map_first_ref();
let right_positions_map = right.position_map_first_ref();
let mut union_labels = Vec::with_capacity(combined_output_capacity(
left.labels.len(),
right.labels.len(),
));
union_labels.extend(left.labels.iter().cloned());
for label in &right.labels {
if !left_positions_map.contains_key(&label) {
union_labels.push(label.clone());
}
}
let left_positions = union_labels
.iter()
.map(|label| left_positions_map.get(&label).copied())
.collect();
let right_positions = union_labels
.iter()
.map(|label| right_positions_map.get(&label).copied())
.collect();
// Per br-frankenpandas-r4k11: pandas outer alignment preserves the
// shared index name. Mirrors align_inner / align_non_unique handling.
let shared_name = if left.name() == right.name() {
left.name().cloned()
} else {
None
};
let mut union_index = Index::new(union_labels);
union_index.name = shared_name;
union_index.tz = joined_tz(left, right);
AlignmentPlan {
union_index,
left_positions,
right_positions,
}
}
pub fn validate_alignment_plan(plan: &AlignmentPlan) -> Result<(), IndexError> {
if plan.left_positions.len() != plan.right_positions.len()
|| plan.left_positions.len() != plan.union_index.len()
{
return Err(IndexError::InvalidAlignmentVectors);
}
Ok(())
}
// ── AG-11: Leapfrog Triejoin for Multi-Way Index Alignment ─────────────
/// Result of multi-way alignment: a union index plus per-input position vectors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MultiAlignmentPlan {
pub union_index: Index,
pub positions: Vec<Vec<Option<usize>>>,
}
/// K-way merge union of multiple sorted iterators.
///
/// Produces a sorted, deduplicated index containing all labels from all inputs.
/// Each input is sorted internally before merging. Uses a min-heap for O(N log K)
/// performance where N = total labels and K = number of indexes.
pub fn leapfrog_union(indexes: &[&Index]) -> Index {
if indexes.is_empty() {
return Index::new(Vec::new());
}
if indexes.len() == 1 {
return indexes[0].unique().sort_values();
}
// Sort and dedup each input
let sorted: Vec<Vec<&IndexLabel>> = indexes
.iter()
.map(|idx| {
let mut labels: Vec<&IndexLabel> = idx.labels().iter().collect();
labels.sort();
labels.dedup();
labels
})
.collect();
// Initialize min-heap: (label, iter_index, position_in_iter)
let mut heap = std::collections::BinaryHeap::new();
for (i, iter) in sorted.iter().enumerate() {
if !iter.is_empty() {
heap.push(std::cmp::Reverse((iter[0].clone(), i, 0_usize)));
}
}
let total = aggregate_output_capacity(sorted.iter().map(Vec::len));
let mut result = Vec::with_capacity(total);
while let Some(std::cmp::Reverse((label, iter_idx, pos))) = heap.pop() {
// Deduplicate: only push if different from last
if result.last() != Some(&label) {
result.push(label);
}
let next_pos = pos + 1;
if next_pos < sorted[iter_idx].len() {
heap.push(std::cmp::Reverse((
sorted[iter_idx][next_pos].clone(),
iter_idx,
next_pos,
)));
}
}
Index::new(result)
}
/// Leapfrog intersection: labels present in ALL input indexes.
///
/// Classic leapfrog algorithm on sorted iterators. For each position,
/// advance the smallest iterator to seek the maximum. When all iterators
/// agree, emit the label.
pub fn leapfrog_intersection(indexes: &[&Index]) -> Index {
if indexes.is_empty() {
return Index::new(Vec::new());
}
if indexes.len() == 1 {
return indexes[0].unique().sort_values();
}
// Sort and dedup each input
let sorted: Vec<Vec<&IndexLabel>> = indexes
.iter()
.map(|idx| {
let mut labels: Vec<&IndexLabel> = idx.labels().iter().collect();
labels.sort();
labels.dedup();
labels
})
.collect();
// Cursors into each sorted iterator
let k = sorted.len();
let mut cursors: Vec<usize> = vec![0; k];
let mut result = Vec::new();
'outer: loop {
// Check if any iterator is exhausted
for i in 0..k {
if cursors[i] >= sorted[i].len() {
break 'outer;
}
}
// Find the max label across all cursors
let mut max_label = sorted[0][cursors[0]];
for i in 1..k {
if sorted[i][cursors[i]] > max_label {
max_label = sorted[i][cursors[i]];
}
}
// Advance all cursors to at least max_label
let mut all_equal = true;
for i in 0..k {
// Binary search for max_label in sorted[i] starting from cursors[i]
let remaining = &sorted[i][cursors[i]..];
match remaining.binary_search(&max_label) {
Ok(offset) => {
cursors[i] += offset;
}
Err(offset) => {
cursors[i] += offset;
all_equal = false;
}
}
if cursors[i] >= sorted[i].len() {
break 'outer;
}
}
if all_equal {
// All iterators point to the same label
result.push(max_label.clone());
for cursor in &mut cursors {
*cursor += 1;
}
}
// If not all equal, the loop continues with updated cursors
}
Index::new(result)
}
/// Multi-way alignment: union all indexes, then compute position vectors.
///
/// This is the AGM-bound-optimal replacement for iterative pairwise `align_union`.
/// For N indexes, produces a single sorted union index and N position vectors
/// mapping each union label to its original position in each input.
pub fn multi_way_align(indexes: &[&Index]) -> MultiAlignmentPlan {
if indexes.is_empty() {
return MultiAlignmentPlan {
union_index: Index::new(Vec::new()),
positions: Vec::new(),
};
}
// Preserve pandas-style union ordering: start with the first index's labels,
// then append unseen labels from subsequent indexes in encounter order.
// This matches iterative align_union(sort=False) semantics while avoiding
// the O(N*K) pairwise alignment cascade.
// Borrow labels into the membership set (no clone per label) and clone only
// the first-seen ones into the output. The prior version cloned EVERY label
// into an owned HashSet<IndexLabel> (even duplicates) — clone-bound. Borrowed
// keys + FxHashSet leave only the unique-label output clones. The borrow is
// valid: every &IndexLabel comes from `indexes`, which outlives this scan.
let aggregate_capacity =
aggregate_output_capacity(indexes.iter().map(|idx| idx.labels().len()));
let mut seen: FxHashSet<&IndexLabel> =
FxHashSet::with_capacity_and_hasher(aggregate_capacity, Default::default());
let mut union_labels: Vec<IndexLabel> = Vec::with_capacity(aggregate_capacity);
for idx in indexes {
for label in idx.labels() {
if seen.insert(label) {
union_labels.push(label.clone());
}
}
}
// Per br-frankenpandas-nrhjq: pandas multi-index union sets name to
// the shared name across all inputs (= None if any differ).
let first_name = indexes.first().and_then(|idx| idx.name()).cloned();
let shared_name = if indexes.iter().all(|idx| idx.name() == first_name.as_ref()) {
first_name
} else {
None
};
let mut union = Index::new(union_labels);
union.name = shared_name;
// Build position maps for each input
let maps: Vec<FxHashMap<&IndexLabel, usize>> = indexes
.iter()
.map(|idx| idx.position_map_first_ref())
.collect();
let positions: Vec<Vec<Option<usize>>> = maps
.iter()
.map(|map| {
union
.labels
.iter()
.map(|label| map.get(label).copied())
.collect()
})
.collect();
MultiAlignmentPlan {
union_index: union,
positions,
}
}
// ── TimedeltaIndex helpers ──────────────────────────────────────────────
/// Error for timedelta_range parameter combinations.
#[derive(Debug, Clone, Error)]
pub enum TimedeltaRangeError {
#[error("must specify at least two of start, end, periods")]
InsufficientParams,
#[error("must specify no more than two of start, end, periods")]
TooManyParams,
/// A zero step goes nowhere (pandas' ZeroDivisionError). A negative one
/// steps backwards and a range stepping away from `end` is empty, as
/// pandas' (they were refused; br-frankenpandas-tzxpk).
#[error("freq must be non-zero")]
ZeroFreq,
}
/// Create a TimedeltaIndex with evenly spaced values.
///
/// Analogous to `pd.timedelta_range()`. Must specify exactly two of:
/// start, end, periods. Frequency defaults to 1 day (86_400_000_000_000 ns).
///
/// # Examples
/// ```
/// use fp_index::timedelta_range;
/// use fp_types::Timedelta;
///
/// let idx = timedelta_range(
/// Some(Timedelta::NANOS_PER_DAY),
/// None,
/// Some(3),
/// Timedelta::NANOS_PER_DAY,
/// None,
/// ).unwrap();
/// assert_eq!(idx.len(), 3);
/// ```
pub fn timedelta_range(
start: Option<i64>,
end: Option<i64>,
periods: Option<usize>,
freq: i64,
name: Option<&str>,
) -> Result<Index, TimedeltaRangeError> {
if freq == 0 {
return Err(TimedeltaRangeError::ZeroFreq);
}
let (start_ns, count) = match (start, end, periods) {
(Some(s), Some(e), None) => {
// A step away from `end` reaches nothing (empty, as pandas').
let n = if (freq > 0 && e < s) || (freq < 0 && e > s) {
0
} else {
((e - s) / freq + 1) as usize
};
(s, n)
}
(Some(s), None, Some(p)) => (s, p),
(None, Some(e), Some(p)) => {
let s = e - (p.saturating_sub(1) as i64) * freq;
(s, p)
}
(Some(_), Some(_), Some(_)) => return Err(TimedeltaRangeError::TooManyParams),
_ => return Err(TimedeltaRangeError::InsufficientParams),
};
let nanos: Vec<i64> = (0..count).map(|i| start_ns + (i as i64) * freq).collect();
let mut idx = Index::from_timedelta64(nanos);
if let Some(n) = name {
idx = idx.set_name(n);
}
Ok(idx)
}
// ── DatetimeIndex helpers ───────────────────────────────────────────────
/// Error for date_range parameter combinations.
#[derive(Debug, Clone, Error)]
pub enum DateRangeError {
#[error("must specify at least two of start, end, periods")]
InsufficientParams,
#[error("need at least 3 dates to infer frequency")]
InsufficientDates,
#[error("must specify no more than two of start, end, periods")]
TooManyParams,
#[error("freq must be positive")]
NonPositiveFreq,
#[error("cannot compute range: end < start with positive freq")]
InvalidRange,
#[error("invalid datetime string: {0}")]
ParseError(String),
}
/// Parse an ISO 8601 datetime string to nanoseconds since epoch.
fn parse_datetime_to_nanos(s: &str) -> Result<i64, DateRangeError> {
use chrono::NaiveDateTime;
let trimmed = s.trim();
// Try full datetime format
if let Ok(dt) = NaiveDateTime::parse_from_str(trimmed, "%Y-%m-%d %H:%M:%S") {
return datetime_to_nanos(dt);
}
if let Ok(dt) = NaiveDateTime::parse_from_str(trimmed, "%Y-%m-%dT%H:%M:%S") {
return datetime_to_nanos(dt);
}
// Try date-only format (midnight)
if let Ok(date) = chrono::NaiveDate::parse_from_str(trimmed, "%Y-%m-%d") {
let dt = date
.and_hms_opt(0, 0, 0)
.ok_or(DateRangeError::InvalidRange)?;
return datetime_to_nanos(dt);
}
Err(DateRangeError::ParseError(trimmed.to_owned()))
}
fn datetime_to_nanos(dt: chrono::NaiveDateTime) -> Result<i64, DateRangeError> {
dt.and_utc()
.timestamp_nanos_opt()
.ok_or(DateRangeError::InvalidRange)
}
fn datetime_nanos_to_date(nanos: i64) -> Result<chrono::NaiveDate, DateRangeError> {
let (date, _) = split_datetime_nanos(nanos)?;
Ok(date)
}
fn split_datetime_nanos(nanos: i64) -> Result<(chrono::NaiveDate, i64), DateRangeError> {
let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
let time_nanos = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
let epoch = chrono::NaiveDate::from_ymd_opt(1970, 1, 1).ok_or(DateRangeError::InvalidRange)?;
let date = epoch
.checked_add_signed(chrono::Duration::days(days))
.ok_or(DateRangeError::InvalidRange)?;
Ok((date, time_nanos))
}
fn date_to_midnight_nanos(date: chrono::NaiveDate) -> Result<i64, DateRangeError> {
let dt = date
.and_hms_opt(0, 0, 0)
.ok_or(DateRangeError::InvalidRange)?;
dt.and_utc()
.timestamp_nanos_opt()
.ok_or(DateRangeError::InvalidRange)
}
fn date_and_time_to_nanos(date: chrono::NaiveDate, time_nanos: i64) -> Result<i64, DateRangeError> {
date_to_midnight_nanos(date)?
.checked_add(time_nanos)
.ok_or(DateRangeError::InvalidRange)
}
fn checked_day_step(
date: chrono::NaiveDate,
days: i64,
) -> Result<chrono::NaiveDate, DateRangeError> {
date.checked_add_signed(chrono::Duration::days(days))
.ok_or(DateRangeError::InvalidRange)
}
fn is_business_day(date: chrono::NaiveDate) -> bool {
use chrono::{Datelike, Weekday};
!matches!(date.weekday(), Weekday::Sat | Weekday::Sun)
}
fn next_business_day(mut date: chrono::NaiveDate) -> Result<chrono::NaiveDate, DateRangeError> {
while !is_business_day(date) {
date = checked_day_step(date, 1)?;
}
Ok(date)
}
fn previous_business_day(mut date: chrono::NaiveDate) -> Result<chrono::NaiveDate, DateRangeError> {
while !is_business_day(date) {
date = checked_day_step(date, -1)?;
}
Ok(date)
}
fn collect_business_days_from_start(
start: chrono::NaiveDate,
periods: usize,
) -> Result<Vec<i64>, DateRangeError> {
let mut values = Vec::with_capacity(periods);
let mut date = next_business_day(start)?;
while values.len() < periods {
values.push(date_to_midnight_nanos(date)?);
date = next_business_day(checked_day_step(date, 1)?)?;
}
Ok(values)
}
fn collect_business_days_through_end(
end: chrono::NaiveDate,
periods: usize,
) -> Result<Vec<i64>, DateRangeError> {
let mut values = Vec::with_capacity(periods);
let mut date = previous_business_day(end)?;
while values.len() < periods {
values.push(date_to_midnight_nanos(date)?);
date = previous_business_day(checked_day_step(date, -1)?)?;
}
values.reverse();
Ok(values)
}
fn collect_business_days_between(
start: chrono::NaiveDate,
end: chrono::NaiveDate,
) -> Result<Vec<i64>, DateRangeError> {
if end < start {
return Err(DateRangeError::InvalidRange);
}
let mut values = Vec::new();
let mut date = next_business_day(start)?;
while date <= end {
values.push(date_to_midnight_nanos(date)?);
date = next_business_day(checked_day_step(date, 1)?)?;
}
Ok(values)
}
/// A small subset of pandas `pandas.tseries.offsets` date offsets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateOffset {
Day(i32),
BusinessDay(i32),
MonthEnd(i32),
}
/// Apply a date offset to a timestamp string and return nanoseconds since epoch.
///
/// This mirrors `pd.Timestamp(timestamp) + pd.offsets.<Offset>(n)` for the
/// supported offsets.
pub fn apply_date_offset(timestamp: &str, offset: DateOffset) -> Result<i64, DateRangeError> {
let nanos = parse_datetime_to_nanos(timestamp)?;
apply_date_offset_to_nanos(nanos, offset)
}
/// Apply a date offset to a nanosecond timestamp.
pub fn apply_date_offset_to_nanos(nanos: i64, offset: DateOffset) -> Result<i64, DateRangeError> {
match offset {
DateOffset::Day(days) => nanos
.checked_add(
i64::from(days)
.checked_mul(Timedelta::NANOS_PER_DAY)
.ok_or(DateRangeError::InvalidRange)?,
)
.ok_or(DateRangeError::InvalidRange),
DateOffset::BusinessDay(days) => {
let (date, time_nanos) = split_datetime_nanos(nanos)?;
let shifted = apply_business_day_offset(date, days)?;
date_and_time_to_nanos(shifted, time_nanos)
}
DateOffset::MonthEnd(months) => {
let (date, time_nanos) = split_datetime_nanos(nanos)?;
let shifted = apply_month_end_offset(date, months)?;
date_and_time_to_nanos(shifted, time_nanos)
}
}
}
fn apply_business_day_offset(
date: chrono::NaiveDate,
days: i32,
) -> Result<chrono::NaiveDate, DateRangeError> {
if days == 0 {
return next_business_day(date);
}
let mut shifted = date;
if days > 0 {
for _ in 0..days.unsigned_abs() {
shifted = next_business_day(checked_day_step(shifted, 1)?)?;
}
} else {
for _ in 0..days.unsigned_abs() {
shifted = previous_business_day(checked_day_step(shifted, -1)?)?;
}
}
Ok(shifted)
}
fn last_day_of_month(year: i32, month: u32) -> Result<chrono::NaiveDate, DateRangeError> {
let (next_year, next_month) = if month == 12 {
(year.checked_add(1).ok_or(DateRangeError::InvalidRange)?, 1)
} else {
(year, month + 1)
};
let first_next_month = chrono::NaiveDate::from_ymd_opt(next_year, next_month, 1)
.ok_or(DateRangeError::InvalidRange)?;
checked_day_step(first_next_month, -1)
}
fn add_months_to_month_end(
date: chrono::NaiveDate,
months: i32,
) -> Result<chrono::NaiveDate, DateRangeError> {
use chrono::Datelike;
let month_index = i64::from(date.year())
.checked_mul(12)
.and_then(|value| value.checked_add(i64::from(date.month()) - 1))
.and_then(|value| value.checked_add(i64::from(months)))
.ok_or(DateRangeError::InvalidRange)?;
let year =
i32::try_from(month_index.div_euclid(12)).map_err(|_| DateRangeError::InvalidRange)?;
let month =
u32::try_from(month_index.rem_euclid(12) + 1).map_err(|_| DateRangeError::InvalidRange)?;
last_day_of_month(year, month)
}
fn month_ordinal(date: chrono::NaiveDate) -> i64 {
use chrono::Datelike;
i64::from(date.year()) * 12 + i64::from(date.month()) - 1
}
fn apply_month_end_offset(
date: chrono::NaiveDate,
months: i32,
) -> Result<chrono::NaiveDate, DateRangeError> {
use chrono::Datelike;
let current_month_end = last_day_of_month(date.year(), date.month())?;
if months == 0 {
return if date == current_month_end {
Ok(date)
} else {
Ok(current_month_end)
};
}
let month_steps = if months > 0 && date != current_month_end {
months - 1
} else {
months
};
add_months_to_month_end(current_month_end, month_steps)
}
/// pandas' month aliases (`MONTH_ALIASES`), January first.
const MONTH_ALIASES: [&str; 12] = [
"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
];
/// pandas' weekday aliases (`int_to_weekday`), Monday first.
const WEEKDAY_ALIASES: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
/// pandas' `_maybe_add_count`: the alias, its count in front unless 1.
fn with_count(base: &str, count: i64) -> String {
if count == 1 {
base.to_owned()
} else {
format!("{count}{base}")
}
}
/// pandas' `unique_deltas`: the distinct differences of consecutive values,
/// ascending.
fn unique_deltas(values: &[i64]) -> Vec<i64> {
let mut deltas: Vec<i64> = values.windows(2).map(|pair| pair[1] - pair[0]).collect();
deltas.sort_unstable();
deltas.dedup();
deltas
}
/// A fixed step under a day as pandas names it: whole hours, minutes,
/// seconds, milli-, microseconds, else nanoseconds, with its count.
fn fixed_frequency_name(step: i64) -> Option<String> {
if step == 0 {
return None;
}
for (unit, suffix) in [
(Timedelta::NANOS_PER_HOUR, "h"),
(Timedelta::NANOS_PER_MIN, "min"),
(Timedelta::NANOS_PER_SEC, "s"),
(Timedelta::NANOS_PER_MILLI, "ms"),
(Timedelta::NANOS_PER_MICRO, "us"),
] {
if step % unit == 0 {
return Some(with_count(suffix, step / unit));
}
}
Some(with_count("ns", step))
}
/// pandas' `month_position_check`: whether every date is its month's
/// calendar end (`ce`), business end (`be`, a Friday within the last three
/// days), calendar start (`cs`) or business start (`bs`, a Monday within the
/// first three), asked in that order.
fn month_position(dates: &[chrono::NaiveDate]) -> Option<&'static str> {
use chrono::Datelike;
let (mut calendar_start, mut business_start) = (true, true);
let (mut calendar_end, mut business_end) = (true, true);
for date in dates {
let (day, weekday) = (date.day(), date.weekday().num_days_from_monday());
let last = last_day_of_month(date.year(), date.month()).ok()?.day();
calendar_start &= day == 1;
business_start &= day == 1 || (day <= 3 && weekday == 0);
calendar_end &= day == last;
business_end &= day == last || (last - day < 3 && weekday == 4);
}
if calendar_end {
Some("ce")
} else if business_end {
Some("be")
} else if calendar_start {
Some("cs")
} else if business_start {
Some("bs")
} else {
None
}
}
/// pandas' `_infer_daily_rule`, for steps of whole days: an annual, then a
/// quarterly, then a monthly rule when every date sits at the same position
/// in its month, else a fixed step (`D`, or `W-<weekday>` for whole weeks),
/// business days, a week of the month. `deltas` are [`unique_deltas`].
fn infer_daily_rule(dates: &[chrono::NaiveDate], deltas: &[i64]) -> Option<String> {
use chrono::Datelike;
let first = dates[0];
let position = month_position(dates);
let years: Vec<i64> = dates.iter().map(|date| i64::from(date.year())).collect();
let ydiffs = unique_deltas(&years);
if ydiffs.len() == 1
&& dates.iter().all(|date| date.month() == first.month())
&& let Some(rule) = position.and_then(|position| match position {
"cs" => Some("YS"),
"bs" => Some("BYS"),
"ce" => Some("YE"),
"be" => Some("BYE"),
_ => None,
})
{
let month = MONTH_ALIASES[first.month0() as usize];
return Some(with_count(&format!("{rule}-{month}"), ydiffs[0]));
}
let months: Vec<i64> = dates.iter().map(|date| month_ordinal(*date)).collect();
let mdiffs = unique_deltas(&months);
if mdiffs.len() == 1 {
let quarterly = position.and_then(|position| match position {
"cs" => Some("QS"),
"bs" => Some("BQS"),
"ce" => Some("QE"),
"be" => Some("BQE"),
_ => None,
});
if mdiffs[0] % 3 == 0
&& let Some(rule) = quarterly
{
// pandas anchors a quarter on the month its first date's month
// shares a remainder with: 0 -> DEC, 2 -> NOV, 1 -> OCT.
let anchor = match first.month() % 3 {
0 => "DEC",
2 => "NOV",
_ => "OCT",
};
return Some(with_count(&format!("{rule}-{anchor}"), mdiffs[0] / 3));
}
if let Some(rule) = position.and_then(|position| match position {
"cs" => Some("MS"),
"bs" => Some("BMS"),
"ce" => Some("ME"),
"be" => Some("BME"),
_ => None,
}) {
return Some(with_count(rule, mdiffs[0]));
}
}
let weekday = first.weekday().num_days_from_monday();
if let [delta] = deltas {
let days = delta / Timedelta::NANOS_PER_DAY;
return Some(if days.rem_euclid(7) == 0 {
with_count(
&format!("W-{}", WEEKDAY_ALIASES[weekday as usize]),
days / 7,
)
} else {
with_count("D", days)
});
}
// Business days: steps of one day, three across a weekend, landing on
// Monday after three and Tuesday..Friday after one.
if deltas == [Timedelta::NANOS_PER_DAY, 3 * Timedelta::NANOS_PER_DAY] {
let mut on = i64::from(weekday);
let business = dates.windows(2).all(|pair| {
let shift = (pair[1] - pair[0]).num_days();
on = (on + shift).rem_euclid(7);
(on == 0 && shift == 3) || ((1..=4).contains(&on) && shift == 1)
});
if business {
return Some("B".to_owned());
}
}
// A week of the month: one weekday, one of the first four weeks.
if dates.iter().all(|date| date.weekday() == first.weekday()) {
let mut weeks: Vec<u32> = dates
.iter()
.map(|date| (date.day() - 1) / 7)
.filter(|week| *week < 4)
.collect();
weeks.sort_unstable();
weeks.dedup();
if let [week] = weeks[..] {
return Some(format!(
"WOM-{}{}",
week + 1,
WEEKDAY_ALIASES[weekday as usize]
));
}
}
None
}
/// Infer a pandas-style frequency string from a DatetimeIndex.
///
/// Returns `Ok(None)` for irregular or duplicate timestamp sequences. Returns
/// an error for the pandas-compatible "fewer than 3 dates" case.
pub fn infer_freq(index: &Index) -> Result<Option<String>, DateRangeError> {
if let Some(range) = index.labels.datetime64_affine_range() {
if range.position(i64::MIN).is_some() {
return Ok(None);
}
if range.len < 3 {
return Err(DateRangeError::InsufficientDates);
}
// A step of whole days is pandas' daily rule, which reads the dates
// (annual / weekly anchors) - from the range's arithmetic, its labels
// left unbuilt; a shorter one is its unit.
if range.step % Timedelta::NANOS_PER_DAY != 0 {
return Ok(fixed_frequency_name(range.step));
}
let mut values = Vec::with_capacity(range.len);
let mut value = range.start;
for _ in 0..range.len {
values.push(value);
value = value.wrapping_add(range.step);
}
return infer_freq_from_nanos(&values);
}
let mut values = Vec::with_capacity(index.len());
for label in index.labels() {
match label {
IndexLabel::Datetime64(value) if *value != i64::MIN => values.push(*value),
IndexLabel::Datetime64(_) => return Ok(None),
_ => {
return Err(DateRangeError::ParseError(
"expected datetime64 index".to_owned(),
));
}
}
}
infer_freq_from_nanos(&values)
}
/// Infer a pandas-style frequency string from timestamp strings.
pub fn infer_freq_from_timestamps(timestamps: &[&str]) -> Result<Option<String>, DateRangeError> {
let values: Vec<i64> = timestamps
.iter()
.map(|timestamp| parse_datetime_to_nanos(timestamp))
.collect::<Result<_, _>>()?;
infer_freq_from_nanos(&values)
}
/// Infer a pandas-style frequency string from nanosecond timestamps, as
/// pandas' `_FrequencyInferer.get_freq` does: None unless strictly
/// increasing or decreasing; when the smallest step is whole days, its daily
/// rule ([`infer_daily_rule`]: YS-JAN, QE-DEC, MS, W-MON, B, WOM-3FRI...);
/// business hours (`bh`) for steps of 1 / 17 / 65 hours; else one fixed step
/// in its unit (`15min`, `-1h`), None for several.
pub fn infer_freq_from_nanos(values: &[i64]) -> Result<Option<String>, DateRangeError> {
if values.len() < 3 {
return Err(DateRangeError::InsufficientDates);
}
let increasing = values.windows(2).all(|pair| pair[1] > pair[0]);
if !increasing && !values.windows(2).all(|pair| pair[1] < pair[0]) {
return Ok(None);
}
let deltas = unique_deltas(values);
if deltas[0] % Timedelta::NANOS_PER_DAY == 0 {
let dates: Vec<chrono::NaiveDate> = values
.iter()
.map(|value| split_datetime_nanos(*value).map(|(date, _)| date))
.collect::<Result<_, _>>()?;
return Ok(infer_daily_rule(&dates, &deltas));
}
let hour = Timedelta::NANOS_PER_HOUR;
if deltas.iter().all(|delta| delta % hour == 0) {
let hours: Vec<i64> = deltas.iter().map(|delta| delta / hour).collect();
if matches!(hours.as_slice(), [1, 17] | [1, 65] | [1, 17, 65]) {
return Ok(Some("bh".to_owned()));
}
}
Ok(match deltas.as_slice() {
[step] => fixed_frequency_name(*step),
_ => None,
})
}
/// Create a DatetimeIndex with evenly spaced values.
///
/// Analogous to `pd.date_range()`. Must specify exactly two of:
/// start, end, periods. Frequency defaults to 1 day.
///
/// # Examples
/// ```
/// use fp_index::date_range;
/// use fp_types::Timedelta;
///
/// let idx = date_range(
/// Some("2024-01-01"),
/// None,
/// Some(3),
/// Timedelta::NANOS_PER_DAY,
/// None,
/// ).unwrap();
/// assert_eq!(idx.len(), 3);
/// ```
pub fn date_range(
start: Option<&str>,
end: Option<&str>,
periods: Option<usize>,
freq: i64,
name: Option<&str>,
) -> Result<Index, DateRangeError> {
if freq <= 0 {
return Err(DateRangeError::NonPositiveFreq);
}
let start_ns = start.map(parse_datetime_to_nanos).transpose()?;
let end_ns = end.map(parse_datetime_to_nanos).transpose()?;
let (start_val, count) = match (start_ns, end_ns, periods) {
(Some(s), Some(e), None) => {
if e < s {
return Err(DateRangeError::InvalidRange);
}
let span = e.checked_sub(s).ok_or(DateRangeError::InvalidRange)?;
let n = (span / freq + 1) as usize;
(s, n)
}
(Some(s), None, Some(p)) => (s, p),
(None, Some(e), Some(p)) => {
let offset = checked_date_range_offset(p.saturating_sub(1), freq)?;
let s = e.checked_sub(offset).ok_or(DateRangeError::InvalidRange)?;
(s, p)
}
(Some(_), Some(_), Some(_)) => return Err(DateRangeError::TooManyParams),
_ => return Err(DateRangeError::InsufficientParams),
};
let last_offset = checked_date_range_offset(count.saturating_sub(1), freq)?;
start_val
.checked_add(last_offset)
.ok_or(DateRangeError::InvalidRange)?;
let mut idx = Index::from_datetime64_affine_range(start_val, freq, count)
.ok_or(DateRangeError::InvalidRange)?;
if let Some(n) = name {
idx = idx.set_name(n);
}
Ok(idx)
}
fn checked_date_range_offset(steps: usize, freq: i64) -> Result<i64, DateRangeError> {
let steps = i64::try_from(steps).map_err(|_| DateRangeError::InvalidRange)?;
steps.checked_mul(freq).ok_or(DateRangeError::InvalidRange)
}
/// Create a DatetimeIndex with default weekday-only business-day values.
///
/// Analogous to `pd.bdate_range(..., freq="B")` for the default Monday-Friday
/// calendar. Exactly two of start, end, and periods must be specified.
pub fn bdate_range(
start: Option<&str>,
end: Option<&str>,
periods: Option<usize>,
name: Option<&str>,
) -> Result<Index, DateRangeError> {
let start_date = start
.map(parse_datetime_to_nanos)
.transpose()?
.map(datetime_nanos_to_date)
.transpose()?;
let end_date = end
.map(parse_datetime_to_nanos)
.transpose()?
.map(datetime_nanos_to_date)
.transpose()?;
let nanos = match (start_date, end_date, periods) {
(Some(start), Some(end), None) => collect_business_days_between(start, end)?,
(Some(start), None, Some(periods)) => collect_business_days_from_start(start, periods)?,
(None, Some(end), Some(periods)) => collect_business_days_through_end(end, periods)?,
(Some(_), Some(_), Some(_)) => return Err(DateRangeError::TooManyParams),
_ => return Err(DateRangeError::InsufficientParams),
};
let mut idx = Index::from_datetime64(nanos);
if let Some(n) = name {
idx = idx.set_name(n);
}
Ok(idx)
}
// ── MultiIndex ──────────────────────────────────────────────────────────
/// Slicing specification for index and MultiIndex selections, matching `pd.IndexSlice`.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct IndexSlice<T = IndexLabel> {
pub start: Option<T>,
pub stop: Option<T>,
pub step: Option<isize>,
}
impl<T> IndexSlice<T> {
/// Create a new `IndexSlice` with explicit start, stop, and step.
#[must_use]
pub const fn new(start: Option<T>, stop: Option<T>, step: Option<isize>) -> Self {
Self { start, stop, step }
}
/// Match a full slice `[:]`.
#[must_use]
pub const fn all() -> Self {
Self {
start: None,
stop: None,
step: None,
}
}
/// Create an `IndexSlice` from start and stop bounds.
#[must_use]
pub const fn from_bounds(start: Option<T>, stop: Option<T>) -> Self {
Self {
start,
stop,
step: None,
}
}
/// Create an `IndexSlice` with only a start bound `[start:]`.
#[must_use]
pub const fn from_start(start: T) -> Self {
Self {
start: Some(start),
stop: None,
step: None,
}
}
/// Create an `IndexSlice` with only a stop bound `[:stop]`.
#[must_use]
pub const fn from_stop(stop: T) -> Self {
Self {
start: None,
stop: Some(stop),
step: None,
}
}
}
/// A hierarchical (multi-level) index for DataFrames and Series.
///
/// Stores multiple levels of labels as separate vectors (columnar layout),
/// analogous to pandas `pd.MultiIndex`. Each row position has one label
/// per level. The combination of labels across all levels forms the
/// composite key for that row.
///
/// This type exists alongside `Index` and can be converted to/from it.
/// Full DataFrame integration is a future step.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiIndex {
/// One `Vec<IndexLabel>` per level, all the same length (= nrows).
levels: Vec<Vec<IndexLabel>>,
/// Optional name for each level, typed: set_index([0, 1]) names them the
/// integers 0 and 1 (fvsao.64).
names: Vec<Option<LabelName>>,
/// Per-level first-seen identity codes, used by duplicate/unique kernels.
#[serde(skip)]
identity_codes: Option<Vec<Vec<u32>>>,
/// A missing label is a value of its level - pandas' groupby
/// (dropna=False) keys, NaN inside `levels` - rather than pandas' code
/// -1 (set_index, from_arrays): an unstack sorts it with the values
/// (last) instead of first. Only [`Self::with_missing_as_level`] sets it.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
missing_is_a_level: bool,
}
/// Typed position plan for an outer alignment of two unique MultiIndexes.
///
/// Each vector is indexed by `union_index` row and names the corresponding
/// source row, or `None` when that side has no matching tuple.
#[derive(Debug, Clone, PartialEq)]
pub struct MultiIndexOuterAlignment {
pub union_index: MultiIndex,
pub left_positions: Vec<Option<usize>>,
pub right_positions: Vec<Option<usize>>,
}
type Utf8LevelPair<'a> = (&'a [IndexLabel], &'a [IndexLabel]);
type Utf8LevelPairs<'a> = (Utf8LevelPair<'a>, Utf8LevelPair<'a>);
struct CompactIdentityCodeLayout<'a> {
level0: &'a [u32],
level1: &'a [u32],
level1_cardinality: usize,
slot_count: usize,
}
impl CompactIdentityCodeLayout<'_> {
#[inline]
fn slot(&self, row: usize) -> usize {
self.level0[row] as usize * self.level1_cardinality + self.level1[row] as usize
}
}
fn multi_index_codes_memory_usage(nlevels: usize, len: usize) -> usize {
nlevels
.saturating_mul(len)
.saturating_mul(std::mem::size_of::<isize>())
}
fn build_multi_index_identity_codes(levels: &[Vec<IndexLabel>]) -> Option<Vec<Vec<u32>>> {
if levels.len() != 2 {
return None;
}
let len = levels.first().map_or(0, Vec::len);
if len == 0 || levels[1].len() != len {
return None;
}
let slot_cap = len.saturating_mul(8).max(1024);
let mut level0_positions =
FxHashMap::<&IndexLabel, u32>::with_capacity_and_hasher(len, Default::default());
let mut level0_codes = Vec::with_capacity(len);
for label in &levels[0] {
if let Some(&code) = level0_positions.get(label) {
level0_codes.push(code);
} else {
let code = u32::try_from(level0_positions.len()).ok()?;
level0_positions.insert(label, code);
level0_codes.push(code);
}
}
let level0_cardinality = level0_positions.len();
if level0_cardinality > slot_cap {
return None;
}
let mut level1_positions =
FxHashMap::<&IndexLabel, u32>::with_capacity_and_hasher(len, Default::default());
let mut level1_codes = Vec::with_capacity(len);
for label in &levels[1] {
if let Some(&code) = level1_positions.get(label) {
level1_codes.push(code);
} else {
let next_cardinality = level1_positions.len().checked_add(1)?;
let slot_count = level0_cardinality.checked_mul(next_cardinality)?;
if slot_count > slot_cap {
return None;
}
let code = u32::try_from(level1_positions.len()).ok()?;
level1_positions.insert(label, code);
level1_codes.push(code);
}
}
Some(vec![level0_codes, level1_codes])
}
impl PartialEq for MultiIndex {
fn eq(&self, other: &Self) -> bool {
self.levels == other.levels && self.names == other.names
}
}
impl MultiIndex {
fn from_levels_and_names(levels: Vec<Vec<IndexLabel>>, names: Vec<Option<LabelName>>) -> Self {
let identity_codes = build_multi_index_identity_codes(&levels);
Self {
levels,
names,
identity_codes,
missing_is_a_level: false,
}
}
/// These levels with a missing label read as a value of its level (see
/// the field): a groupby result's keys under dropna=False.
#[must_use]
pub fn with_missing_as_level(mut self, missing_is_a_level: bool) -> Self {
self.missing_is_a_level = missing_is_a_level;
self
}
/// Whether a missing label is a value of its level (see the field).
#[must_use]
pub fn missing_is_a_level(&self) -> bool {
self.missing_is_a_level
}
fn compact_two_level_identity_layout(&self) -> Option<CompactIdentityCodeLayout<'_>> {
let codes = self.identity_codes.as_ref()?;
if codes.len() != 2 || codes[0].len() != self.len() || codes[1].len() != self.len() {
return None;
}
let level0_cardinality = codes[0]
.iter()
.copied()
.max()
.map_or(0usize, |code| code as usize + 1);
let level1_cardinality = codes[1]
.iter()
.copied()
.max()
.map_or(0usize, |code| code as usize + 1);
let slot_count = level0_cardinality.checked_mul(level1_cardinality)?;
if slot_count == 0 {
return None;
}
if slot_count > self.len().saturating_mul(8).max(1024) {
return None;
}
Some(CompactIdentityCodeLayout {
level0: &codes[0],
level1: &codes[1],
level1_cardinality,
slot_count,
})
}
/// Number of levels in this MultiIndex.
#[must_use]
pub fn nlevels(&self) -> usize {
self.levels.len()
}
/// Number of rows (entries) in this MultiIndex.
#[must_use]
pub fn len(&self) -> usize {
self.levels.first().map_or(0, Vec::len)
}
/// Whether this MultiIndex has zero entries.
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Compare two rows lexicographically across all levels.
///
/// Private helper for sortedness predicates. Returns `Ordering::Equal`
/// only when every level value matches exactly.
fn row_cmp(&self, a: usize, b: usize) -> std::cmp::Ordering {
for level in 0..self.nlevels() {
let ord = self.levels[level][a].cmp(&self.levels[level][b]);
if ord != std::cmp::Ordering::Equal {
return ord;
}
}
std::cmp::Ordering::Equal
}
/// Whether this MultiIndex is sorted in lexicographic (row-major) order.
///
/// Matches `pd.MultiIndex.is_monotonic_increasing`. Row `i` must be less
/// than or equal to row `i+1` under level-by-level comparison. Empty or
/// single-row indexes return `true` (trivially sorted).
///
/// Per br-frankenpandas-w4uu: pandas `df.loc['A':'B']` on a MultiIndex
/// raises `KeyError: MultiIndex slicing requires the index to be
/// lexsorted` when this predicate is false. fp-frame's range-slice
/// callers should gate on this before delegating to `slice_locs`.
#[must_use]
pub fn is_monotonic_increasing(&self) -> bool {
if self.len() <= 1 {
return true;
}
(0..self.len() - 1).all(|i| self.row_cmp(i, i + 1) != std::cmp::Ordering::Greater)
}
/// Whether this MultiIndex is sorted in strictly descending order.
///
/// Matches `pd.MultiIndex.is_monotonic_decreasing`. Row `i` must be
/// greater than or equal to row `i+1`. Empty / single-row: `true`.
#[must_use]
pub fn is_monotonic_decreasing(&self) -> bool {
if self.len() <= 1 {
return true;
}
(0..self.len() - 1).all(|i| self.row_cmp(i, i + 1) != std::cmp::Ordering::Less)
}
/// Alias for `is_monotonic_increasing`.
///
/// ⚠️ REMOVED, not deprecated: `pd.MultiIndex.is_lexsorted` raises
/// `AttributeError` on 2.2.3 (deprecated in 1.x, dropped in 2.0). Kept as a
/// convenience alias for migrated code -- an FP superset, not parity.
#[must_use]
pub fn is_lexsorted(&self) -> bool {
self.is_monotonic_increasing()
}
/// Level names, typed ([`LabelName`]).
#[must_use]
pub fn names(&self) -> &[Option<LabelName>] {
&self.names
}
/// Scalar index name, matching `pd.MultiIndex.name`.
#[must_use]
pub const fn name(&self) -> Option<&LabelName> {
None
}
/// Number of entries, matching `pd.MultiIndex.size`.
#[must_use]
pub fn size(&self) -> usize {
self.len()
}
/// Shape of this one-dimensional index, matching `pd.MultiIndex.shape`.
#[must_use]
pub fn shape(&self) -> (usize,) {
(self.len(),)
}
/// Number of dimensions, matching `pd.MultiIndex.ndim`.
#[must_use]
pub fn ndim(&self) -> usize {
1
}
/// Alias for `is_empty`, matching the pandas `.empty` property.
#[must_use]
pub fn empty(&self) -> bool {
self.is_empty()
}
fn shift_unsupported_error() -> IndexError {
IndexError::InvalidArgument(
"This method is only implemented for DatetimeIndex, PeriodIndex and TimedeltaIndex; Got type MultiIndex"
.to_owned(),
)
}
/// Unsupported temporal shift, matching `pd.MultiIndex.shift(...)`.
pub fn shift(&self, _periods: i64, _freq: Option<&str>) -> Result<Self, IndexError> {
Err(Self::shift_unsupported_error())
}
fn astype_categorical_error() -> IndexError {
IndexError::InvalidArgument(
"> 1 ndim Categorical are not supported at this time".to_owned(),
)
}
fn astype_unsupported_dtype_error(dtype: &str) -> IndexError {
IndexError::InvalidArgument(format!(
"Setting a MultiIndex dtype to anything other than object is not supported; got {dtype}"
))
}
/// Cast labels to a different dtype, matching `pd.MultiIndex.astype(...)`.
///
/// Pandas only supports the object dtype on MultiIndex; categorical raises
/// `NotImplementedError` and any other dtype raises `TypeError`. Object
/// returns a clone of the index.
pub fn astype(&self, dtype: &str) -> Result<Self, IndexError> {
match dtype {
"object" | "O" => Ok(self.clone()),
"category" => Err(Self::astype_categorical_error()),
other => Err(Self::astype_unsupported_dtype_error(other)),
}
}
fn diff_unsupported_error() -> IndexError {
IndexError::InvalidArgument(
"cannot perform __sub__ with this index type: MultiIndex".to_owned(),
)
}
/// Unsupported positional differencing, matching `pd.MultiIndex.diff(...)`.
///
/// Pandas defines `Index.diff` as `self - self.shift(periods)` and raises
/// `TypeError` because tuple-valued levels do not support subtraction.
pub fn diff(&self, _periods: i64) -> Result<Self, IndexError> {
Err(Self::diff_unsupported_error())
}
/// Numeric rounding, matching `pd.MultiIndex.round(...)`, which is a NO-OP
/// returning an equal copy.
///
/// ⚠️ THIS USED TO REFUSE, on the reasoning that "pandas applies `np.around`
/// to the underlying values; tuple-valued MultiIndex labels do not support
/// `rint`". That conflates two different calls. MEASURED, live pandas 2.2.3:
///
/// ```text
/// mi = pd.MultiIndex.from_tuples([(1.567, "a"), (2.345, "b")])
/// mi.round(0) / round(2) / round(-1) -> [(1.567, 'a'), (2.345, 'b')] unchanged
/// mi.round(2).equals(mi) -> True (a copy, not the same object)
/// np.around(mi, 2) -> TypeError: can't multiply sequence
/// by non-int of type 'float'
/// ```
///
/// So `np.around(index)` does raise — but `Index.round()` never reaches it for
/// a MultiIndex, and the float level value is NOT rounded either. The old
/// error text was numpy's `rint` message, which is not even what numpy emits
/// on this input.
///
/// `decimals` is accepted and ignored, exactly as pandas does.
pub fn round(&self, _decimals: i32) -> Result<Self, IndexError> {
Ok(self.clone())
}
fn string_accessor_error() -> IndexError {
IndexError::InvalidArgument(
"Can only use .str accessor with Index, not MultiIndex".to_owned(),
)
}
/// Unsupported string accessor.
///
/// Refusing IS the parity behaviour: `pd.MultiIndex.str` raises
/// `AttributeError` on 2.2.3 (a plain string-valued `pd.Index` DOES carry
/// `.str`; a MultiIndex does not). The wording before cited the attribute as
/// though it existed.
pub fn r#str(&self) -> Result<(), IndexError> {
Err(Self::string_accessor_error())
}
fn asof_comparison_type_name(&self) -> &'static str {
match self.levels.first().and_then(|level| level.first()) {
Some(IndexLabel::Int64(_)) => "int",
Some(IndexLabel::Float64(_)) => "float",
Some(IndexLabel::Bool(_)) => "bool",
Some(IndexLabel::Utf8(_)) => "str",
Some(IndexLabel::Timedelta64(_)) => "Timedelta",
Some(IndexLabel::Datetime64(_)) => "Timestamp",
Some(IndexLabel::Null(fp_types::NullKind::Null)) => "NoneType",
Some(IndexLabel::Null(fp_types::NullKind::NaN)) => "float",
Some(IndexLabel::Null(fp_types::NullKind::NaT)) => "NaTType",
Some(IndexLabel::Period(_)) => "Period",
Some(IndexLabel::Interval(_)) => "Interval",
Some(IndexLabel::Object(_)) | None => "object",
}
}
fn asof_unsupported_error(&self) -> IndexError {
IndexError::InvalidArgument(format!(
"'<' not supported between instances of 'tuple' and '{}'",
self.asof_comparison_type_name()
))
}
/// Unsupported nearest-key lookup, matching `pd.MultiIndex.asof(...)`.
pub fn asof(&self, _key: &[IndexLabel]) -> Result<Option<Vec<IndexLabel>>, IndexError> {
if self.is_empty() {
return Ok(None);
}
Err(self.asof_unsupported_error())
}
fn asof_locs_no_mask_error() -> IndexError {
IndexError::InvalidArgument("object too deep for desired array".to_owned())
}
fn asof_locs_empty_mask_error() -> IndexError {
IndexError::InvalidArgument("attempt to get argmax of an empty sequence".to_owned())
}
fn asof_locs_empty_take_error() -> IndexError {
IndexError::InvalidArgument("cannot do a non-empty take from an empty axes.".to_owned())
}
fn asof_locs_mask_length_error(expected: usize, actual: usize) -> IndexError {
IndexError::InvalidArgument(format!(
"boolean index did not match indexed array along axis 0; size of axis is {expected} but size of corresponding boolean axis is {actual}"
))
}
fn asof_locs_broadcast_error(where_len: usize) -> IndexError {
IndexError::InvalidArgument(format!(
"operands could not be broadcast together with shapes ({where_len},) (2,)"
))
}
/// Unsupported nearest-position lookup, matching `pd.MultiIndex.asof_locs(...)`.
pub fn asof_locs(
&self,
where_index: &Self,
mask: Option<&[bool]>,
) -> Result<Vec<Option<usize>>, IndexError> {
let Some(mask) = mask else {
return Err(Self::asof_locs_no_mask_error());
};
if mask.len() != self.len() {
return Err(Self::asof_locs_mask_length_error(self.len(), mask.len()));
}
if mask.is_empty() && self.is_empty() && where_index.is_empty() {
return Err(Self::asof_locs_empty_mask_error());
}
if mask.iter().all(|include| !*include) && !where_index.is_empty() {
return Err(Self::asof_locs_empty_take_error());
}
Err(Self::asof_locs_broadcast_error(where_index.len()))
}
/// Set the names for all levels.
#[must_use]
pub fn set_names(mut self, names: Vec<Option<LabelName>>) -> Self {
// Pad or truncate to match nlevels.
self.names = names;
self.names.resize(self.nlevels(), None);
self
}
/// Rename all MultiIndex levels, matching `pd.MultiIndex.rename(names)`.
///
/// Unlike [`Self::set_names`], pandas rename requires one name per level
/// and returns a renamed clone without mutating the source index.
pub fn rename(&self, names: Vec<Option<LabelName>>) -> Result<Self, IndexError> {
if names.len() != self.nlevels() {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: names.len(),
context: "MultiIndex.rename names length".to_owned(),
});
}
Ok(Self::from_levels_and_names(self.levels.clone(), names))
}
/// Rename one MultiIndex level, matching `pd.MultiIndex.rename(name, level=...)`.
pub fn rename_level(&self, name: Option<LabelName>, level: usize) -> Result<Self, IndexError> {
if level >= self.nlevels() {
return Err(IndexError::OutOfBounds {
position: level,
length: self.nlevels(),
});
}
let mut names = self.names.clone();
names[level] = name;
Ok(Self::from_levels_and_names(self.levels.clone(), names))
}
fn shared_names(&self, other: &Self) -> Vec<Option<LabelName>> {
self.names
.iter()
.zip(&other.names)
.map(
|(left, right)| {
if left == right { left.clone() } else { None }
},
)
.collect()
}
fn ensure_same_nlevels(&self, other: &Self) -> Result<(), IndexError> {
if self.nlevels() != other.nlevels() {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: other.nlevels(),
context: "MultiIndex level count mismatch".to_owned(),
});
}
Ok(())
}
/// Build the AACE outer-alignment witness without materializing composite
/// `Vec<IndexLabel>` tuples when the per-level codes fit in a `u64`.
///
/// Outer alignment is only position-preserving for unique composite labels;
/// duplicate tuples retain pandas' duplicate-aware expansion surface and
/// are rejected here rather than silently choosing a first occurrence.
pub fn outer_align(&self, other: &Self) -> Result<MultiIndexOuterAlignment, IndexError> {
self.ensure_same_nlevels(other)?;
if self.has_duplicates() || other.has_duplicates() {
return Err(IndexError::InvalidArgument(
"outer_align requires uniquely valued MultiIndexes".to_owned(),
));
}
if let Some((left_keys, right_keys)) = self.factorize_packed_keys(other) {
let mut union_levels: Vec<Vec<IndexLabel>> = self
.levels
.iter()
.map(|_| Vec::with_capacity(self.len().saturating_add(other.len())))
.collect();
let mut union_positions =
FxHashMap::<u64, usize>::with_capacity_and_hasher(self.len(), Default::default());
let mut left_positions = Vec::with_capacity(self.len().saturating_add(other.len()));
let mut right_positions = Vec::with_capacity(self.len().saturating_add(other.len()));
for (row, &key) in left_keys.iter().enumerate() {
union_positions.insert(key, left_positions.len());
for (out, level) in union_levels.iter_mut().zip(&self.levels) {
out.push(level[row].clone());
}
left_positions.push(Some(row));
right_positions.push(None);
}
for (row, &key) in right_keys.iter().enumerate() {
if let Some(&union_row) = union_positions.get(&key) {
right_positions[union_row] = Some(row);
} else {
union_positions.insert(key, left_positions.len());
for (out, level) in union_levels.iter_mut().zip(&other.levels) {
out.push(level[row].clone());
}
left_positions.push(None);
right_positions.push(Some(row));
}
}
return Ok(MultiIndexOuterAlignment {
union_index: Self::from_levels_and_names(union_levels, self.shared_names(other)),
left_positions,
right_positions,
});
}
let union_index = self.union(other)?;
Ok(MultiIndexOuterAlignment {
left_positions: self
.get_indexer(&union_index)?
.into_iter()
.map(|position| usize::try_from(position).ok())
.collect(),
right_positions: other
.get_indexer(&union_index)?
.into_iter()
.map(|position| usize::try_from(position).ok())
.collect(),
union_index,
})
}
fn tuple_at(&self, row: usize) -> Vec<IndexLabel> {
self.levels.iter().map(|level| level[row].clone()).collect()
}
fn take_existing_positions(&self, positions: &[usize]) -> Self {
let levels = self
.levels
.iter()
.map(|level| {
positions
.iter()
.map(|&position| level[position].clone())
.collect()
})
.collect();
Self::from_levels_and_names(levels, self.names.clone())
.with_missing_as_level(self.missing_is_a_level)
}
fn missing_label_for_level(&self, level_idx: usize) -> IndexLabel {
self.levels[level_idx]
.iter()
.find(|label| label.is_missing())
.cloned()
.unwrap_or(IndexLabel::Datetime64(i64::MIN))
}
fn from_tuples_with_names(
tuples: Vec<Vec<IndexLabel>>,
names: Vec<Option<LabelName>>,
) -> Result<Self, IndexError> {
Ok(Self::from_tuples(tuples)?.set_names(names))
}
/// A level's catalog as pandas factorizes it (sorted, its `safe_sort`):
/// the distinct non-missing labels, numbers (bools, ints, floats) by
/// value first, then strings, then any other kind in its own order.
fn level_catalog(level: &[IndexLabel]) -> Vec<IndexLabel> {
fn number(label: &IndexLabel) -> Option<f64> {
match label {
IndexLabel::Bool(value) => Some(f64::from(u8::from(*value))),
#[allow(clippy::cast_precision_loss)] // only ordering int vs float
IndexLabel::Int64(value) => Some(*value as f64),
IndexLabel::Float64(value) => Some(value.0),
_ => None,
}
}
fn kind(label: &IndexLabel) -> u8 {
match label {
IndexLabel::Bool(_) | IndexLabel::Int64(_) | IndexLabel::Float64(_) => 0,
IndexLabel::Utf8(_) => 1,
_ => 2,
}
}
let mut seen = FxHashMap::<&IndexLabel, ()>::default();
let mut catalog: Vec<IndexLabel> = level
.iter()
.filter(|label| !label.is_missing() && seen.insert(label, ()).is_none())
.cloned()
.collect();
catalog.sort_by(|a, b| match (a, b) {
(IndexLabel::Int64(x), IndexLabel::Int64(y)) => x.cmp(y),
_ => match (number(a), number(b)) {
(Some(x), Some(y)) => x.total_cmp(&y).then_with(|| a.cmp(b)),
_ => kind(a).cmp(&kind(b)).then_with(|| a.cmp(b)),
},
});
catalog
}
/// Unique labels for each level, sorted as pandas factorizes them
/// (br-frankenpandas-98f6w: they kept first-seen order).
///
/// Matches `pd.MultiIndex.levels`. Missing labels are excluded from the
/// level catalog and receive `-1` in `codes()`.
#[must_use]
pub fn levels(&self) -> Vec<Index> {
self.levels
.iter()
.enumerate()
.map(|(level_idx, level)| {
let mut index = Index::new(Self::level_catalog(level));
if let Some(name) = self.names.get(level_idx).and_then(|name| name.as_ref()) {
index = index.set_name(name);
}
index
})
.collect()
}
/// Integer level codes for each row, matching `pd.MultiIndex.codes`.
///
/// Missing labels receive code `-1`; all other labels are encoded by their
/// position in the corresponding (sorted) `levels()` entry.
#[must_use]
pub fn codes(&self) -> Vec<Vec<isize>> {
self.levels
.iter()
.map(|level| {
let positions: FxHashMap<IndexLabel, isize> = Self::level_catalog(level)
.into_iter()
.enumerate()
.map(|(code, label)| (label, isize::try_from(code).unwrap_or(isize::MAX)))
.collect();
level
.iter()
.map(|label| {
if label.is_missing() {
-1
} else {
positions.get(label).copied().unwrap_or(-1)
}
})
.collect()
})
.collect()
}
/// Cardinality of each level, matching `pd.MultiIndex.levshape`.
#[must_use]
pub fn levshape(&self) -> Vec<usize> {
self.levels().iter().map(Index::len).collect()
}
/// Materialize every composite key as an owned tuple.
///
/// Matches `pd.MultiIndex.to_list()` / `tolist()`.
#[must_use]
pub fn to_list(&self) -> Vec<Vec<IndexLabel>> {
(0..self.len()).map(|row| self.tuple_at(row)).collect()
}
/// Alias for `to_list`, matching `pd.MultiIndex.tolist()`.
#[must_use]
pub fn tolist(&self) -> Vec<Vec<IndexLabel>> {
self.to_list()
}
/// Object-array-shaped materialization, matching `pd.MultiIndex.to_numpy`.
#[must_use]
pub fn to_numpy(&self) -> Vec<Vec<IndexLabel>> {
self.to_list()
}
/// Alias for `to_numpy`, matching `pd.MultiIndex.values`.
#[must_use]
pub fn values(&self) -> Vec<Vec<IndexLabel>> {
self.to_numpy()
}
/// Alias for `to_numpy`, matching `pd.MultiIndex.array`.
#[must_use]
pub fn array(&self) -> Vec<Vec<IndexLabel>> {
self.to_numpy()
}
/// Alias for `to_numpy`, matching `pd.MultiIndex.ravel()`.
#[must_use]
pub fn ravel(&self) -> Vec<Vec<IndexLabel>> {
self.to_numpy()
}
/// Return a shallow clone view, matching `pd.MultiIndex.view`.
#[must_use]
pub fn view(&self) -> Self {
self.clone()
}
/// MultiIndex transpose is identity, matching `pd.MultiIndex.transpose`.
#[must_use]
pub fn transpose(&self) -> Self {
self.clone()
}
/// Alias for `transpose`, matching `pd.MultiIndex.T`.
#[allow(non_snake_case)]
#[must_use]
pub fn T(&self) -> Self {
self.transpose()
}
/// Row materialization for `pd.MultiIndex.to_frame(index=False)`.
///
/// `fp-frame` owns the richer DataFrame return type; the index crate keeps
/// the level-by-level row payload that callers can lift into a frame.
#[must_use]
pub fn to_frame(&self) -> Vec<Vec<IndexLabel>> {
self.to_list()
}
/// Series-shaped materialization using tuple keys as both index and value.
///
/// This mirrors `pd.MultiIndex.to_series()` at the payload level while
/// avoiding a dependency from `fp-index` back into `fp-frame`.
#[must_use]
pub fn to_series(&self) -> Vec<(Vec<IndexLabel>, Vec<IndexLabel>)> {
self.to_list()
.into_iter()
.map(|tuple| (tuple.clone(), tuple))
.collect()
}
/// Stringify each tuple in row order, matching `pd.MultiIndex.format()`.
#[must_use]
pub fn format(&self) -> Vec<String> {
self.to_list()
.into_iter()
.map(|tuple| {
let parts: Vec<String> = tuple.into_iter().map(|label| label.to_string()).collect();
format!("({})", parts.join(", "))
})
.collect()
}
/// Approximate memory footprint of all level labels and codes.
///
/// `deep=false` counts fixed-width labels and `String` headers; `deep=true`
/// additionally counts string bytes, mirroring `Index::memory_usage`.
#[must_use]
pub fn memory_usage(&self, deep: bool) -> usize {
let level_bytes = self.levels.iter().flatten().fold(0usize, |total, label| {
total.saturating_add(match label {
IndexLabel::Int64(_)
| IndexLabel::Float64(_)
| IndexLabel::Timedelta64(_)
| IndexLabel::Datetime64(_)
| IndexLabel::Object(_)
| IndexLabel::Period(_)
| IndexLabel::Interval(_)
| IndexLabel::Null(_) => 8,
IndexLabel::Bool(_) => 1,
IndexLabel::Utf8(value) => {
if deep {
std::mem::size_of::<String>().saturating_add(value.len())
} else {
std::mem::size_of::<String>()
}
}
})
});
level_bytes.saturating_add(multi_index_codes_memory_usage(self.nlevels(), self.len()))
}
/// Shallow memory footprint, matching `pd.MultiIndex.nbytes`.
#[must_use]
pub fn nbytes(&self) -> usize {
self.memory_usage(false)
}
/// Pandas dtype string for MultiIndex itself.
#[must_use]
pub fn dtype(&self) -> &'static str {
"object"
}
/// Dtype string for each level, matching `pd.MultiIndex.dtypes`.
#[must_use]
pub fn dtypes(&self) -> Vec<&'static str> {
self.levels
.iter()
.map(|level| Index::new(level.clone()).dtype())
.collect()
}
/// Pandas-style inferred type for MultiIndex values.
#[must_use]
pub fn inferred_type(&self) -> &'static str {
"mixed"
}
/// Infer object labels without changing this typed representation.
#[must_use]
pub fn infer_objects(&self) -> Self {
self.clone()
}
/// Whether this MultiIndex can hold integer labels as scalar keys.
#[must_use]
pub fn holds_integer(&self) -> bool {
false
}
/// Return the sole tuple, matching `pd.MultiIndex.item()`.
pub fn item(&self) -> Result<Vec<IndexLabel>, IndexError> {
if self.len() == 1 {
Ok(self.tuple_at(0))
} else {
Err(IndexError::InvalidArgument(format!(
"item requires exactly one tuple, got {}",
self.len()
)))
}
}
/// Return a shallow copy, matching `pd.MultiIndex.copy()`.
#[must_use]
pub fn copy(&self) -> Self {
self.clone()
}
fn multi_index_isna_error() -> IndexError {
IndexError::InvalidArgument("isna is not defined for MultiIndex".to_owned())
}
/// Unsupported missing-label check, matching `pd.MultiIndex.hasnans`.
pub fn hasnans(&self) -> Result<bool, IndexError> {
Err(Self::multi_index_isna_error())
}
/// Unsupported missing-label mask, matching `pd.MultiIndex.isna()`.
pub fn isna(&self) -> Result<Vec<bool>, IndexError> {
Err(Self::multi_index_isna_error())
}
/// Alias for `isna`, matching `pd.MultiIndex.isnull`.
pub fn isnull(&self) -> Result<Vec<bool>, IndexError> {
Err(Self::multi_index_isna_error())
}
/// Unsupported inverse missing-label mask, matching `pd.MultiIndex.notna()`.
pub fn notna(&self) -> Result<Vec<bool>, IndexError> {
Err(Self::multi_index_isna_error())
}
/// Alias for `notna`, matching `pd.MultiIndex.notnull`.
pub fn notnull(&self) -> Result<Vec<bool>, IndexError> {
Err(Self::multi_index_isna_error())
}
/// Replace missing labels in every level with one scalar label.
#[must_use]
pub fn fillna(&self, value: &IndexLabel) -> Self {
let levels = self
.levels
.iter()
.map(|level| {
level
.iter()
.map(|label| {
if label.is_missing() {
value.clone()
} else {
label.clone()
}
})
.collect()
})
.collect();
Self::from_levels_and_names(levels, self.names.clone())
}
/// Replace missing labels with one replacement per level.
pub fn fillna_tuple(&self, values: &[IndexLabel]) -> Result<Self, IndexError> {
if values.len() != self.nlevels() {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: values.len(),
context: "fillna_tuple replacement arity mismatch".to_owned(),
});
}
let levels = self
.levels
.iter()
.enumerate()
.map(|(level_idx, level)| {
level
.iter()
.map(|label| {
if label.is_missing() {
values[level_idx].clone()
} else {
label.clone()
}
})
.collect()
})
.collect();
Ok(Self::from_levels_and_names(levels, self.names.clone()))
}
/// Replace tuples where `cond` is true with `value`.
pub fn putmask(&self, cond: &[bool], value: Vec<IndexLabel>) -> Result<Self, IndexError> {
if cond.len() != self.len() {
return Err(IndexError::LengthMismatch {
expected: self.len(),
actual: cond.len(),
context: "putmask condition length mismatch".to_owned(),
});
}
if value.len() != self.nlevels() {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: value.len(),
context: "putmask tuple arity mismatch".to_owned(),
});
}
let tuples = (0..self.len())
.map(|row| {
if cond[row] {
value.clone()
} else {
self.tuple_at(row)
}
})
.collect();
Self::from_tuples_with_names(tuples, self.names.clone())
}
/// Keep original tuples where `cond` is true, otherwise use `other`.
pub fn r#where(&self, cond: &[bool], other: Vec<IndexLabel>) -> Result<Self, IndexError> {
if cond.len() != self.len() {
return Err(IndexError::LengthMismatch {
expected: self.len(),
actual: cond.len(),
context: "where condition length mismatch".to_owned(),
});
}
if other.len() != self.nlevels() {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: other.len(),
context: "where tuple arity mismatch".to_owned(),
});
}
let tuples = (0..self.len())
.map(|row| {
if cond[row] {
self.tuple_at(row)
} else {
other.clone()
}
})
.collect();
Self::from_tuples_with_names(tuples, self.names.clone())
}
/// Map each composite tuple through a caller-supplied function.
pub fn map<T, F>(&self, mut mapper: F) -> Vec<T>
where
F: FnMut(&[IndexLabel]) -> T,
{
(0..self.len())
.map(|row| {
let tuple = self.tuple_at(row);
mapper(&tuple)
})
.collect()
}
/// Rebuild row labels using replacement level catalogs and current codes.
pub fn set_levels(&self, new_levels: Vec<Vec<IndexLabel>>) -> Result<Self, IndexError> {
if new_levels.len() != self.nlevels() {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: new_levels.len(),
context: "set_levels level count mismatch".to_owned(),
});
}
let codes = self.codes();
let mut levels = Vec::with_capacity(self.nlevels());
for (level_idx, level_codes) in codes.into_iter().enumerate() {
let mut level = Vec::with_capacity(self.len());
for code in level_codes {
if code == -1 {
level.push(self.missing_label_for_level(level_idx));
continue;
}
if code < -1 {
return Err(IndexError::InvalidArgument(format!(
"negative code {code} at level {level_idx}"
)));
}
let position = usize::try_from(code).map_err(|_| {
IndexError::InvalidArgument(format!("invalid code {code} at level {level_idx}"))
})?;
let label = new_levels[level_idx]
.get(position)
.ok_or(IndexError::OutOfBounds {
position,
length: new_levels[level_idx].len(),
})?;
level.push(label.clone());
}
levels.push(level);
}
Ok(Self::from_levels_and_names(levels, self.names.clone()))
}
/// Rebuild row labels using replacement codes and current level catalogs.
pub fn set_codes(&self, codes: Vec<Vec<isize>>) -> Result<Self, IndexError> {
if codes.len() != self.nlevels() {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: codes.len(),
context: "set_codes level count mismatch".to_owned(),
});
}
let catalogs = self.levels();
let mut levels = Vec::with_capacity(self.nlevels());
for (level_idx, level_codes) in codes.into_iter().enumerate() {
if level_codes.len() != self.len() {
return Err(IndexError::LengthMismatch {
expected: self.len(),
actual: level_codes.len(),
context: format!("set_codes level {level_idx} length mismatch"),
});
}
let labels = catalogs[level_idx].labels();
let mut level = Vec::with_capacity(self.len());
for code in level_codes {
if code == -1 {
level.push(self.missing_label_for_level(level_idx));
continue;
}
if code < -1 {
return Err(IndexError::InvalidArgument(format!(
"negative code {code} at level {level_idx}"
)));
}
let position = usize::try_from(code).map_err(|_| {
IndexError::InvalidArgument(format!("invalid code {code} at level {level_idx}"))
})?;
let label = labels.get(position).ok_or(IndexError::OutOfBounds {
position,
length: labels.len(),
})?;
level.push(label.clone());
}
levels.push(level);
}
Ok(Self::from_levels_and_names(levels, self.names.clone()))
}
/// Drop unused level labels. This representation stores row labels directly,
/// so there is no separate unused catalog to prune.
#[must_use]
pub fn remove_unused_levels(&self) -> Self {
self.clone()
}
/// Identity check, matching `pd.MultiIndex.is_`.
#[must_use]
pub fn is_(&self, other: &Self) -> bool {
std::ptr::eq(self, other)
}
/// Whether this MultiIndex is boolean-typed.
#[must_use]
pub fn is_boolean(&self) -> bool {
false
}
/// Whether this MultiIndex is categorical-typed.
#[must_use]
pub fn is_categorical(&self) -> bool {
false
}
/// Whether this MultiIndex is floating-typed.
#[must_use]
pub fn is_floating(&self) -> bool {
false
}
/// Whether this MultiIndex is integer-typed.
#[must_use]
pub fn is_integer(&self) -> bool {
false
}
/// Whether this MultiIndex is interval-typed.
#[must_use]
pub fn is_interval(&self) -> bool {
false
}
/// Whether this MultiIndex is numeric-typed.
#[must_use]
pub fn is_numeric(&self) -> bool {
false
}
/// Whether this MultiIndex is object-backed.
#[must_use]
pub fn is_object(&self) -> bool {
true
}
/// Compare row tuples only, matching `pd.MultiIndex.equals`.
#[must_use]
pub fn equals(&self, other: &Self) -> bool {
self.levels == other.levels
}
/// Compare row tuples and level names, matching `pd.MultiIndex.identical`.
#[must_use]
pub fn identical(&self, other: &Self) -> bool {
self.equals(other) && self.names == other.names
}
/// Compare unique level catalogs, matching `pd.MultiIndex.equal_levels`.
#[must_use]
pub fn equal_levels(&self, other: &Self) -> bool {
self.levels() == other.levels()
}
/// Get the labels for a specific level.
///
/// Matches `pd.MultiIndex.get_level_values(level)`.
pub fn get_level_values(&self, level: usize) -> Result<Index, IndexError> {
if level >= self.levels.len() {
return Err(IndexError::OutOfBounds {
position: level,
length: self.levels.len(),
});
}
let mut idx = Index::new(self.levels[level].clone());
if let Some(name) = self.names.get(level).and_then(|n| n.as_ref()) {
idx = idx.set_name(name);
}
Ok(idx)
}
/// Get the tuple of labels at a specific position.
pub fn get_tuple(&self, position: usize) -> Option<Vec<&IndexLabel>> {
if position >= self.len() {
return None;
}
Some(self.levels.iter().map(|level| &level[position]).collect())
}
/// Select rows by positional index.
pub fn take(&self, positions: &[usize]) -> Result<Self, IndexError> {
for &position in positions {
if position >= self.len() {
return Err(IndexError::OutOfBounds {
position,
length: self.len(),
});
}
}
let mut levels = Vec::with_capacity(self.nlevels());
for level in &self.levels {
let selected = positions
.iter()
.map(|&position| level[position].clone())
.collect();
levels.push(selected);
}
// Rows of the same levels: a missing label stays what it was.
Ok(Self::from_levels_and_names(levels, self.names.clone())
.with_missing_as_level(self.missing_is_a_level))
}
/// Delete the tuple at a positional location.
///
/// Matches `pd.MultiIndex.delete(loc)`.
pub fn delete(&self, loc: usize) -> Result<Self, IndexError> {
if loc >= self.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: self.len(),
});
}
let positions: Vec<usize> = (0..self.len()).filter(|&row| row != loc).collect();
Ok(self.take_existing_positions(&positions))
}
/// Insert a tuple at a positional location.
///
/// Matches `pd.MultiIndex.insert(loc, item)`. Inserting into an empty
/// zero-level MultiIndex adopts the tuple arity as the new level count.
pub fn insert(&self, loc: usize, item: Vec<IndexLabel>) -> Result<Self, IndexError> {
if loc > self.len() {
return Err(IndexError::OutOfBounds {
position: loc,
length: self.len(),
});
}
if self.nlevels() == 0 {
if loc != 0 {
return Err(IndexError::OutOfBounds {
position: loc,
length: 0,
});
}
return Self::from_tuples(vec![item]);
}
if item.len() != self.nlevels() {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: item.len(),
context: "insert tuple arity mismatch".to_owned(),
});
}
let mut levels = self.levels.clone();
for (level_idx, label) in item.into_iter().enumerate() {
levels[level_idx].insert(loc, label);
}
Ok(Self::from_levels_and_names(levels, self.names.clone()))
}
/// Drop every occurrence of the provided tuples.
///
/// Matches `pd.MultiIndex.drop(labels)` with the default fail-closed
/// behavior for missing labels.
pub fn drop(&self, labels_to_drop: &[Vec<IndexLabel>]) -> Result<Self, IndexError> {
for label in labels_to_drop {
self.validate_key_arity(label, false)?;
}
// Reuse one key buffer across rows instead of materializing every row
// tuple via to_list() (which allocates a Vec per row). `found` stores
// references into `labels_to_drop` (stable across iterations) — obtained
// from drop_set.get() — so the reused buffer never escapes. FxHashSet
// replaces the std SipHash set. Bit-identical: same retained positions
// and same missing-key detection (value-based membership).
let drop_set: FxHashSet<&Vec<IndexLabel>> = labels_to_drop.iter().collect();
let mut found: FxHashSet<&Vec<IndexLabel>> = FxHashSet::default();
let mut positions = Vec::new();
let mut key: Vec<IndexLabel> = Vec::with_capacity(self.nlevels());
for row in 0..self.len() {
key.clear();
key.extend(self.levels.iter().map(|level| level[row].clone()));
if let Some(matched) = drop_set.get(&key) {
found.insert(*matched);
} else {
positions.push(row);
}
}
if let Some(missing) = labels_to_drop.iter().find(|label| !found.contains(label)) {
return Err(IndexError::InvalidArgument(format!(
"tuple key not found: {:?}",
missing
)));
}
Ok(self.take_existing_positions(&positions))
}
fn validate_key_arity(
&self,
key: &[IndexLabel],
allow_partial: bool,
) -> Result<(), IndexError> {
let nlevels = self.nlevels();
if key.is_empty() {
return Err(IndexError::InvalidArgument(
"MultiIndex key must contain at least one level".to_owned(),
));
}
if (!allow_partial && key.len() != nlevels) || (allow_partial && key.len() > nlevels) {
return Err(IndexError::InvalidArgument(format!(
"wrong tuple arity: expected {}{}, got {}",
if allow_partial { "1.." } else { "" },
nlevels,
key.len()
)));
}
Ok(())
}
fn row_matches_prefix(&self, row: usize, key: &[IndexLabel]) -> bool {
key.iter()
.enumerate()
.all(|(level, expected)| &self.levels[level][row] == expected)
}
fn row_prefix_cmp(&self, row: usize, key: &[IndexLabel]) -> std::cmp::Ordering {
for (level, expected) in key.iter().enumerate() {
let ord = self.levels[level][row].cmp(expected);
if ord != std::cmp::Ordering::Equal {
return ord;
}
}
std::cmp::Ordering::Equal
}
/// Return matching row positions for an exact tuple key.
pub fn get_loc_tuple(&self, key: &[IndexLabel]) -> Result<Vec<usize>, IndexError> {
self.validate_key_arity(key, false)?;
let positions: Vec<usize> = (0..self.len())
.filter(|&row| self.row_matches_prefix(row, key))
.collect();
if positions.is_empty() {
return Err(IndexError::InvalidArgument(format!(
"tuple key not found: {:?}",
key
)));
}
Ok(positions)
}
/// Return row positions for an exact tuple, partial-prefix tuple, or a single level key.
///
/// `level=None` treats `key` as an exact tuple when it has full arity, or a
/// prefix tuple when shorter than `nlevels()`. `level=Some(n)` treats
/// `key` as a single label lookup on that level.
pub fn get_loc(
&self,
key: &[IndexLabel],
level: Option<usize>,
) -> Result<Vec<usize>, IndexError> {
if let Some(level) = level {
if level >= self.nlevels() {
return Err(IndexError::OutOfBounds {
position: level,
length: self.nlevels(),
});
}
if key.len() != 1 {
return Err(IndexError::InvalidArgument(format!(
"level lookup expects exactly one label, got {}",
key.len()
)));
}
let positions: Vec<usize> = self.levels[level]
.iter()
.enumerate()
.filter_map(|(row, label)| if label == &key[0] { Some(row) } else { None })
.collect();
if positions.is_empty() {
return Err(IndexError::InvalidArgument(format!(
"level key not found at level {level}: {:?}",
key[0]
)));
}
return Ok(positions);
}
self.validate_key_arity(key, true)?;
let positions: Vec<usize> = (0..self.len())
.filter(|&row| self.row_matches_prefix(row, key))
.collect();
if positions.is_empty() {
return Err(IndexError::InvalidArgument(format!(
"tuple key not found: {:?}",
key
)));
}
Ok(positions)
}
/// Return row positions for a list-like exact or partial-prefix selector.
///
/// Matches the list-label subset of `pd.MultiIndex.get_locs(seq)`.
pub fn get_locs(&self, key: &[IndexLabel]) -> Result<Vec<usize>, IndexError> {
if key.is_empty() {
return Ok(Vec::new());
}
self.get_loc(key, None)
}
/// pandas-style partial tuple lookup returning matching positions and the remaining index.
pub fn get_loc_level(
&self,
key: &[IndexLabel],
) -> Result<(Vec<usize>, Option<MultiIndexOrIndex>), IndexError> {
let positions = self.get_loc(key, None)?;
if key.len() == self.nlevels() {
return Ok((positions, None));
}
let mut remaining = MultiIndexOrIndex::Multi(self.take(&positions)?);
for _ in 0..key.len() {
remaining = match remaining {
MultiIndexOrIndex::Multi(mi) => mi.droplevel(0)?,
MultiIndexOrIndex::Index(_) => {
return Err(IndexError::InvalidArgument(
"cannot drop more levels than remain".to_owned(),
));
}
};
}
Ok((positions, Some(remaining)))
}
/// Return `(start, stop)` bounds for a lexicographic tuple slice.
///
/// The returned `stop` is exclusive, matching pandas `slice_locs`.
pub fn slice_locs(
&self,
start: Option<&[IndexLabel]>,
end: Option<&[IndexLabel]>,
) -> Result<(usize, usize), IndexError> {
if let Some(start) = start {
self.validate_key_arity(start, true)?;
}
if let Some(end) = end {
self.validate_key_arity(end, true)?;
}
let start_pos = match start {
Some(start_key) => (0..self.len())
.find(|&row| self.row_prefix_cmp(row, start_key) != std::cmp::Ordering::Less)
.unwrap_or(self.len()),
None => 0,
};
let end_pos = match end {
Some(end_key) => (0..self.len())
.rfind(|&row| self.row_prefix_cmp(row, end_key) != std::cmp::Ordering::Greater)
.map_or(0, |row| row + 1),
None => self.len(),
};
if end_pos < start_pos {
return Ok((start_pos, start_pos));
}
Ok((start_pos, end_pos))
}
/// Bound for a tuple slice, matching `pd.MultiIndex.get_slice_bound`.
pub fn get_slice_bound(&self, label: &[IndexLabel], side: &str) -> Result<usize, IndexError> {
match side {
"left" => Ok(self.slice_locs(Some(label), Some(label))?.0),
"right" => Ok(self.slice_locs(Some(label), Some(label))?.1),
other => Err(IndexError::InvalidArgument(format!(
"get_slice_bound: side must be 'left' or 'right', got {other:?}"
))),
}
}
/// Alias for `slice_locs`, matching `pd.MultiIndex.slice_indexer`.
pub fn slice_indexer(
&self,
start: Option<&[IndexLabel]>,
end: Option<&[IndexLabel]>,
) -> Result<(usize, usize), IndexError> {
self.slice_locs(start, end)
}
/// Return a label-bounded range, matching `pd.MultiIndex.truncate`.
///
/// Bounds are interpreted as partial or full tuple prefixes and are
/// inclusive on both sides. Open-ended bounds retain the corresponding
/// leading or trailing rows.
pub fn truncate(
&self,
before: Option<&[IndexLabel]>,
after: Option<&[IndexLabel]>,
) -> Result<Self, IndexError> {
let (start, stop) = self.slice_locs(before, after)?;
let positions: Vec<usize> = (start..stop).collect();
Ok(self.take_existing_positions(&positions))
}
/// Insertion positions for target tuples, matching `pd.MultiIndex.searchsorted`.
///
/// `side` is `"left"` for the first valid insertion position or `"right"`
/// for the position after an equal run. Like pandas, callers are expected
/// to use this on lexicographically sorted indexes.
pub fn searchsorted(&self, target: &Self, side: &str) -> Result<Vec<usize>, IndexError> {
if side != "left" && side != "right" {
return Err(IndexError::InvalidArgument(format!(
"searchsorted: side must be 'left' or 'right', got {side:?}"
)));
}
Ok((0..target.len())
.map(|target_row| {
let needle = target.tuple_at(target_row);
let mut lo = 0_usize;
let mut hi = self.len();
while lo < hi {
let mid = lo + (hi - lo) / 2;
let cmp = self.tuple_at(mid).cmp(&needle);
use std::cmp::Ordering;
let go_right = matches!(
(cmp, side),
(Ordering::Less, _) | (Ordering::Equal, "right")
);
if go_right {
lo = mid + 1;
} else {
hi = mid;
}
}
lo
})
.collect())
}
/// Compute a non-unique indexer against another MultiIndex.
///
/// Matches `pd.MultiIndex.get_indexer_non_unique(target)` by expanding
/// every matching source position for each target tuple in target order.
/// Missing target tuples contribute a single `-1` entry and their target
/// position is recorded in the returned `missing` vector.
#[must_use]
/// Dictionary-encode every level of `self` and `target` into integer codes
/// (consistent across both) and pack each row's tuple into one mixed-radix
/// `u64` key (br-frankenpandas-mipack). Lets get_indexer hash an integer per
/// row instead of allocating a `Vec<IndexLabel>` (and cloning Utf8 Strings)
/// per row. Returns `None` when there are no levels, the level counts
/// differ, or the combined code space overflows `u64` (caller keeps the
/// `Vec<IndexLabel>`-key path). Bijective on tuple identity, so the source
/// map and target lookups match exactly the same rows.
/// Pack each row's tuple into one mixed-radix `u64` whose ascending order
/// equals the lexicographic `row_cmp` order (br-frankenpandas-misort): per
/// level, distinct values are ranked by `IndexLabel::Ord` and the rank codes
/// are packed most-significant-first. So sorting these `u64` keys reproduces
/// the level-by-level tuple sort while comparing integers instead of
/// (Utf8) tuples. Returns `None` when there are no levels or the combined
/// code space overflows `u64` (caller keeps the tuple-comparison sort).
fn sorted_packed_keys(&self) -> Option<Vec<u64>> {
let nlev = self.nlevels();
if nlev == 0 {
return None;
}
let n = self.len();
let mut keys = vec![0u64; n];
let mut combined: u128 = 1;
for level in 0..nlev {
let col = &self.levels[level];
// Dedup to DISTINCT values first (O(n) hash), then sort only those
// (O(d log d)); sorting all n refs would cost as much as the tuple
// sort we are replacing.
let mut sorted: Vec<&IndexLabel> =
col.iter().collect::<FxHashSet<_>>().into_iter().collect();
sorted.sort_unstable();
let radix = sorted.len() as u64;
let mut rank: FxHashMap<&IndexLabel, u64> =
FxHashMap::with_capacity_and_hasher(sorted.len(), Default::default());
for (r, value) in sorted.iter().enumerate() {
rank.insert(*value, r as u64);
}
for (dst, value) in keys.iter_mut().zip(col.iter()) {
*dst = dst.checked_mul(radix)?.checked_add(rank[value])?;
}
combined = combined.checked_mul(radix as u128)?;
if combined > u64::MAX as u128 {
return None;
}
}
Some(keys)
}
/// Pack each row's tuple into one mixed-radix `u64` using FIRST-SEEN per-level
/// codes (br-frankenpandas-midedup). Unlike [`Self::sorted_packed_keys`] this
/// skips the per-level distinct sort — dedup only needs the keys to be a
/// bijection on tuple identity, not lexicographically ordered. Lets
/// duplicated/unique/drop_duplicates hash one integer per row instead of
/// allocating (and Utf8-cloning) a `Vec<IndexLabel>` per row. `None` when
/// there are no levels or the combined code space overflows `u64`.
fn identity_packed_keys(&self) -> Option<Vec<u64>> {
let nlev = self.nlevels();
if nlev == 0 {
return None;
}
let n = self.len();
let mut keys = vec![0u64; n];
let mut combined: u128 = 1;
for level in 0..nlev {
let col = &self.levels[level];
let mut code: FxHashMap<&IndexLabel, u64> =
FxHashMap::with_capacity_and_hasher(col.len(), Default::default());
let mut next = 0u64;
let codes: Vec<u64> = col
.iter()
.map(|value| {
*code.entry(value).or_insert_with(|| {
let c = next;
next += 1;
c
})
})
.collect();
let radix = next;
for (dst, &c) in keys.iter_mut().zip(&codes) {
*dst = dst.checked_mul(radix)?.checked_add(c)?;
}
combined = combined.checked_mul(radix as u128)?;
if combined > u64::MAX as u128 {
return None;
}
}
Some(keys)
}
fn factorize_packed_keys(&self, target: &Self) -> Option<(Vec<u64>, Vec<u64>)> {
let nlev = self.nlevels();
if nlev == 0 || nlev != target.nlevels() {
return None;
}
let n = self.len();
let m = target.len();
let mut src = vec![0u64; n];
let mut tgt = vec![0u64; m];
let mut combined: u128 = 1;
for level in 0..nlev {
let mut codes: FxHashMap<&IndexLabel, u64> = FxHashMap::default();
let mut next = 0u64;
// Source first so its codes are dense and lookups stay consistent;
// target-only values get fresh codes that no source key can match.
let s_level = &self.levels[level];
let t_level = &target.levels[level];
let s_codes: Vec<u64> = (0..n)
.map(|row| {
*codes.entry(&s_level[row]).or_insert_with(|| {
let c = next;
next += 1;
c
})
})
.collect();
let t_codes: Vec<u64> = (0..m)
.map(|row| {
*codes.entry(&t_level[row]).or_insert_with(|| {
let c = next;
next += 1;
c
})
})
.collect();
// Mixed-radix: shift existing partial keys up by this level's radix
// (= its distinct-value count) and add the new codes.
let radix = next;
for (dst, &c) in src.iter_mut().zip(&s_codes) {
*dst = dst.checked_mul(radix)?.checked_add(c)?;
}
for (dst, &c) in tgt.iter_mut().zip(&t_codes) {
*dst = dst.checked_mul(radix)?.checked_add(c)?;
}
combined = combined.checked_mul(radix as u128)?;
if combined > u64::MAX as u128 {
return None;
}
}
Some((src, tgt))
}
fn two_utf8_levels(&self) -> Option<Utf8LevelPair<'_>> {
if self.nlevels() != 2 {
return None;
}
let self_l0 = self.levels[0].as_slice();
let self_l1 = self.levels[1].as_slice();
if [self_l0, self_l1].into_iter().all(|level| {
level
.iter()
.all(|label| matches!(label, IndexLabel::Utf8(_)))
}) {
Some((self_l0, self_l1))
} else {
None
}
}
fn two_utf8_level_slices<'a>(&'a self, target: &'a Self) -> Option<Utf8LevelPairs<'a>> {
if let (Some(self_levels), Some(target_levels)) =
(self.two_utf8_levels(), target.two_utf8_levels())
{
Some((self_levels, target_levels))
} else {
None
}
}
#[inline]
fn utf8_pair_at<'a>(levels: Utf8LevelPair<'a>, row: usize) -> (&'a str, &'a str) {
let IndexLabel::Utf8(left) = &levels.0[row] else {
unreachable!("two_utf8_level_slices pre-validates all labels")
};
let IndexLabel::Utf8(right) = &levels.1[row] else {
unreachable!("two_utf8_level_slices pre-validates all labels")
};
(left.as_str(), right.as_str())
}
fn two_utf8_result_from_pairs(pairs: Vec<(&str, &str)>, names: Vec<Option<LabelName>>) -> Self {
let mut left = Vec::with_capacity(pairs.len());
let mut right = Vec::with_capacity(pairs.len());
for (l, r) in pairs {
left.push(IndexLabel::Utf8(l.to_owned()));
right.push(IndexLabel::Utf8(r.to_owned()));
}
Self::from_levels_and_names(vec![left, right], names)
}
pub fn get_indexer_non_unique(&self, target: &Self) -> (Vec<isize>, Vec<usize>) {
if self.nlevels() != target.nlevels() {
return (vec![-1; target.len()], (0..target.len()).collect());
}
if let Some((src_keys, tgt_keys)) = self.factorize_packed_keys(target) {
let mut positions = FxHashMap::<u64, Vec<usize>>::with_capacity_and_hasher(
self.len(),
Default::default(),
);
for (row, &key) in src_keys.iter().enumerate() {
positions.entry(key).or_default().push(row);
}
let mut indexer = Vec::new();
let mut missing = Vec::new();
for (target_row, &key) in tgt_keys.iter().enumerate() {
if let Some(matches) = positions.get(&key) {
indexer.extend(matches.iter().map(|&pos| pos as isize));
} else {
indexer.push(-1);
missing.push(target_row);
}
}
return (indexer, missing);
}
let mut positions = FxHashMap::<Vec<IndexLabel>, Vec<usize>>::with_capacity_and_hasher(
self.len(),
Default::default(),
);
for row in 0..self.len() {
let key: Vec<IndexLabel> = self.levels.iter().map(|level| level[row].clone()).collect();
positions.entry(key).or_default().push(row);
}
let mut indexer = Vec::new();
let mut missing = Vec::new();
for target_row in 0..target.len() {
let key: Vec<IndexLabel> = target
.levels
.iter()
.map(|level| level[target_row].clone())
.collect();
if let Some(matches) = positions.get(&key) {
indexer.extend(matches.iter().map(|&pos| pos as isize));
} else {
indexer.push(-1);
missing.push(target_row);
}
}
(indexer, missing)
}
/// Compute a positional indexer against another MultiIndex.
///
/// Matches `pd.MultiIndex.get_indexer(target)` for unique source indexes:
/// each target tuple maps to its first source position, and missing target
/// tuples map to `-1`. Duplicate source tuples are rejected because pandas
/// treats reindexing from a non-unique index as invalid; callers that want
/// duplicate expansion should use [`Self::get_indexer_for`] or
/// [`Self::get_indexer_non_unique`].
pub fn get_indexer(&self, target: &Self) -> Result<Vec<isize>, IndexError> {
if self.has_duplicates() {
return Err(IndexError::InvalidArgument(
"get_indexer requires a uniquely valued MultiIndex".to_owned(),
));
}
if self.nlevels() != target.nlevels() {
return Ok(vec![-1; target.len()]);
}
if let Some((src_keys, tgt_keys)) = self.factorize_packed_keys(target) {
let mut positions =
FxHashMap::<u64, isize>::with_capacity_and_hasher(self.len(), Default::default());
for (row, &key) in src_keys.iter().enumerate() {
positions
.entry(key)
.or_insert(isize::try_from(row).unwrap_or(isize::MAX));
}
return Ok(tgt_keys
.iter()
.map(|key| positions.get(key).copied().unwrap_or(-1))
.collect());
}
let mut positions = FxHashMap::<Vec<IndexLabel>, isize>::with_capacity_and_hasher(
self.len(),
Default::default(),
);
for row in 0..self.len() {
positions
.entry(self.tuple_at(row))
.or_insert(isize::try_from(row).unwrap_or(isize::MAX));
}
Ok((0..target.len())
.map(|target_row| {
let key = target.tuple_at(target_row);
positions.get(&key).copied().unwrap_or(-1)
})
.collect())
}
/// Compute a positional indexer, expanding duplicate source matches.
///
/// Matches `pd.MultiIndex.get_indexer_for(target)`: unique source indexes
/// use the compact one-position-per-target form, while non-unique source
/// indexes expand every matching source position for each target tuple.
pub fn get_indexer_for(&self, target: &Self) -> Result<Vec<isize>, IndexError> {
if self.has_duplicates() {
Ok(self.get_indexer_non_unique(target).0)
} else {
self.get_indexer(target)
}
}
/// Reindex to a target MultiIndex, returning the target and source positions.
///
/// Matches `pd.MultiIndex.reindex(target)` for unique source indexes:
/// the returned index is the requested target, and the indexer maps each
/// target tuple to its source position or `-1` for missing tuples.
pub fn reindex(&self, target: &Self) -> Result<(Self, Vec<isize>), IndexError> {
Ok((target.clone(), self.get_indexer(target)?))
}
/// Per-row flag for duplicated composite tuples.
///
/// Matches `pd.MultiIndex.duplicated(keep='first'|'last'|False)`.
/// - `DuplicateKeep::First` marks all but the first occurrence of each
/// tuple as duplicated (pandas default).
/// - `DuplicateKeep::Last` marks all but the last occurrence.
/// - `DuplicateKeep::None` marks every occurrence of any tuple that
/// appears more than once.
#[must_use]
pub fn duplicated(&self, keep: DuplicateKeep) -> Vec<bool> {
let len = self.len();
let mut out = vec![false; len];
if len == 0 {
return out;
}
if let Some(layout) = self.compact_two_level_identity_layout() {
match keep {
DuplicateKeep::First => {
let mut seen = vec![0_u8; layout.slot_count];
for (row, slot) in out.iter_mut().enumerate() {
let key = layout.slot(row);
if seen[key] == 0 {
seen[key] = 1;
} else {
*slot = true;
}
}
}
DuplicateKeep::Last => {
let mut seen = vec![0_u8; layout.slot_count];
for row in (0..len).rev() {
let key = layout.slot(row);
if seen[key] == 0 {
seen[key] = 1;
} else {
out[row] = true;
}
}
}
DuplicateKeep::None => {
let mut counts = vec![0_usize; layout.slot_count];
for row in 0..len {
counts[layout.slot(row)] += 1;
}
for (row, slot) in out.iter_mut().enumerate() {
if counts[layout.slot(row)] > 1 {
*slot = true;
}
}
}
}
return out;
}
// Materialize each row's composite key exactly once per pass. The prior
// version built BOTH a counts and a first_seen map for every keep mode
// (incl. a key.clone()) and then rebuilt the key again in the keep-mode
// loop — 3-4 Vec<IndexLabel> allocations per row. Each mode now does the
// minimal work; output is positional so marking order is irrelevant.
// Packed-key fast path (br-frankenpandas-midedup): one u64 per row keyed
// on tuple identity, so dedup hashes integers instead of allocating (and
// Utf8-cloning) a Vec<IndexLabel> per row. Bijective on identity ⇒ the
// dup mask is identical to the Vec-key path.
if let Some(keys) = self.identity_packed_keys() {
match keep {
DuplicateKeep::First => {
let mut seen: FxHashSet<u64> =
FxHashSet::with_capacity_and_hasher(len, Default::default());
for (row, slot) in out.iter_mut().enumerate() {
if !seen.insert(keys[row]) {
*slot = true;
}
}
}
DuplicateKeep::Last => {
let mut seen: FxHashSet<u64> =
FxHashSet::with_capacity_and_hasher(len, Default::default());
for row in (0..len).rev() {
if !seen.insert(keys[row]) {
out[row] = true;
}
}
}
DuplicateKeep::None => {
let mut counts: FxHashMap<u64, usize> =
FxHashMap::with_capacity_and_hasher(len, Default::default());
for &key in &keys {
*counts.entry(key).or_insert(0) += 1;
}
for (row, slot) in out.iter_mut().enumerate() {
if counts[&keys[row]] > 1 {
*slot = true;
}
}
}
}
return out;
}
let key_at = |row: usize| -> Vec<IndexLabel> {
self.levels.iter().map(|level| level[row].clone()).collect()
};
match keep {
DuplicateKeep::First => {
// First occurrence kept; a key already seen earlier is a dup.
let mut seen: FxHashSet<Vec<IndexLabel>> =
FxHashSet::with_capacity_and_hasher(len, Default::default());
for (row, slot) in out.iter_mut().enumerate() {
if !seen.insert(key_at(row)) {
*slot = true;
}
}
}
DuplicateKeep::Last => {
// Last occurrence kept; scanning in reverse, the first key seen
// in reverse is the last forward occurrence (kept = false).
let mut seen: FxHashSet<Vec<IndexLabel>> =
FxHashSet::with_capacity_and_hasher(len, Default::default());
for row in (0..len).rev() {
if !seen.insert(key_at(row)) {
out[row] = true;
}
}
}
DuplicateKeep::None => {
// Every occurrence of a key with count > 1 is a dup.
let mut counts: FxHashMap<Vec<IndexLabel>, usize> =
FxHashMap::with_capacity_and_hasher(len, Default::default());
for row in 0..len {
*counts.entry(key_at(row)).or_insert(0) += 1;
}
for (row, slot) in out.iter_mut().enumerate() {
if counts[&key_at(row)] > 1 {
*slot = true;
}
}
}
}
out
}
/// Whether all composite tuples are unique.
///
/// Matches `pd.MultiIndex.is_unique`.
#[must_use]
pub fn is_unique(&self) -> bool {
let len = self.len();
if len <= 1 {
return true;
}
if let Some(layout) = self.compact_two_level_identity_layout() {
let mut seen = vec![0_u8; layout.slot_count];
for row in 0..len {
let key = layout.slot(row);
if seen[key] != 0 {
return false;
}
seen[key] = 1;
}
return true;
}
if let Some(keys) = self.identity_packed_keys() {
let mut seen: FxHashSet<u64> =
FxHashSet::with_capacity_and_hasher(len, Default::default());
return keys.into_iter().all(|key| seen.insert(key));
}
let mut seen: FxHashSet<Vec<IndexLabel>> =
FxHashSet::with_capacity_and_hasher(len, Default::default());
(0..len).all(|row| seen.insert(self.tuple_at(row)))
}
/// Whether any composite tuple appears more than once.
///
/// Matches `pd.MultiIndex.has_duplicates`.
#[must_use]
pub fn has_duplicates(&self) -> bool {
!self.is_unique()
}
/// Drop duplicated tuples with pandas' default `keep='first'`.
#[must_use]
pub fn drop_duplicates(&self) -> Self {
self.drop_duplicates_keep(DuplicateKeep::First)
}
/// Drop duplicated tuples with explicit keep behavior.
#[must_use]
pub fn drop_duplicates_keep(&self, keep: DuplicateKeep) -> Self {
if keep == DuplicateKeep::First
&& let Some(layout) = self.compact_two_level_identity_layout()
{
let mut seen = vec![0_u8; layout.slot_count];
let mut positions = Vec::with_capacity(layout.slot_count.min(self.len()));
for row in 0..self.len() {
let key = layout.slot(row);
if seen[key] == 0 {
seen[key] = 1;
positions.push(row);
}
}
return self.take_existing_positions(&positions);
}
let duplicated = self.duplicated(keep);
let positions: Vec<usize> = duplicated
.iter()
.enumerate()
.filter_map(|(position, is_duplicated)| (!is_duplicated).then_some(position))
.collect();
self.take_existing_positions(&positions)
}
/// Unique tuples, preserving first-seen order.
#[must_use]
pub fn unique(&self) -> Self {
self.drop_duplicates_keep(DuplicateKeep::First)
}
/// Number of unique tuples.
#[must_use]
pub fn nunique(&self) -> usize {
let len = self.len();
if len == 0 {
return 0;
}
if let Some(layout) = self.compact_two_level_identity_layout() {
let mut seen = vec![0_u8; layout.slot_count];
let mut count = 0usize;
for row in 0..len {
let key = layout.slot(row);
if seen[key] == 0 {
seen[key] = 1;
count += 1;
}
}
return count;
}
if let Some(keys) = self.identity_packed_keys() {
let mut seen: FxHashSet<u64> =
FxHashSet::with_capacity_and_hasher(len, Default::default());
for key in keys {
seen.insert(key);
}
return seen.len();
}
let mut seen: FxHashSet<Vec<IndexLabel>> =
FxHashSet::with_capacity_and_hasher(len, Default::default());
for row in 0..len {
seen.insert(self.tuple_at(row));
}
seen.len()
}
/// Unsupported boolean reduction, matching `pd.MultiIndex.all()`.
pub fn all(&self) -> Result<bool, IndexError> {
Err(IndexError::InvalidArgument(
"cannot perform all with this index type: MultiIndex".to_owned(),
))
}
/// Unsupported boolean reduction, matching `pd.MultiIndex.any()`.
pub fn any(&self) -> Result<bool, IndexError> {
Err(IndexError::InvalidArgument(
"cannot perform any with this index type: MultiIndex".to_owned(),
))
}
/// Factorize tuples into integer codes and unique tuples.
///
/// Missing labels remain part of the composite tuple identity, matching
/// pandas' MultiIndex-level factorization behavior.
#[must_use]
pub fn factorize(&self) -> (Vec<isize>, Self) {
let mut positions: FxHashMap<Vec<IndexLabel>, isize> =
FxHashMap::with_capacity_and_hasher(self.len(), Default::default());
let mut uniques = Vec::<Vec<IndexLabel>>::new();
let mut codes = Vec::with_capacity(self.len());
for tuple in self.to_list() {
if let Some(code) = positions.get(&tuple) {
codes.push(*code);
} else {
let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
positions.insert(tuple.clone(), code);
uniques.push(tuple);
codes.push(code);
}
}
let mut levels: Vec<Vec<IndexLabel>> = (0..self.nlevels())
.map(|_| Vec::with_capacity(uniques.len()))
.collect();
for tuple in uniques {
for (level_idx, label) in tuple.into_iter().enumerate() {
levels[level_idx].push(label);
}
}
let unique_index = Self::from_levels_and_names(levels, self.names.clone());
(codes, unique_index)
}
/// Count unique tuple occurrences, sorted by count descending then tuple.
#[must_use]
pub fn value_counts(&self) -> Vec<(Vec<IndexLabel>, usize)> {
if let Some(layout) = self.compact_two_level_identity_layout() {
let mut counts = vec![0usize; layout.slot_count];
let mut first_rows = vec![usize::MAX; layout.slot_count];
let mut unique_count = 0usize;
for row in 0..self.len() {
let slot = layout.slot(row);
if counts[slot] == 0 {
first_rows[slot] = row;
unique_count += 1;
}
counts[slot] += 1;
}
let mut pairs = Vec::with_capacity(unique_count);
for (slot, count) in counts.into_iter().enumerate() {
if count != 0 {
pairs.push((self.tuple_at(first_rows[slot]), count));
}
}
pairs.sort_by(|(left_tuple, left_count), (right_tuple, right_count)| {
right_count
.cmp(left_count)
.then_with(|| left_tuple.cmp(right_tuple))
});
return pairs;
}
let mut counts: FxHashMap<Vec<IndexLabel>, usize> =
FxHashMap::with_capacity_and_hasher(self.len(), Default::default());
for tuple in self.to_list() {
*counts.entry(tuple).or_insert(0) += 1;
}
let mut pairs: Vec<(Vec<IndexLabel>, usize)> = counts.into_iter().collect();
pairs.sort_by(|(left_tuple, left_count), (right_tuple, right_count)| {
right_count
.cmp(left_count)
.then_with(|| left_tuple.cmp(right_tuple))
});
pairs
}
/// Positional sorter for lexicographic tuple order.
#[must_use]
pub fn argsort(&self) -> Vec<usize> {
let mut order: Vec<usize> = (0..self.len()).collect();
// Packed-key fast path: sort on one u64 per row (ascending u64 order ==
// lexicographic row_cmp order) instead of comparing (Utf8) tuples. The
// `.then(left.cmp(right))` original-position tiebreak is preserved, so
// the permutation is identical to the tuple-comparison sort.
if let Some(keys) = self.sorted_packed_keys() {
order.sort_by(|&left, &right| {
keys[left].cmp(&keys[right]).then_with(|| left.cmp(&right))
});
return order;
}
order.sort_by(|&left, &right| self.row_cmp(left, right).then_with(|| left.cmp(&right)));
order
}
/// Sort tuples lexicographically, matching `pd.MultiIndex.sort_values()`.
#[must_use]
pub fn sort_values(&self) -> Self {
self.take_existing_positions(&self.argsort())
}
/// Alias for `sort_values`, matching `pd.MultiIndex.sort`.
#[must_use]
pub fn sort(&self) -> Self {
self.sort_values()
}
/// Sort tuples and return the positional indexer used for the sort.
#[must_use]
pub fn sortlevel(&self) -> (Self, Vec<usize>) {
let order = self.argsort();
(self.take_existing_positions(&order), order)
}
/// Lexicographic minimum tuple.
#[must_use]
pub fn min(&self) -> Option<Vec<IndexLabel>> {
self.argsort()
.first()
.map(|&position| self.tuple_at(position))
}
/// Lexicographic maximum tuple.
#[must_use]
pub fn max(&self) -> Option<Vec<IndexLabel>> {
self.argsort()
.last()
.map(|&position| self.tuple_at(position))
}
/// Position of the maximum tuple.
#[must_use]
pub fn argmax(&self) -> Option<usize> {
self.argsort().last().copied()
}
/// Position of the minimum tuple.
#[must_use]
pub fn argmin(&self) -> Option<usize> {
self.argsort().first().copied()
}
/// Append another MultiIndex to this one.
///
/// Matches `pd.MultiIndex.append(other)` for equal-level indexes.
pub fn append(&self, other: &Self) -> Result<Self, IndexError> {
self.ensure_same_nlevels(other)?;
let mut levels = Vec::with_capacity(self.nlevels());
for level_idx in 0..self.nlevels() {
let mut level = self.levels[level_idx].clone();
level.extend(other.levels[level_idx].iter().cloned());
levels.push(level);
}
Ok(Self::from_levels_and_names(
levels,
self.shared_names(other),
))
}
/// Repeat each tuple `repeats` times, matching `pd.MultiIndex.repeat`.
#[must_use]
pub fn repeat(&self, repeats: usize) -> Self {
if repeats == 1 {
return self.clone();
}
let mut levels = Vec::with_capacity(self.nlevels());
for level in &self.levels {
let mut repeated = Vec::with_capacity(repeat_output_capacity(level.len(), repeats));
for label in level {
for _ in 0..repeats {
repeated.push(label.clone());
}
}
levels.push(repeated);
}
Self::from_levels_and_names(levels, self.names.clone())
}
/// Drop tuples containing any missing level label.
///
/// Matches `pd.MultiIndex.dropna(how='any')`, which is pandas' default.
#[must_use]
pub fn dropna(&self) -> Self {
self.dropna_any()
}
/// Drop tuples containing any missing level label.
#[must_use]
pub fn dropna_any(&self) -> Self {
let positions: Vec<usize> = (0..self.len())
.filter(|&row| self.levels.iter().all(|level| !level[row].is_missing()))
.collect();
self.take_existing_positions(&positions)
}
/// Drop tuples whose level labels are all missing.
#[must_use]
pub fn dropna_all(&self) -> Self {
let positions: Vec<usize> = (0..self.len())
.filter(|&row| !self.levels.iter().all(|level| level[row].is_missing()))
.collect();
self.take_existing_positions(&positions)
}
/// Tuple intersection preserving left order and de-duplicating results.
pub fn intersection(&self, other: &Self) -> Result<Self, IndexError> {
self.ensure_same_nlevels(other)?;
if let Some((self_levels, other_levels)) = self.two_utf8_level_slices(other) {
let mut other_set = FxHashSet::<(&str, &str)>::default();
for row in 0..other.len() {
other_set.insert(Self::utf8_pair_at(other_levels, row));
}
let mut seen = FxHashSet::<(&str, &str)>::default();
let mut pairs = Vec::new();
for row in 0..self.len() {
let key = Self::utf8_pair_at(self_levels, row);
if other_set.contains(&key) && seen.insert(key) {
pairs.push(key);
if seen.len() == other_set.len() {
break;
}
}
}
return Ok(Self::two_utf8_result_from_pairs(
pairs,
self.shared_names(other),
));
}
// Packed-key fast path (br-frankenpandas-misetop): identity-coded u64 per
// row instead of to_list() (per-row Vec<IndexLabel> + Utf8 clone) and a
// SipHash HashMap<Vec<IndexLabel>>. Keep self rows whose key is in other,
// deduped first-seen, then gather those positions. Bijective on tuple
// identity ⇒ same kept rows, same order.
if let Some((self_keys, other_keys)) = self.factorize_packed_keys(other) {
let other_set: FxHashSet<u64> = other_keys.into_iter().collect();
let mut seen: FxHashSet<u64> =
FxHashSet::with_capacity_and_hasher(self_keys.len(), Default::default());
let positions: Vec<usize> = self_keys
.iter()
.enumerate()
.filter_map(|(i, &k)| (other_set.contains(&k) && seen.insert(k)).then_some(i))
.collect();
return Ok(self
.take_existing_positions(&positions)
.set_names(self.shared_names(other)));
}
let other_keys: FxHashSet<Vec<IndexLabel>> = other.to_list().into_iter().collect();
let mut seen =
FxHashSet::<Vec<IndexLabel>>::with_capacity_and_hasher(self.len(), Default::default());
let tuples = self
.to_list()
.into_iter()
.filter(|tuple| other_keys.contains(tuple) && seen.insert(tuple.clone()))
.collect();
Self::from_tuples_with_names(tuples, self.shared_names(other))
}
/// Tuple union preserving first-seen order from `self` then `other`.
pub fn union(&self, other: &Self) -> Result<Self, IndexError> {
self.ensure_same_nlevels(other)?;
if let Some((self_levels, other_levels)) = self.two_utf8_level_slices(other) {
let mut seen = FxHashSet::<(&str, &str)>::default();
let mut pairs = Vec::new();
for (levels, len) in [(self_levels, self.len()), (other_levels, other.len())] {
for row in 0..len {
let key = Self::utf8_pair_at(levels, row);
if seen.insert(key) {
pairs.push(key);
}
}
}
return Ok(Self::two_utf8_result_from_pairs(
pairs,
self.shared_names(other),
));
}
// General typed composite path: pack the dictionary-coded level columns
// into one key and gather rows column-by-column. This preserves the
// left-first outer-union order without allocating a `Vec<IndexLabel>`
// tuple (or cloning its labels merely to hash it) for every row.
if let Some((self_keys, other_keys)) = self.factorize_packed_keys(other) {
let mut seen: FxHashSet<u64> = FxHashSet::with_capacity_and_hasher(
self.len().saturating_add(other.len()),
Default::default(),
);
let mut levels: Vec<Vec<IndexLabel>> = self
.levels
.iter()
.map(|_| Vec::with_capacity(self.len().saturating_add(other.len())))
.collect();
for (keys, source) in [(&self_keys, self), (&other_keys, other)] {
for (row, &key) in keys.iter().enumerate() {
if seen.insert(key) {
for (out, level) in levels.iter_mut().zip(&source.levels) {
out.push(level[row].clone());
}
}
}
}
return Ok(Self::from_levels_and_names(
levels,
self.shared_names(other),
));
}
let mut seen = FxHashSet::<Vec<IndexLabel>>::with_capacity_and_hasher(
combined_output_capacity(self.len(), other.len()),
Default::default(),
);
let mut tuples = Vec::with_capacity(combined_output_capacity(self.len(), other.len()));
for tuple in self.to_list().into_iter().chain(other.to_list()) {
if seen.insert(tuple.clone()) {
tuples.push(tuple);
}
}
Self::from_tuples_with_names(tuples, self.shared_names(other))
}
/// Alias for `union`, matching the flat `Index::union_with` naming.
pub fn union_with(&self, other: &Self) -> Result<Self, IndexError> {
self.union(other)
}
/// Tuple difference preserving left order and de-duplicating results.
pub fn difference(&self, other: &Self) -> Result<Self, IndexError> {
self.ensure_same_nlevels(other)?;
if let Some((self_levels, other_levels)) = self.two_utf8_level_slices(other) {
let mut other_set = FxHashSet::<(&str, &str)>::default();
for row in 0..other.len() {
other_set.insert(Self::utf8_pair_at(other_levels, row));
}
let mut seen = FxHashSet::<(&str, &str)>::default();
let mut pairs = Vec::new();
for row in 0..self.len() {
let key = Self::utf8_pair_at(self_levels, row);
if !other_set.contains(&key) && seen.insert(key) {
pairs.push(key);
}
}
return Ok(Self::two_utf8_result_from_pairs(
pairs,
self.shared_names(other),
));
}
// Packed-key fast path (br-frankenpandas-misetop): keep self rows whose
// key is NOT in other, deduped first-seen. See intersection.
if let Some((self_keys, other_keys)) = self.factorize_packed_keys(other) {
let other_set: FxHashSet<u64> = other_keys.into_iter().collect();
let mut seen: FxHashSet<u64> =
FxHashSet::with_capacity_and_hasher(self_keys.len(), Default::default());
let positions: Vec<usize> = self_keys
.iter()
.enumerate()
.filter_map(|(i, &k)| (!other_set.contains(&k) && seen.insert(k)).then_some(i))
.collect();
return Ok(self
.take_existing_positions(&positions)
.set_names(self.shared_names(other)));
}
let other_keys: FxHashSet<Vec<IndexLabel>> = other.to_list().into_iter().collect();
let mut seen =
FxHashSet::<Vec<IndexLabel>>::with_capacity_and_hasher(self.len(), Default::default());
let tuples = self
.to_list()
.into_iter()
.filter(|tuple| !other_keys.contains(tuple) && seen.insert(tuple.clone()))
.collect();
Self::from_tuples_with_names(tuples, self.shared_names(other))
}
/// Tuple symmetric difference preserving first-seen order.
pub fn symmetric_difference(&self, other: &Self) -> Result<Self, IndexError> {
self.ensure_same_nlevels(other)?;
if let Some((self_levels, other_levels)) = self.two_utf8_level_slices(other) {
let mut self_set = FxHashSet::<(&str, &str)>::default();
for row in 0..self.len() {
self_set.insert(Self::utf8_pair_at(self_levels, row));
}
let mut other_set = FxHashSet::<(&str, &str)>::default();
for row in 0..other.len() {
other_set.insert(Self::utf8_pair_at(other_levels, row));
}
let mut seen = FxHashSet::<(&str, &str)>::default();
let mut pairs = Vec::new();
for row in 0..self.len() {
let key = Self::utf8_pair_at(self_levels, row);
if !other_set.contains(&key) && seen.insert(key) {
pairs.push(key);
}
}
for row in 0..other.len() {
let key = Self::utf8_pair_at(other_levels, row);
if !self_set.contains(&key) && seen.insert(key) {
pairs.push(key);
}
}
return Ok(Self::two_utf8_result_from_pairs(
pairs,
self.shared_names(other),
));
}
let self_keys: FxHashSet<Vec<IndexLabel>> = self.to_list().into_iter().collect();
let other_keys: FxHashSet<Vec<IndexLabel>> = other.to_list().into_iter().collect();
let mut seen = FxHashSet::<Vec<IndexLabel>>::with_capacity_and_hasher(
combined_output_capacity(self.len(), other.len()),
Default::default(),
);
let mut tuples = Vec::new();
for tuple in self.to_list() {
if !other_keys.contains(&tuple) && seen.insert(tuple.clone()) {
tuples.push(tuple);
}
}
for tuple in other.to_list() {
if !self_keys.contains(&tuple) && seen.insert(tuple.clone()) {
tuples.push(tuple);
}
}
Self::from_tuples_with_names(tuples, self.shared_names(other))
}
/// Group tuple positions by composite key, matching `pd.MultiIndex.groupby`.
#[must_use]
pub fn groupby(&self) -> HashMap<Vec<IndexLabel>, Vec<usize>> {
let mut groups = HashMap::<Vec<IndexLabel>, Vec<usize>>::new();
for row in 0..self.len() {
groups.entry(self.tuple_at(row)).or_default().push(row);
}
groups
}
/// Join two MultiIndexes using pandas-style join modes.
pub fn join(&self, other: &Self, how: &str) -> Result<Self, IndexError> {
match how {
"left" => Ok(self.clone()),
"right" => Ok(other.clone()),
"inner" => self.intersection(other),
"outer" => self.union(other),
other => Err(IndexError::InvalidArgument(format!(
"join: how must be 'left', 'right', 'inner', or 'outer', got {other:?}"
))),
}
}
/// Per-row membership test against a set of tuples.
///
/// Matches `pd.MultiIndex.isin(values)`. Each entry in the returned
/// bool vector is `true` iff that row's composite tuple appears in
/// `values`. Tuples whose length does not match the MultiIndex's
/// number of levels never match (silently contribute `false`),
/// matching pandas' lenient behavior.
#[must_use]
pub fn isin(&self, values: &[Vec<IndexLabel>]) -> Vec<bool> {
let nlevels = self.nlevels();
let lookup: FxHashSet<&Vec<IndexLabel>> =
values.iter().filter(|v| v.len() == nlevels).collect();
if lookup.is_empty() {
return vec![false; self.len()];
}
// Reuse one key buffer across rows: clear + extend refills the composite
// lookup key in place, so membership is tested without allocating a fresh
// Vec<IndexLabel> per row. Result is identical (value-based membership,
// positional bool output).
let mut key: Vec<IndexLabel> = Vec::with_capacity(nlevels);
let mut out = Vec::with_capacity(self.len());
for row in 0..self.len() {
key.clear();
key.extend(self.levels.iter().map(|level| level[row].clone()));
out.push(lookup.contains(&key));
}
out
}
/// Per-row membership test against values for a single level.
///
/// Matches `pd.MultiIndex.isin(values, level=...)`. Returns `true`
/// for positions whose label at `level` is in `values`. Returns an
/// `OutOfBounds` error when `level` exceeds `nlevels()`.
pub fn isin_level(&self, values: &[IndexLabel], level: usize) -> Result<Vec<bool>, IndexError> {
if level >= self.nlevels() {
return Err(IndexError::OutOfBounds {
position: level,
length: self.nlevels(),
});
}
let lookup: FxHashSet<&IndexLabel> = values.iter().collect();
Ok(self.levels[level]
.iter()
.map(|label| lookup.contains(label))
.collect())
}
/// Construct a MultiIndex from tuples of labels.
///
/// Matches `pd.MultiIndex.from_tuples(tuples)`.
/// Each inner Vec represents one row's labels across all levels.
pub fn from_tuples(tuples: Vec<Vec<IndexLabel>>) -> Result<Self, IndexError> {
if tuples.is_empty() {
return Ok(Self::from_levels_and_names(Vec::new(), Vec::new()));
}
let nlevels = tuples[0].len();
for (i, t) in tuples.iter().enumerate() {
if t.len() != nlevels {
return Err(IndexError::LengthMismatch {
expected: nlevels,
actual: t.len(),
context: format!("tuple at position {i} has wrong number of levels"),
});
}
}
let mut levels: Vec<Vec<IndexLabel>> = (0..nlevels)
.map(|_| Vec::with_capacity(tuples.len()))
.collect();
for tuple in &tuples {
for (level_idx, label) in tuple.iter().enumerate() {
levels[level_idx].push(label.clone());
}
}
Ok(Self::from_levels_and_names(levels, vec![None; nlevels]))
}
/// Construct a MultiIndex from parallel arrays (one per level).
///
/// Matches `pd.MultiIndex.from_arrays(arrays)`.
pub fn from_arrays(arrays: Vec<Vec<IndexLabel>>) -> Result<Self, IndexError> {
if arrays.is_empty() {
return Ok(Self::from_levels_and_names(Vec::new(), Vec::new()));
}
let expected_len = arrays[0].len();
for (i, arr) in arrays.iter().enumerate() {
if arr.len() != expected_len {
return Err(IndexError::LengthMismatch {
expected: expected_len,
actual: arr.len(),
context: format!("level {i} array length mismatch"),
});
}
}
let nlevels = arrays.len();
Ok(Self::from_levels_and_names(arrays, vec![None; nlevels]))
}
/// Construct a MultiIndex from frame-like columns.
///
/// Matches `pd.MultiIndex.from_frame(frame)` at the payload level:
/// each input entry is one frame column, with the optional column name
/// becoming the corresponding level name.
pub fn from_frame(columns: Vec<(Option<String>, Vec<IndexLabel>)>) -> Result<Self, IndexError> {
if columns.is_empty() {
return Ok(Self::from_levels_and_names(Vec::new(), Vec::new()));
}
let expected_len = columns[0].1.len();
for (column_idx, (_, values)) in columns.iter().enumerate() {
if values.len() != expected_len {
return Err(IndexError::LengthMismatch {
expected: expected_len,
actual: values.len(),
context: format!("from_frame column {column_idx} length mismatch"),
});
}
}
let mut names = Vec::with_capacity(columns.len());
let mut levels = Vec::with_capacity(columns.len());
for (name, values) in columns {
names.push(name.map(LabelName::from));
levels.push(values);
}
Ok(Self::from_levels_and_names(levels, names))
}
/// Construct a MultiIndex from the Cartesian product of iterables.
///
/// Matches `pd.MultiIndex.from_product(iterables)`.
pub fn from_product(iterables: Vec<Vec<IndexLabel>>) -> Result<Self, IndexError> {
if iterables.is_empty() {
return Ok(Self::from_levels_and_names(Vec::new(), Vec::new()));
}
// Compute total size of the Cartesian product.
let total = checked_cartesian_product_len(iterables.iter().map(Vec::len))?;
if total == 0 {
let nlevels = iterables.len();
return Ok(Self::from_levels_and_names(
(0..nlevels).map(|_| Vec::new()).collect(),
vec![None; nlevels],
));
}
let nlevels = iterables.len();
let mut levels: Vec<Vec<IndexLabel>> =
(0..nlevels).map(|_| Vec::with_capacity(total)).collect();
// Generate Cartesian product: for each position, compute which
// element from each level by dividing position by the product of
// all subsequent level lengths.
for pos in 0..total {
let mut remaining = pos;
for (level_idx, iterable) in iterables.iter().enumerate().rev() {
let idx_in_level = remaining % iterable.len();
remaining /= iterable.len();
levels[level_idx].push(iterable[idx_in_level].clone());
}
}
Ok(Self::from_levels_and_names(levels, vec![None; nlevels]))
}
/// Flatten this MultiIndex into a single-level Index by joining
/// level labels with a separator.
///
/// Matches `pd.MultiIndex.to_flat_index()` (approximately).
#[must_use]
pub fn to_flat_index(&self, sep: &str) -> Index {
use std::fmt::Write as _;
let n = self.len();
// Contiguous-Utf8 flat index (br-frankenpandas-flatidx-contig): the old form
// built n separate `IndexLabel::Utf8(String)` — one heap allocation per row —
// then `Index::new(Vec<IndexLabel>)`. This is the reshape MultiIndex floor hit
// by wide_to_long / stack / unstack / set_index_multi, and it is built eagerly
// even though the row MultiIndex is stored alongside. Instead write ALL n
// composite labels into ONE growing String buffer, recording byte offsets, and
// hand the buffer + offsets to the lazy contiguous-Utf8 Index backing (nbspq):
// one big allocation instead of n small ones, no per-row IndexLabel box, no
// per-row `Vec<String>` + `join`. Semantically identical — the backing
// materializes the same `IndexLabel::Utf8` labels on demand (same bytes:
// `write!("{}", level[i])` == `level[i].to_string()`, `sep` between levels ==
// `parts.join(sep)`), so labels(), lookups, and duplicate detection are unchanged.
// The n composite-label bytes are independent per row and the assembly is
// CPU-bound (per-row `write!` formatting + `push_str`, not raw bandwidth), so
// build it in PARALLEL — each worker fills its own local byte buffer + relative
// offsets for a contiguous row range, then the chunks are concatenated in row
// order with offsets shifted by the running byte base. Bit-identical to the
// serial build. This is the reshape MultiIndex floor hit by wide_to_long / stack
// / unstack / set_index_multi; CPU-bound per-thread-buffer parallelism scales
// even on a loaded box (no shared-allocator/bandwidth contention).
let levels = &self.levels;
// The per-level `write!(buf, "{}", level[i])` above was the LAST piece of
// `core::fmt` left inside this already-parallel, already-contiguous build:
// an `IndexLabel` Display + `Formatter::pad` dispatch per LEVEL per ROW,
// and this loop does no other work. Dispatch straight off the variant
// instead. BIT-IDENTICAL by construction against `impl Display for
// IndexLabel`: `Int64(v) => write!(f, "{v}")` is plain decimal, which is
// exactly `push_i64_decimal`; `Utf8(v) => write!(f, "{v}")` is exactly the
// string's bytes. Every other variant (Float64 "%.1f"-style ".0" fixup,
// Bool "True"/"False", Null, temporal) keeps the verbatim Display path
// through a REUSED scratch String, which also drops that variant's per-row
// allocation. Same bytes, same offsets, same order.
let build = |lo: usize, hi: usize| -> (Vec<u8>, Vec<usize>) {
let mut buf: Vec<u8> = Vec::new();
let mut offs: Vec<usize> = Vec::with_capacity(hi - lo);
let mut scratch = String::new();
for i in lo..hi {
for (li, level) in levels.iter().enumerate() {
if li > 0 {
buf.extend_from_slice(sep.as_bytes());
}
match &level[i] {
IndexLabel::Int64(v) => push_i64_decimal(&mut buf, *v),
IndexLabel::Utf8(s) => buf.extend_from_slice(s.as_bytes()),
other => {
scratch.clear();
let _ = write!(scratch, "{other}");
buf.extend_from_slice(scratch.as_bytes());
}
}
}
offs.push(buf.len());
}
(buf, offs)
};
const FLATIDX_PAR_MIN_ROWS: usize = 50_000;
const FLATIDX_PAR_MIN_PER_WORKER: usize = 16_384;
let workers = if n >= FLATIDX_PAR_MIN_ROWS {
cached_available_parallelism()
.min(16)
.min(n / FLATIDX_PAR_MIN_PER_WORKER)
.max(1)
} else {
1
};
let (bytes, offsets): (Vec<u8>, Vec<usize>) = if workers >= 2 {
let chunk = n.div_ceil(workers);
let build = &build;
let parts: Vec<(Vec<u8>, Vec<usize>)> = std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(workers);
let mut start = 0;
while start < n {
let end = (start + chunk).min(n);
handles.push(scope.spawn(move || build(start, end)));
start = end;
}
handles
.into_iter()
.map(|h| h.join().expect("to_flat_index thread"))
.collect()
});
let total: usize = parts.iter().map(|(b, _)| b.len()).sum();
let mut bytes = Vec::with_capacity(total);
let mut offsets = Vec::with_capacity(n + 1);
offsets.push(0);
let mut base = 0usize;
for (b, offs) in &parts {
for &o in offs {
offsets.push(base + o);
}
base += b.len();
bytes.extend_from_slice(b);
}
(bytes, offsets)
} else {
let (b, offs) = build(0, n);
let mut offsets = Vec::with_capacity(n + 1);
offsets.push(0);
offsets.extend_from_slice(&offs);
(b, offsets)
};
Index::from_utf8_contiguous(Arc::from(bytes), Arc::from(offsets))
}
/// **Bench-only ORIG reference.** Byte-for-byte the `to_flat_index` body as it
/// stood before the `core::fmt` removal (`write!(buf, "{}", level[i])` per level
/// per row), including the identical parallel/serial split and gates, so an A/B
/// isolates EXACTLY the formatting change and nothing else. Compiled only under
/// `cfg(test)`, so the shipped binary is unaffected. Kept in-tree (rather than
/// stashed or diffed against another build) because `rch exec` picks its worker
/// non-deterministically and the ORIG/CAND ratio is NOT worker-invariant: both
/// arms must live in ONE binary and alternate inside ONE invocation.
#[cfg(test)]
#[must_use]
pub(crate) fn to_flat_index_ref_write_fmt(&self, sep: &str) -> Index {
use std::fmt::Write as _;
let n = self.len();
let levels = &self.levels;
let build = |lo: usize, hi: usize| -> (Vec<u8>, Vec<usize>) {
let mut buf = String::new();
let mut offs: Vec<usize> = Vec::with_capacity(hi - lo);
for i in lo..hi {
for (li, level) in levels.iter().enumerate() {
if li > 0 {
buf.push_str(sep);
}
let _ = write!(buf, "{}", level[i]);
}
offs.push(buf.len());
}
(buf.into_bytes(), offs)
};
const FLATIDX_PAR_MIN_ROWS: usize = 50_000;
const FLATIDX_PAR_MIN_PER_WORKER: usize = 16_384;
let workers = if n >= FLATIDX_PAR_MIN_ROWS {
cached_available_parallelism()
.min(16)
.min(n / FLATIDX_PAR_MIN_PER_WORKER)
.max(1)
} else {
1
};
let (bytes, offsets): (Vec<u8>, Vec<usize>) = if workers >= 2 {
let chunk = n.div_ceil(workers);
let build = &build;
let parts: Vec<(Vec<u8>, Vec<usize>)> = std::thread::scope(|scope| {
let mut handles = Vec::with_capacity(workers);
let mut start = 0;
while start < n {
let end = (start + chunk).min(n);
handles.push(scope.spawn(move || build(start, end)));
start = end;
}
handles
.into_iter()
.map(|h| h.join().expect("to_flat_index ref thread"))
.collect()
});
let total: usize = parts.iter().map(|(b, _)| b.len()).sum();
let mut bytes = Vec::with_capacity(total);
let mut offsets = Vec::with_capacity(n + 1);
offsets.push(0);
let mut base = 0usize;
for (b, offs) in &parts {
for &o in offs {
offsets.push(base + o);
}
base += b.len();
bytes.extend_from_slice(b);
}
(bytes, offsets)
} else {
let (b, offs) = build(0, n);
let mut offsets = Vec::with_capacity(n + 1);
offsets.push(0);
offsets.extend_from_slice(&offs);
(b, offsets)
};
Index::from_utf8_contiguous(Arc::from(bytes), Arc::from(offsets))
}
/// Drop a level from this MultiIndex, returning a new MultiIndex
/// (or an Index if only one level remains).
///
/// Matches `pd.MultiIndex.droplevel(level)`.
pub fn droplevel(&self, level: usize) -> Result<MultiIndexOrIndex, IndexError> {
if level >= self.nlevels() {
return Err(IndexError::OutOfBounds {
position: level,
length: self.nlevels(),
});
}
if self.nlevels() <= 1 {
return Err(IndexError::OutOfBounds {
position: level,
length: self.nlevels(),
});
}
let mut new_levels = self.levels.clone();
new_levels.remove(level);
let mut new_names = self.names.clone();
new_names.remove(level);
if new_levels.len() == 1 {
let mut idx = Index::new(new_levels.into_iter().next().unwrap());
if let Some(ref name) = new_names[0] {
idx = idx.set_name(name);
}
Ok(MultiIndexOrIndex::Index(idx))
} else {
Ok(MultiIndexOrIndex::Multi(Self::from_levels_and_names(
new_levels, new_names,
)))
}
}
/// Swap two levels.
///
/// Matches `pd.MultiIndex.swaplevel(i, j)`.
pub fn swaplevel(&self, i: usize, j: usize) -> Result<Self, IndexError> {
if i >= self.nlevels() || j >= self.nlevels() {
return Err(IndexError::OutOfBounds {
position: i.max(j),
length: self.nlevels(),
});
}
let mut new_levels = self.levels.clone();
let mut new_names = self.names.clone();
new_levels.swap(i, j);
new_names.swap(i, j);
Ok(Self::from_levels_and_names(new_levels, new_names))
}
/// Reorder levels according to the given order.
///
/// Matches `pd.MultiIndex.reorder_levels(order)`.
/// `order` is a slice of level indices specifying the new order.
/// Must contain each level index exactly once.
pub fn reorder_levels(&self, order: &[usize]) -> Result<Self, IndexError> {
if order.len() != self.nlevels() {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: order.len(),
context: "reorder_levels: order length must match nlevels".into(),
});
}
// Validate all indices are in range and unique.
let mut seen = vec![false; self.nlevels()];
for &idx in order {
if idx >= self.nlevels() {
return Err(IndexError::OutOfBounds {
position: idx,
length: self.nlevels(),
});
}
if seen[idx] {
return Err(IndexError::LengthMismatch {
expected: self.nlevels(),
actual: order.len(),
context: format!("reorder_levels: duplicate level index {idx}"),
});
}
seen[idx] = true;
}
let new_levels: Vec<Vec<IndexLabel>> =
order.iter().map(|&idx| self.levels[idx].clone()).collect();
let new_names: Vec<Option<LabelName>> =
order.iter().map(|&idx| self.names[idx].clone()).collect();
Ok(Self::from_levels_and_names(new_levels, new_names))
}
}
/// Result of `MultiIndex::droplevel` — either a MultiIndex (if 2+ levels remain)
/// or a plain Index (if reduced to 1 level).
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq)]
pub enum MultiIndexOrIndex {
Multi(MultiIndex),
Index(Index),
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use fp_types::{Period, PeriodFreq, Scalar, Timedelta};
use crate::{Int64TwoAffineLabels, LabelKinds, OrderedF64};
#[test]
fn index_categories_ride_selection_and_refuse_outsiders_cld41() {
let text = |values: &[&str]| -> Vec<IndexLabel> {
values
.iter()
.map(|value| IndexLabel::Utf8((*value).to_owned()))
.collect()
};
let categories = super::IndexCategories {
categories: text(&["y", "x", "z"]),
ordered: true,
};
let index = Index::new(text(&["x", "y", "x"]))
.with_categories(Some(categories.clone()))
.expect("labels among the categories");
assert_eq!(index.categories(), Some(&categories));
// A selection of the labels keeps them (take, slice, clone).
assert_eq!(index.take(&[2, 0]).categories(), Some(&categories));
assert_eq!(index.slice(1, 2).categories(), Some(&categories));
assert_eq!(index.clone().categories(), Some(&categories));
// Equality ignores them, as the zone-free label comparison does.
assert_eq!(index, Index::new(text(&["x", "y", "x"])));
// NEGATIVE: a label outside the categories is refused, and a plain
// index has none.
assert!(
Index::new(text(&["x", "w"]))
.with_categories(Some(categories))
.is_err()
);
assert!(Index::new(text(&["x"])).categories().is_none());
}
#[test]
fn interval_labels_compare_hash_and_print_like_pandas_c27hq() {
use std::collections::HashSet;
use fp_types::{Interval, IntervalClosed};
let right = |left: f64, right: f64| Interval::new(left, right, IntervalClosed::Right);
let a = IndexLabel::Interval(right(0.0, 1.0));
let b = IndexLabel::Interval(right(1.0, 2.0));
// An interval is a present label, equal to itself whatever the
// endpoints' type, printed as pandas prints it.
assert!(!a.is_missing());
assert_eq!(
a,
IndexLabel::Interval(right(0.0, 1.0).with_int_endpoints())
);
assert_eq!(b.to_string(), "(1.0, 2.0]");
// Ordered by left then right endpoint, before missing labels.
let mut labels = vec![
IndexLabel::Null(fp_types::NullKind::NaN),
b.clone(),
IndexLabel::Interval(right(0.0, 2.0)),
a.clone(),
];
labels.sort();
assert_eq!(
labels,
vec![
a.clone(),
IndexLabel::Interval(right(0.0, 2.0)),
b.clone(),
IndexLabel::Null(fp_types::NullKind::NaN),
]
);
// Equal intervals hash alike (-0.0 is 0.0), so an index finds them.
let set: HashSet<IndexLabel> = [a.clone(), IndexLabel::Interval(right(-0.0, 1.0))]
.into_iter()
.collect();
assert_eq!(set.len(), 1);
let index = Index::new(vec![b.clone(), a.clone()]);
assert_eq!(index.position(&a), Some(1));
// NEGATIVE: the closed side is part of the label, and an interval is
// not its text.
assert_ne!(
a,
IndexLabel::Interval(Interval::new(0.0, 1.0, IntervalClosed::Left))
);
assert_ne!(a, IndexLabel::Utf8("(0.0, 1.0]".to_owned()));
}
#[test]
fn slice_bounds_read_decreasing_and_unsorted_like_pandas_h1kl9() {
let int = IndexLabel::Int64;
let float = |value: f64| IndexLabel::Float64(OrderedF64(value));
// A decreasing index: a held label bounds by its position, one
// between labels by the count above (left) or not below (right).
let decreasing = Index::from_i64(vec![4, 3, 2, 1]);
assert_eq!(
decreasing.slice_locs(Some(&int(2)), Some(&int(3))),
Ok((2, 2))
);
assert_eq!(
decreasing.slice_locs(Some(&float(2.5)), Some(&float(1.5))),
Ok((2, 3))
);
// A stop before the start is kept (pandas slices nothing with it).
assert_eq!(
decreasing.slice_locs(Some(&int(0)), Some(&int(5))),
Ok((4, 0))
);
// An unsorted index finds a held label; one it cannot place, or one
// held apart from one run, is pandas' KeyError.
let unsorted = Index::from_i64(vec![3, 1, 2]);
assert_eq!(
unsorted.slice_locs(Some(&int(1)), Some(&int(2))),
Ok((1, 3))
);
assert_eq!(
unsorted.get_slice_bound(&int(5), "left"),
Err(IndexError::LabelNotFound(int(5)))
);
assert_eq!(
Index::from_i64(vec![1, 2, 1]).get_slice_bound(&int(1), "left"),
Err(IndexError::KeyError(
"Cannot get left slice bound for non-unique label: 1".to_owned()
))
);
// NEGATIVE: an increasing index keeps its searchsorted bounds, a run
// of equal labels bounding by its ends, and an unknown side is an
// error.
let increasing = Index::from_i64(vec![1, 2, 2, 3]);
assert_eq!(
increasing.slice_locs(Some(&int(2)), Some(&int(2))),
Ok((1, 3))
);
assert_eq!(increasing.get_slice_bound(&float(2.5), "right"), Ok(3));
assert!(increasing.get_slice_bound(&int(2), "middle").is_err());
}
#[test]
fn unsorted_unique_int64_positions_gating_and_resolution() {
// Unsorted unique Int64 ⇒ resolves via the cached hashtable.
let idx = Index::new(vec![
IndexLabel::Int64(4),
IndexLabel::Int64(0),
IndexLabel::Int64(6),
IndexLabel::Int64(2),
]);
let got = idx
.unsorted_unique_int64_positions(&[
IndexLabel::Int64(6),
IndexLabel::Int64(4),
IndexLabel::Int64(99),
])
.expect("unsorted unique Int64 index should resolve");
assert_eq!(got, vec![Some(2), Some(0), None]);
// Sorted-ascending Int64 ⇒ None (binary-search path owns it).
let sorted = Index::new(vec![
IndexLabel::Int64(0),
IndexLabel::Int64(2),
IndexLabel::Int64(4),
]);
assert!(
sorted
.unsorted_unique_int64_positions(&[IndexLabel::Int64(2)])
.is_none()
);
// Duplicate labels ⇒ None (multimap semantics required).
let dup = Index::new(vec![
IndexLabel::Int64(5),
IndexLabel::Int64(1),
IndexLabel::Int64(5),
]);
assert!(
dup.unsorted_unique_int64_positions(&[IndexLabel::Int64(5)])
.is_none()
);
}
#[test]
fn get_indexer_unsorted_unique_utf8_matches_map_path() {
// Unsorted unique Utf8 self now routes through the cached resolver; the
// result must equal first-occurrence positions (None for absent).
let idx = Index::new(vec![
IndexLabel::Utf8("beta".to_owned()),
IndexLabel::Utf8("alpha".to_owned()),
IndexLabel::Utf8("gamma".to_owned()),
]);
let target = Index::new(vec![
IndexLabel::Utf8("gamma".to_owned()),
IndexLabel::Utf8("alpha".to_owned()),
IndexLabel::Utf8("missing".to_owned()),
IndexLabel::Utf8("beta".to_owned()),
]);
assert_eq!(
idx.get_indexer(&target),
vec![Some(2), Some(1), None, Some(0)]
);
// Duplicate self keeps first-occurrence semantics via the map fallback.
let dup = Index::new(vec![
IndexLabel::Utf8("x".to_owned()),
IndexLabel::Utf8("y".to_owned()),
IndexLabel::Utf8("x".to_owned()),
]);
let t2 = Index::new(vec![IndexLabel::Utf8("x".to_owned())]);
assert_eq!(dup.get_indexer(&t2), vec![Some(0)]);
}
use super::{
CategoricalIndex, DateOffset, DateRangeError, DatetimeIndex, Index, IndexError, IndexLabel,
Int64AffineLabels, MultiIndex, PeriodFields, PeriodIndex, RangeIndex, TimedeltaIndex,
TimedeltaRangeError, align_union, apply_date_offset, bdate_range, date_range, infer_freq,
infer_freq_from_timestamps, timedelta_range, validate_alignment_plan,
};
fn int64_labels(index: &Index) -> Vec<i64> {
index
.labels()
.iter()
.filter_map(|label| match label {
IndexLabel::Int64(value) => Some(*value),
_ => None,
})
.collect()
}
/// Regression lock for br-frankenpandas-i3t8. `Index` must stay
/// `Send + Sync` so `DataFrame` can be wrapped in `Arc` and shared
/// across reader threads. A future refactor that reintroduces
/// `std::cell::OnceCell` (or any `!Sync` interior-mutability primitive)
/// breaks this test at compile time.
#[test]
fn index_is_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Index>();
assert_send_sync::<MultiIndex>();
}
#[test]
fn bdate_range_rolls_weekend_start_forward() {
let idx = bdate_range(Some("2024-01-06"), None, Some(3), None).unwrap();
assert_eq!(
idx.labels(),
&[
IndexLabel::Datetime64(1_704_672_000_000_000_000),
IndexLabel::Datetime64(1_704_758_400_000_000_000),
IndexLabel::Datetime64(1_704_844_800_000_000_000),
]
);
}
#[test]
fn bdate_range_rolls_weekend_end_backward_and_preserves_name() {
let idx = bdate_range(None, Some("2024-01-07"), Some(3), Some("biz")).unwrap();
assert_eq!(
idx.labels(),
&[
IndexLabel::Datetime64(1_704_240_000_000_000_000),
IndexLabel::Datetime64(1_704_326_400_000_000_000),
IndexLabel::Datetime64(1_704_412_800_000_000_000),
]
);
assert_eq!(idx.name().map(|n| n.as_str()), Some("biz"));
}
#[test]
fn timedelta_range_rejects_over_specified_parameters() {
let err = timedelta_range(
Some(Timedelta::NANOS_PER_DAY),
Some(3 * Timedelta::NANOS_PER_DAY),
Some(2),
Timedelta::NANOS_PER_DAY,
None,
)
.expect_err("start + end + periods with explicit freq must fail closed");
assert!(matches!(err, TimedeltaRangeError::TooManyParams));
}
#[test]
fn timedelta_range_steps_backwards_and_away_is_empty_tzxpk() {
let day = Timedelta::NANOS_PER_DAY;
let labels = |idx: Index| idx.labels().to_vec();
// pandas: timedelta_range('5D', periods=3, freq='-1D') is 5, 4, 3 days.
assert_eq!(
labels(timedelta_range(Some(5 * day), None, Some(3), -day, None).unwrap()),
[5, 4, 3].map(|d| IndexLabel::Timedelta64(d * day))
);
// ... from end: '-1D' ending at 1 day is 3, 2, 1 days.
assert_eq!(
labels(timedelta_range(None, Some(day), Some(3), -day, None).unwrap()),
[3, 2, 1].map(|d| IndexLabel::Timedelta64(d * day))
);
// Stepping away from `end` is empty, either sign.
assert!(
timedelta_range(Some(day), Some(5 * day), None, -day, None)
.unwrap()
.is_empty()
);
assert!(
timedelta_range(Some(5 * day), Some(day), None, day, None)
.unwrap()
.is_empty()
);
// NEGATIVE: a zero step is refused.
assert!(matches!(
timedelta_range(Some(day), None, Some(2), 0, None),
Err(TimedeltaRangeError::ZeroFreq)
));
}
#[test]
fn date_range_rejects_over_specified_parameters() {
let err = date_range(
Some("2020-01-01"),
Some("2020-01-03"),
Some(2),
Timedelta::NANOS_PER_DAY,
None,
)
.expect_err("start + end + periods with explicit freq must fail closed");
assert!(matches!(err, DateRangeError::TooManyParams));
}
#[test]
fn date_range_keeps_validated_labels_lazy_until_observed() {
let index = date_range(
Some("2024-01-01"),
None,
Some(3),
Timedelta::NANOS_PER_DAY,
Some("timestamp"),
)
.unwrap();
assert_eq!(
index.labels.datetime64_affine_range(),
Some(Int64AffineLabels {
start: 1_704_067_200_000_000_000,
step: Timedelta::NANOS_PER_DAY,
len: 3,
})
);
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.name().map(|n| n.as_str()), Some("timestamp"));
assert_eq!(
index.labels(),
&[
IndexLabel::Datetime64(1_704_067_200_000_000_000),
IndexLabel::Datetime64(1_704_153_600_000_000_000),
IndexLabel::Datetime64(1_704_240_000_000_000_000),
]
);
}
#[test]
fn datetime_index_of_an_affine_range_keeps_it_lazy_so0mr() {
// A DatetimeIndex over a date_range's lazy range, zoned, answers its
// instants without making its labels (br-frankenpandas-so0mr).
let (start, step) = (1_704_067_200_000_000_000, 60 * Timedelta::NANOS_PER_SEC);
let expected: Vec<i64> = (0..4).map(|k| start + k * step).collect();
let affine = Index::from_datetime64_affine_range(start, step, 4).unwrap();
let dti = DatetimeIndex::from_index(affine)
.and_then(|dti| dti.with_tz(Some("UTC")))
.unwrap();
assert_eq!(dti.asi8(), expected);
assert!(dti.as_index().labels.materialized.get().is_none());
assert_eq!(dti.tz().as_deref(), Some("UTC"));
assert_eq!(
DatetimeIndex::from_index(Index::from_datetime64(expected.clone()))
.unwrap()
.asi8(),
expected
);
// Negative: an index of other labels is still refused.
let ints = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]);
assert!(DatetimeIndex::from_index(ints).is_err());
// Labels a clone makes are the original's too (a Series resampled
// made them again every call).
let original = Index::from_datetime64_affine_range(start, step, 4).unwrap();
let clone = original.clone();
assert!(original.labels.materialized.get().is_none());
assert_eq!(clone.labels().len(), 4);
assert!(original.labels.materialized.get().is_some());
assert_eq!(original.labels(), clone.labels());
}
#[test]
fn datetime_index_reads_one_stamp_at_a_position_tumiz() {
// asi8_at is asi8()[pos] without the rest - a lazy range answers
// from its arithmetic, labels unmade (br-frankenpandas-tumiz).
let (start, step) = (1_704_067_200_000_000_000, -3_600 * Timedelta::NANOS_PER_SEC);
let lazy =
DatetimeIndex::from_index(Index::from_datetime64_affine_range(start, step, 5).unwrap())
.unwrap();
let listed = DatetimeIndex::new(vec![start, i64::MIN, start - 7]);
for dti in [&lazy, &listed] {
let all = dti.asi8();
let each: Vec<i64> = (0..all.len()).filter_map(|pos| dti.asi8_at(pos)).collect();
assert_eq!(each, all);
// NEGATIVE: past the end is None, not a stamp.
assert_eq!(dti.asi8_at(all.len()), None);
}
assert!(lazy.as_index().labels.materialized.get().is_none());
}
#[test]
fn date_range_affine_matches_eager_labels_for_each_parameter_form() {
let expected = |start: i64, step: i64, len: usize| {
(0..len)
.map(|offset| {
IndexLabel::Datetime64(
start + i64::try_from(offset).expect("small test offset fits i64") * step,
)
})
.collect::<Vec<_>>()
};
let start = 1_704_067_200_000_000_000;
let start_end = date_range(
Some("2024-01-01"),
Some("2024-01-06"),
None,
2 * Timedelta::NANOS_PER_DAY,
None,
)
.unwrap();
assert_eq!(
start_end.labels(),
expected(start, 2 * Timedelta::NANOS_PER_DAY, 3)
);
let end_periods = date_range(
None,
Some("2024-01-01 02:00:00"),
Some(3),
Timedelta::NANOS_PER_HOUR,
None,
)
.unwrap();
assert_eq!(
end_periods.labels(),
expected(start, Timedelta::NANOS_PER_HOUR, 3)
);
let empty = date_range(
Some("2024-01-01"),
None,
Some(0),
Timedelta::NANOS_PER_DAY,
Some("empty"),
)
.unwrap();
assert!(empty.is_empty());
assert_eq!(empty.name().map(|n| n.as_str()), Some("empty"));
}
#[test]
fn date_range_rejects_generated_timestamp_overflow() {
let err = date_range(
Some("2262-04-11 23:47:16"),
None,
Some(3),
Timedelta::NANOS_PER_SEC,
None,
)
.expect_err("overflow past i64::MAX nanos must fail closed");
assert!(matches!(err, DateRangeError::InvalidRange));
}
#[test]
fn date_range_rejects_backfilled_timestamp_underflow() {
let err = date_range(
None,
Some("1677-09-21 00:12:44"),
Some(3),
Timedelta::NANOS_PER_SEC,
None,
)
.expect_err("underflow before i64::MIN nanos must fail closed");
assert!(matches!(err, DateRangeError::InvalidRange));
}
#[test]
fn date_range_rejects_out_of_bounds_timestamp_parse() {
let err = date_range(
Some("2263-01-01"),
None,
Some(1),
Timedelta::NANOS_PER_DAY,
None,
)
.expect_err("out-of-bounds timestamps must not be coerced to i64::MIN");
assert!(matches!(err, DateRangeError::InvalidRange));
}
#[test]
fn date_offset_business_day_skips_weekend() {
let nanos = apply_date_offset("2024-01-05", DateOffset::BusinessDay(1)).unwrap();
assert_eq!(nanos, 1_704_672_000_000_000_000);
}
#[test]
fn date_offset_month_end_handles_leap_year() {
let nanos = apply_date_offset("2024-02-10", DateOffset::MonthEnd(1)).unwrap();
assert_eq!(nanos, 1_709_164_800_000_000_000);
}
#[test]
fn index_label_numbers_compare_by_value_l5sed() {
use std::hash::{BuildHasher, RandomState};
let hashes = RandomState::new();
let int = IndexLabel::Int64;
let float = |value: f64| IndexLabel::Float64(OrderedF64(value));
// An int and the float it equals are one label, hashed alike.
assert_eq!(int(2), float(2.0));
assert_eq!(hashes.hash_one(int(2)), hashes.hash_one(float(2.0)));
assert_eq!(int(0), float(-0.0));
assert_eq!(hashes.hash_one(int(0)), hashes.hash_one(float(-0.0)));
assert_eq!(int(2).cmp(&float(2.0)), std::cmp::Ordering::Equal);
// Numbers order by value, beside each other; NaN after them.
let mut labels = vec![
IndexLabel::Utf8("a".into()),
int(2),
float(f64::NAN),
float(1.5),
int(1),
];
labels.sort();
assert_eq!(
labels,
vec![
int(1),
float(1.5),
int(2),
float(f64::NAN),
IndexLabel::Utf8("a".into())
]
);
// Exact at the edges: 2^53 + 1 is no float, 2^63 no int.
let big = (1_i64 << 53) + 1;
assert_ne!(int(big), float(9_007_199_254_740_992.0));
assert!(int(big) > float(9_007_199_254_740_992.0));
assert_ne!(int(i64::MAX), float(9_223_372_036_854_775_808.0));
assert!(int(i64::MAX) < float(9_223_372_036_854_775_808.0));
assert_eq!(int(i64::MIN), float(-9_223_372_036_854_775_808.0));
// Lookups over an int index find an integral float key.
let index = Index::new(vec![int(1), int(2)]);
assert_eq!(index.position(&float(2.0)), Some(1));
assert_eq!(index.isin(&[float(1.0)]), vec![true, false]);
let targets = Index::new(vec![float(2.0), float(3.0)]);
assert_eq!(index.get_indexer(&targets), vec![Some(1), None]);
assert!(index.equals(&Index::new(vec![float(1.0), float(2.0)])));
// NEGATIVE: a fraction, text, a bool, a duration and a missing value
// equal no int.
assert_ne!(int(1), float(1.5));
assert_eq!(index.position(&float(1.5)), None);
assert_ne!(int(1), IndexLabel::Utf8("1".into()));
assert_ne!(int(1), IndexLabel::Bool(true));
assert_ne!(int(1), IndexLabel::Timedelta64(1));
assert_ne!(int(1), IndexLabel::Null(fp_types::NullKind::NaN));
assert_eq!(index.position(&IndexLabel::Utf8("2".into())), None);
}
#[test]
fn declared_dtype_holds_and_carries_as_pandas_i20vm() {
use crate::DeclaredDtype;
let ints = || Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]);
// An object index of ints: its dtype object, its labels ints.
let object = ints().with_declared_dtype(Some(DeclaredDtype::Object));
assert_eq!(object.dtype(), "object");
assert_eq!(object.labels()[0], IndexLabel::Int64(1));
assert_eq!(object.take(&[1]).dtype(), "object");
assert_eq!(object.slice(0, 1).dtype(), "object");
// Equality ignores it, as pandas' equals.
assert_eq!(object, ints());
// No row keeps the source's dtype (dwyud).
assert_eq!(ints().take(&[]).dtype(), "int64");
assert_eq!(ints().slice(0, 0).dtype(), "int64");
let floats = Index::new(vec![IndexLabel::Float64(OrderedF64(1.5))]);
assert_eq!(floats.slice(0, 0).dtype(), "float64");
// int32 while the labels are ints (pqjzo).
let int32 = ints().with_declared_dtype(Some(DeclaredDtype::Int32));
assert_eq!(int32.take(&[0]).dtype(), "int32");
let halves = Index::new(vec![IndexLabel::Float64(OrderedF64(0.5))]);
assert_eq!(halves.with_dtype_of(&int32).dtype(), "float64");
// NEGATIVE: labels of their own read their own dtype.
assert_eq!(ints().take(&[0]).dtype(), "int64");
assert_eq!(object.with_declared_dtype(None).dtype(), "int64");
}
#[test]
fn empty_indexes_keep_the_dtype_they_are_built_as_ce86r() {
// No labels show a type: an empty index cast to (or built as) a
// dtype reports it, as pandas (they were object).
let empty = crate::Index::new(Vec::new());
for (dtype, expected) in [
("int64", "int64"),
("float64", "float64"),
("bool", "bool"),
("str", "object"),
("datetime64[ns]", "datetime64[ns]"),
("timedelta64[ns]", "timedelta64[ns]"),
] {
assert_eq!(empty.astype(dtype).unwrap().dtype(), expected, "{dtype}");
}
assert_eq!(
crate::Index::from_datetime64(Vec::new()).dtype(),
"datetime64[ns]"
);
assert_eq!(
crate::Index::from_timedelta64(Vec::new()).dtype(),
"timedelta64[ns]"
);
// NEGATIVE: labels still decide a non-empty index's dtype, and an
// empty one with no dtype asked for is object.
let ints = crate::Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]);
assert_eq!(ints.astype("float64").unwrap().dtype(), "float64");
assert_eq!(empty.dtype(), "object");
assert_eq!(
crate::Index::from_datetime64(vec![5]).declared_dtype(),
None
);
}
#[test]
fn an_empty_period_range_keeps_its_freq_ce86r() {
let start = Period::new(648, PeriodFreq::Monthly);
let none = crate::PeriodIndex::from_range(start, 0);
assert_eq!(none.freq(), Some(PeriodFreq::Monthly));
assert_eq!(none.unique().freq(), Some(PeriodFreq::Monthly));
// Periods' own freq still decides, and equality follows the freq:
// the same periods from either constructor are equal, empty
// indexes of two freqs are not.
let three = crate::PeriodIndex::from_range(start, 3);
assert_eq!(three, crate::PeriodIndex::new(three.values().to_vec()));
assert_ne!(
none,
crate::PeriodIndex::from_range(Period::new(19_000, PeriodFreq::Daily), 0)
);
assert_eq!(crate::PeriodIndex::new(Vec::new()).freq(), None);
}
#[test]
fn take_freq_keeps_it_for_an_empty_take_0l1nu() {
// pandas reads no positions as an empty slice (s.iloc[[]] keeps 'D'),
// one or a steady step as a slice scaled by it, anything else as none.
let daily = || Some("D".to_owned());
assert_eq!(crate::take_freq(daily(), &[]).as_deref(), Some("D"));
assert_eq!(crate::take_freq(daily(), &[3]).as_deref(), Some("D"));
assert_eq!(
crate::take_freq(daily(), &[4, 2, 0]).as_deref(),
Some("-2D")
);
assert_eq!(crate::take_freq(daily(), &[0, 1, 3]), None);
assert_eq!(crate::take_freq(None, &[]), None);
}
#[test]
fn infer_freq_detects_fixed_and_calendar_offsets() {
assert_eq!(
infer_freq_from_timestamps(&["2024-01-01", "2024-01-03", "2024-01-05"]).unwrap(),
Some("2D".to_owned())
);
assert_eq!(
infer_freq_from_timestamps(&[
"2024-01-01",
"2024-01-02",
"2024-01-03",
"2024-01-04",
"2024-01-05",
"2024-01-08",
"2024-01-09",
])
.unwrap(),
Some("B".to_owned())
);
assert_eq!(
infer_freq_from_timestamps(&["2024-01-31", "2024-02-29", "2024-03-31"]).unwrap(),
Some("ME".to_owned())
);
}
#[test]
fn infer_freq_returns_none_for_irregular_or_duplicate_values() {
assert_eq!(
infer_freq_from_timestamps(&["2024-01-01", "2024-01-02", "2024-01-04"]).unwrap(),
None
);
assert_eq!(
infer_freq_from_timestamps(&["2024-01-01", "2024-01-02", "2024-01-02"]).unwrap(),
None
);
}
#[test]
fn infer_freq_uses_datetime_affine_witness_without_materializing_8xtj5() {
let cases = [
(0, 1, 0),
(0, 0, 1),
(0, Timedelta::NANOS_PER_SEC, 2),
(0, Timedelta::NANOS_PER_DAY, 3),
(17, 2 * Timedelta::NANOS_PER_SEC, 100),
(0, -Timedelta::NANOS_PER_SEC, 3),
(i64::MIN, 1, 1),
(i64::MIN, 1, 3),
];
for (start, step, len) in cases {
let affine = Index::from_datetime64_affine_range(start, step, len)
.expect("valid affine test range");
let eager_values = (0..len)
.map(|offset| start + i64::try_from(offset).expect("small test offset") * step)
.collect();
let eager = Index::from_datetime64(eager_values);
let affine_result = infer_freq(&affine);
let eager_result = infer_freq(&eager);
assert_eq!(
format!("{affine_result:?}"),
format!("{eager_result:?}"),
"affine inference must preserve eager semantics for start={start}, step={step}, len={len}",
);
assert!(
affine.labels.materialized.get().is_none(),
"frequency inference must not materialize affine labels",
);
}
}
#[test]
fn union_alignment_preserves_left_then_right_unseen_order() {
let left = Index::new(vec![1_i64.into(), 2_i64.into(), 4_i64.into()]);
let right = Index::new(vec![2_i64.into(), 3_i64.into(), 4_i64.into()]);
let plan = align_union(&left, &right);
assert_eq!(
plan.union_index.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(4),
IndexLabel::Int64(3),
]
);
assert_eq!(plan.left_positions, vec![Some(0), Some(1), Some(2), None]);
assert_eq!(plan.right_positions, vec![None, Some(0), Some(2), Some(1)]);
validate_alignment_plan(&plan).expect("plan must be valid");
}
#[test]
fn duplicate_detection_matches_index_surface() {
let index = Index::new(vec!["a".into(), "a".into(), "b".into()]);
assert!(index.has_duplicates());
}
#[test]
fn has_duplicates_sort_fast_path_matches_hashmap_idxdup() {
// The strict-ascending fast path in has_duplicates must agree with the
// FxHashMap detect_duplicates for every shape: sorted-unique (fast path
// returns false), sorted-with-dups (not strictly ascending -> Unsorted
// -> hashmap), unsorted-unique, unsorted-dups, descending, single,
// empty, and Utf8.
let cases: Vec<Vec<IndexLabel>> = vec![
vec![],
vec![5_i64.into()],
vec![1_i64.into(), 2_i64.into(), 3_i64.into()], // sorted unique
vec![1_i64.into(), 5_i64.into(), 9_i64.into()], // sorted unique, gapped
vec![1_i64.into(), 2_i64.into(), 2_i64.into()], // sorted with dup
vec![3_i64.into(), 1_i64.into(), 2_i64.into()], // unsorted unique
vec![3_i64.into(), 1_i64.into(), 3_i64.into()], // unsorted dup
vec![9_i64.into(), 5_i64.into(), 1_i64.into()], // descending unique
vec!["a".into(), "b".into(), "c".into()], // sorted utf8 unique
vec!["a".into(), "a".into(), "b".into()], // utf8 dup
vec!["c".into(), "a".into(), "b".into()], // unsorted utf8 unique
];
for labels in cases {
let expected = super::detect_duplicates(&labels);
let got = Index::new(labels.clone()).has_duplicates();
assert_eq!(got, expected, "mismatch for {labels:?}");
}
}
#[test]
fn dedup_family_sort_fast_path_matches_reference_idxdup() {
// unique / duplicated / drop_duplicates strict-ascending fast paths must
// equal an independent first-seen reference for every shape.
let cases: Vec<Vec<IndexLabel>> = vec![
vec![],
vec![7_i64.into()],
vec![1_i64.into(), 2_i64.into(), 3_i64.into()], // sorted unique
vec![1_i64.into(), 2_i64.into(), 2_i64.into(), 4_i64.into()], // sorted dup
vec![3_i64.into(), 1_i64.into(), 3_i64.into(), 2_i64.into()], // unsorted dup
vec![9_i64.into(), 5_i64.into(), 1_i64.into()], // descending
vec!["a".into(), "b".into(), "c".into()], // sorted utf8
vec!["b".into(), "a".into(), "b".into()], // unsorted utf8 dup
];
for labels in cases {
let idx = Index::new(labels.clone());
let mut seen = std::collections::HashSet::new();
let ref_unique: Vec<IndexLabel> = labels
.iter()
.filter(|l| seen.insert((*l).clone()))
.cloned()
.collect();
assert_eq!(
idx.unique().labels(),
ref_unique.as_slice(),
"unique {labels:?}"
);
let mut seen_f = std::collections::HashSet::new();
let ref_dup_first: Vec<bool> =
labels.iter().map(|l| !seen_f.insert(l.clone())).collect();
assert_eq!(
idx.duplicated(DuplicateKeep::First),
ref_dup_first,
"duplicated(First) {labels:?}"
);
assert_eq!(
idx.drop_duplicates().labels(),
ref_unique.as_slice(),
"drop_duplicates {labels:?}"
);
}
}
#[test]
fn typed_int64_unique_preserves_typed_backing_codb() {
let index = Index::from_i64_values(vec![3, 1, 3, 2, 1]).set_name("row");
assert!(index.labels.materialized.get().is_none());
let unique = index.unique();
assert_eq!(unique.name().map(|n| n.as_str()), Some("row"));
assert_eq!(unique.labels.int64_view().unwrap().as_slice(), &[3, 1, 2]);
assert!(index.labels.materialized.get().is_none());
assert!(
unique.labels.materialized.get().is_none(),
"typed Int64 unique should preserve typed output backing"
);
let materialized = Index::new(vec![
IndexLabel::Int64(3),
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(2),
IndexLabel::Int64(1),
])
.set_name("row");
assert_eq!(unique.labels(), materialized.unique().labels());
}
#[test]
fn typed_int64_drop_duplicates_preserves_typed_backing_codb() {
let index = Index::from_i64_values(vec![9, 9, 4, 9, 4, 2]).set_name("axis");
assert!(index.labels.materialized.get().is_none());
let dropped = index.drop_duplicates();
assert_eq!(dropped.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[9, 4, 2]);
assert!(index.labels.materialized.get().is_none());
assert!(
dropped.labels.materialized.get().is_none(),
"drop_duplicates delegates to unique and should keep typed backing"
);
}
#[test]
fn typed_int64_drop_duplicates_keep_modes_preserve_typed_backing_codb() {
let index = Index::from_i64_values(vec![9, 9, 4, 9, 4, 2]).set_name("axis");
assert!(index.labels.materialized.get().is_none());
let keep_last = index.drop_duplicates_keep(DuplicateKeep::Last);
let keep_none = index.drop_duplicates_keep(DuplicateKeep::None);
assert_eq!(keep_last.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
keep_last.labels.int64_view().unwrap().as_slice(),
&[9, 4, 2]
);
assert_eq!(keep_none.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(keep_none.labels.int64_view().unwrap().as_slice(), &[2]);
assert!(
index.labels.materialized.get().is_none(),
"keep modes should not materialize the source Int64 labels"
);
assert!(
keep_last.labels.materialized.get().is_none(),
"keep=last should keep typed output backing"
);
assert!(
keep_none.labels.materialized.get().is_none(),
"keep=false should keep typed output backing"
);
let materialized = Index::new(vec![
IndexLabel::Int64(9),
IndexLabel::Int64(9),
IndexLabel::Int64(4),
IndexLabel::Int64(9),
IndexLabel::Int64(4),
IndexLabel::Int64(2),
])
.set_name("axis");
assert_eq!(
keep_last.labels(),
materialized
.drop_duplicates_keep(DuplicateKeep::Last)
.labels()
);
assert_eq!(
keep_none.labels(),
materialized
.drop_duplicates_keep(DuplicateKeep::None)
.labels()
);
}
#[test]
fn sorted_merge_set_ops_match_reference_idxdup() {
// intersection / difference must equal the self-ordered, deduped
// FxHashMap reference whether the two-pointer fast path fires (both
// strictly ascending) or the hash path runs (any side unsorted).
let s = |v: &[i64]| v.iter().map(|x| IndexLabel::Int64(*x)).collect::<Vec<_>>();
let pairs: Vec<(Vec<IndexLabel>, Vec<IndexLabel>)> = vec![
(s(&[1, 2, 3, 5]), s(&[2, 3, 4])), // both sorted, overlap
(s(&[1, 2, 3]), s(&[4, 5, 6])), // both sorted, disjoint
(s(&[1, 2, 3]), s(&[1, 2, 3])), // identical
(s(&[1, 2, 3]), vec![]), // empty other
(vec![], s(&[1, 2, 3])), // empty self
(s(&[3, 1, 2]), s(&[2, 3])), // self unsorted -> hash path
(s(&[1, 2, 3]), s(&[3, 1])), // other unsorted -> hash path
(
vec!["a".into(), "c".into(), "e".into()],
vec!["b".into(), "c".into()],
), // utf8 sorted
(
vec![1_i64.into(), 2_i64.into()],
vec!["a".into(), "b".into()],
), // mixed-type sorted, disjoint by Ord variant
];
for (a, b) in pairs {
let ia = Index::new(a.clone());
let ib = Index::new(b.clone());
let bset: std::collections::HashSet<IndexLabel> = b.iter().cloned().collect();
let mut seen = std::collections::HashSet::new();
let ref_inter: Vec<IndexLabel> = a
.iter()
.filter(|l| bset.contains(*l) && seen.insert((*l).clone()))
.cloned()
.collect();
assert_eq!(
ia.intersection(&ib).labels(),
ref_inter.as_slice(),
"intersection {a:?} ∩ {b:?}"
);
let mut seen_d = std::collections::HashSet::new();
let ref_diff: Vec<IndexLabel> = a
.iter()
.filter(|l| !bset.contains(*l) && seen_d.insert((*l).clone()))
.cloned()
.collect();
assert_eq!(
ia.difference(&ib).labels(),
ref_diff.as_slice(),
"difference {a:?} \\ {b:?}"
);
}
}
#[test]
fn sorted_int64_set_ops_keep_typed_backing_without_materializing_v7m2q() {
let left = Index::from_i64_values(vec![1, 3, 5, 9]).set_name("axis");
let right = Index::from_i64_values(vec![0, 3, 4, 9, 10]).set_name("axis");
assert!(left.labels.materialized.get().is_none());
assert!(right.labels.materialized.get().is_none());
let intersection = left.intersection(&right);
let difference = left.difference(&right);
assert_eq!(intersection.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(difference.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
intersection.labels.int64_view().unwrap().as_slice(),
&[3, 9]
);
assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[1, 5]);
assert!(
left.labels.materialized.get().is_none(),
"sorted Int64 set ops should not materialize the left input"
);
assert!(
right.labels.materialized.get().is_none(),
"sorted Int64 set ops should not materialize the right input"
);
assert!(
intersection.labels.materialized.get().is_none(),
"intersection should keep typed Int64 output backing"
);
assert!(
difference.labels.materialized.get().is_none(),
"difference should keep typed Int64 output backing"
);
}
#[test]
fn datetime_timedelta_get_loc_binary_search_matches_linear_idxdup() {
// get_loc now binary-searches a monotonic typed index; the result must
// equal a linear first-match reference for both sorted (binary path) and
// unsorted (linear path) value vectors.
for nanos in [
vec![10_i64, 20, 30, 40, 50], // sorted -> AscendingDatetime64/Timedelta64
vec![30_i64, 10, 50, 20, 40], // unsorted -> linear fallback
] {
let dt = DatetimeIndex::new(nanos.clone());
let td = TimedeltaIndex::new(nanos.clone());
for q in [10_i64, 20, 30, 40, 50, 0, 99] {
let expected = nanos.iter().position(|n| *n == q);
assert_eq!(
dt.get_loc(q).ok(),
expected,
"datetime nanos={nanos:?} q={q}"
);
assert_eq!(
td.get_loc(q).ok(),
expected,
"timedelta nanos={nanos:?} q={q}"
);
}
}
}
#[test]
fn get_indexer_sorted_fast_path_matches_reference_idxdup() {
// get_indexer's sorted merge / binary-search fast paths and the
// FxHashMap fallback must all equal a first-occurrence reference.
let s = |v: &[i64]| v.iter().map(|x| IndexLabel::Int64(*x)).collect::<Vec<_>>();
let cases: Vec<(Vec<IndexLabel>, Vec<IndexLabel>)> = vec![
(s(&[1, 2, 3, 4, 5]), s(&[2, 4, 6])), // both sorted
(s(&[1, 2, 3, 4, 5]), s(&[5, 1, 3, 9])), // self sorted, target unsorted
(s(&[3, 1, 5, 2]), s(&[1, 2, 3])), // self unsorted -> hash path
(s(&[1, 2, 3]), vec![]), // empty target
(vec![], s(&[1, 2])), // empty self
(
vec!["a".into(), "c".into(), "e".into()],
vec!["c".into(), "z".into(), "a".into()],
), // utf8, target unsorted
(s(&[1, 2, 3]), vec!["a".into()]), // mixed type sorted, no match
];
for (a, b) in cases {
let ia = Index::new(a.clone());
let ib = Index::new(b.clone());
let ref_out: Vec<Option<usize>> =
b.iter().map(|t| a.iter().position(|x| x == t)).collect();
assert_eq!(ia.get_indexer(&ib), ref_out, "get_indexer {a:?} -> {b:?}");
}
}
/// br-frankenpandas: `RangeValuesIter` carries an i64 fast arm and an i128
/// fallback, plus overridden `fold`/`rfold` that must agree with the
/// element-at-a-time `next`/`next_back` they bypass. Every combination is
/// checked against an independent i128 reference, including a range whose
/// endpoint does NOT fit in i64 so the fallback is genuinely exercised —
/// otherwise this test would pass while only ever running one arm.
#[test]
fn range_values_iter_arms_and_folds_all_agree() {
let cases: [(i64, i64, i64); 9] = [
(0, 20, 2),
(1, 7, 3),
(5, 5, 1),
(10, 0, -2),
(-9, 9, 4),
(0, 1, 1),
(i64::MIN, i64::MIN + 10, 1),
(i64::MAX - 10, i64::MAX, 1),
(0, i64::MAX, i64::MAX / 2),
];
let mut saw_fast = false;
for (start, stop, step) in cases {
let range = RangeIndex::new(start, stop, step).expect("valid range");
let values = range.values();
let len = values.len();
// The i128 fallback cannot be reached through a normally-sized
// RangeIndex: the last value is always strictly inside `stop`, so
// it fits in i64 by construction, and the only ranges that select
// the fallback are longer than i64::MAX and cannot be iterated in
// a test. So drive the SAME parameters through a forced-slow
// iterator and require the two arms to agree element for element.
// Without this the fallback would be dead code under test.
let slow = crate::RangeValuesIter {
start,
step,
head: 0,
tail: len,
i64_safe: false,
};
assert!(!slow.i64_safe);
assert_eq!(
slow.collect::<Vec<_>>(),
values.iter().collect::<Vec<_>>(),
"i128 arm disagrees with i64 arm {start},{stop},{step}"
);
assert_eq!(
slow.fold(0_i128, |acc, v| acc + i128::from(v)),
values.iter().fold(0_i128, |acc, v| acc + i128::from(v)),
"i128 fold disagrees with i64 fold {start},{stop},{step}"
);
assert_eq!(
slow.rfold(0_i128, |acc, v| acc + i128::from(v)),
values.iter().rfold(0_i128, |acc, v| acc + i128::from(v)),
"i128 rfold disagrees with i64 rfold {start},{stop},{step}"
);
let reference: Vec<i64> = (0..len)
.map(|position| {
let v = i128::from(start) + (position as i128) * i128::from(step);
i64::try_from(v).expect("reference fits")
})
.collect();
assert!(
values.iter().i64_safe,
"a normally-sized range must select the i64 arm {start},{stop},{step}"
);
saw_fast = true;
assert_eq!(
values.iter().collect::<Vec<_>>(),
reference,
"next {start},{stop},{step}"
);
assert_eq!(values.to_vec(), reference, "to_vec {start},{stop},{step}");
let mut reversed: Vec<i64> = values.iter().rev().collect();
reversed.reverse();
assert_eq!(reversed, reference, "next_back {start},{stop},{step}");
let want: i128 = reference.iter().map(|&v| i128::from(v)).sum();
let folded = values.iter().fold(0_i128, |acc, v| acc + i128::from(v));
let rfolded = values.iter().rfold(0_i128, |acc, v| acc + i128::from(v));
assert_eq!(folded, want, "fold {start},{stop},{step}");
assert_eq!(rfolded, want, "rfold {start},{stop},{step}");
assert_eq!(
values.iter().len(),
len,
"ExactSizeIterator {start},{stop},{step}"
);
// A partially consumed iterator must fold the REMAINDER, which is
// where a fast arm that recomputes from `start` would silently
// disagree with `next`.
if len >= 3 {
let mut partial = values.iter();
partial.next();
partial.next_back();
assert_eq!(
partial.fold(0_i128, |acc, v| acc + i128::from(v)),
reference[1..len - 1]
.iter()
.map(|&v| i128::from(v))
.sum::<i128>(),
"partial fold {start},{stop},{step}"
);
}
}
assert!(saw_fast, "no case exercised the i64 fast arm");
// And the selector itself must still be able to say NO: a range longer
// than i64::MAX positions cannot do i64 position arithmetic. Checked
// without iterating it.
let huge = RangeIndex::new(i64::MIN, i64::MAX, 1).expect("valid range");
assert!(
!huge.values().iter().i64_safe,
"a range longer than i64::MAX must fall back to the i128 arm"
);
}
#[test]
fn known_unique_constructor_seeds_duplicate_cache() {
let index = Index::new_known_unique(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
assert_eq!(index.duplicate_cache.get(), Some(&false));
assert!(!index.has_duplicates());
}
#[test]
fn index_equality_ignores_duplicate_cache_state() {
let index_with_cache = Index::new(vec!["a".into(), "a".into(), "b".into()]);
assert!(index_with_cache.has_duplicates());
let fresh_index = Index::new(vec!["a".into(), "a".into(), "b".into()]);
assert_eq!(index_with_cache, fresh_index);
}
#[test]
fn index_label_identity_cache_preserves_equality_contracts() {
let base = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
let clone = base.clone();
assert_eq!(base.label_identity, clone.label_identity);
assert_eq!(base, clone);
let renamed = clone.rename_index(Some("rows"));
assert_eq!(base.label_identity, renamed.label_identity);
assert!(base.equals(&renamed));
assert!(!base.identical(&renamed));
let independent_equal = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
assert_ne!(base.label_identity, independent_equal.label_identity);
assert_eq!(base, independent_equal);
let different = Index::new(vec![1_i64.into(), 2_i64.into(), 4_i64.into()]);
assert_ne!(base, different);
assert!(!base.equals(&different));
}
#[test]
fn label_kinds_equal_a_pass_over_the_labels_nmna9() {
// label_kinds - kept by label identity, answered without a scan for
// typed ints and a datetime range - equals a fold over the labels,
// and the typed index constructors check through it
// (br-frankenpandas-nmna9).
let pass = |index: &Index| {
index
.labels()
.iter()
.fold(LabelKinds::default(), |kinds, label| {
kinds.union(LabelKinds::of(label))
})
};
let null = |kind| IndexLabel::Null(kind);
let cases = [
Index::new(vec![1_i64.into(), 2_i64.into()]),
Index::from_i64_values(vec![5, 3, 9]),
Index::from_range(0, 10, 2),
Index::new(vec![
"a".into(),
null(fp_types::NullKind::NaN),
IndexLabel::Bool(true),
]),
Index::from_datetime64(vec![0, 10, 20]),
Index::new(vec![
IndexLabel::Datetime64(3),
null(fp_types::NullKind::NaT),
]),
Index::new(vec![
IndexLabel::Timedelta64(7),
null(fp_types::NullKind::Null),
]),
Index::new(Vec::new()),
];
for index in cases {
assert_eq!(index.label_kinds(), pass(&index), "{index:?}");
assert_eq!(index.clone().label_kinds(), pass(&index), "{index:?}");
}
assert!(DatetimeIndex::from_index(Index::from_datetime64(vec![0, 10, 20])).is_ok());
assert!(TimedeltaIndex::from_index(Index::new(vec![IndexLabel::Timedelta64(1)])).is_ok());
// NEGATIVE: another kind beside them refuses, and labels made from
// ones already seen are a new identity with their own kinds.
assert!(
DatetimeIndex::from_index(Index::new(vec![IndexLabel::Datetime64(1), 2_i64.into()]))
.is_err()
);
assert!(
TimedeltaIndex::from_index(Index::new(vec![
IndexLabel::Timedelta64(1),
null(fp_types::NullKind::NaT),
]))
.is_err()
);
let ints = Index::new(vec![1_i64.into(), 2_i64.into()]);
assert_eq!(ints.label_kinds(), LabelKinds::INT64);
let mut labels = ints.labels().to_vec();
labels.push(IndexLabel::Bool(true));
assert_eq!(
Index::new(labels).label_kinds(),
LabelKinds::INT64.union(LabelKinds::BOOL)
);
}
#[test]
fn row_multiindex_levels_ride_with_their_flat_labels_4qg5w9() {
let utf8 = |s: &str| IndexLabel::Utf8(s.to_owned());
let levels = MultiIndex::from_arrays(vec![
vec![utf8("y"), utf8("x"), utf8("x")],
vec![1_i64.into(), 1_i64.into(), 2_i64.into()],
])
.expect("levels")
.set_names(vec![Some("k".into()), Some("j".into())]);
let flat = Index::new(vec![utf8("y|1"), utf8("x|1"), utf8("x|2")]);
let index = flat
.clone()
.with_row_multiindex(levels.clone())
.expect("heights match");
assert_eq!(index.row_multiindex(), Some(&levels));
assert_eq!(index, flat, "the levels do not change label equality");
assert_eq!(index.clone().row_multiindex(), Some(&levels));
// take and slice carry the levels at the same positions.
let taken = index.take(&[2, 0]);
assert_eq!(taken.labels(), &[utf8("x|2"), utf8("y|1")]);
let taken_levels = taken.row_multiindex().expect("take carries the levels");
assert_eq!(
taken_levels.get_tuple(0),
Some(vec![&utf8("x"), &2_i64.into()])
);
assert_eq!(
taken_levels.get_tuple(1),
Some(vec![&utf8("y"), &1_i64.into()])
);
assert_eq!(taken_levels.names(), levels.names());
let sliced = index.slice(1, 2);
assert_eq!(sliced.labels(), &[utf8("x|1"), utf8("x|2")]);
let sliced_levels = sliced.row_multiindex().expect("slice carries the levels");
assert_eq!(sliced_levels.len(), 2);
assert_eq!(
sliced_levels.get_tuple(0),
Some(vec![&utf8("x"), &1_i64.into()])
);
// NEGATIVE: labels built any other way are flat, never mislabelled.
let sorted = index.sort_values();
assert_eq!(sorted.labels(), &[utf8("x|1"), utf8("x|2"), utf8("y|1")]);
assert!(sorted.row_multiindex().is_none());
assert!(index.to_flat_index().row_multiindex().is_none());
assert!(matches!(
flat.with_row_multiindex(levels.take(&[0]).expect("take")),
Err(IndexError::LengthMismatch {
expected: 3,
actual: 1,
..
})
));
}
#[test]
fn semantic_fingerprint_cache_reuses_label_result() {
let index = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
let calls = std::cell::Cell::new(0);
let first = index.semantic_labels_fingerprint_with(|labels| {
calls.set(calls.get() + 1);
format!("labels:{}", labels.len())
});
let second = index.semantic_labels_fingerprint_with(|_| {
calls.set(calls.get() + 1);
"changed".to_owned()
});
assert_eq!(first, "labels:3");
assert_eq!(second, "labels:3");
assert_eq!(calls.get(), 1);
}
#[test]
fn int64_unit_range_index_preserves_materialized_surface() {
let index = Index::new_known_unique_int64_unit_range(-2, 4).rename_index(Some("idx"));
let reference = Index::new(vec![
IndexLabel::Int64(-2),
IndexLabel::Int64(-1),
IndexLabel::Int64(0),
IndexLabel::Int64(1),
])
.rename_index(Some("idx"));
assert_eq!(index.len(), 4);
assert!(!index.has_duplicates());
assert!(index.is_sorted());
assert_eq!(index.position(&IndexLabel::Int64(0)), Some(2));
assert_eq!(index.position(&IndexLabel::Int64(2)), None);
assert_eq!(index.labels(), reference.labels());
assert_eq!(index, reference);
}
#[test]
fn int64_affine_range_index_preserves_materialized_surface() {
let index = Index::new_known_unique_int64_affine_range(3, 2, 4)
.unwrap()
.rename_index(Some("idx"));
let reference = Index::new(vec![
IndexLabel::Int64(3),
IndexLabel::Int64(5),
IndexLabel::Int64(7),
IndexLabel::Int64(9),
])
.rename_index(Some("idx"));
assert_eq!(index.len(), 4);
assert!(!index.has_duplicates());
assert!(index.is_sorted());
assert_eq!(index.position(&IndexLabel::Int64(7)), Some(2));
assert_eq!(index.position(&IndexLabel::Int64(8)), None);
assert_eq!(index.labels(), reference.labels());
let values = index.int64_label_values().unwrap();
assert_eq!(values.as_slice(), &[3, 5, 7, 9]);
assert_eq!(index, reference);
let singleton = Index::new_known_unique_int64_affine_range(i64::MAX, 1, 1).unwrap();
assert_eq!(singleton.labels(), &[IndexLabel::Int64(i64::MAX)]);
}
#[test]
fn int64_strided_index_preserves_duplicate_and_unsorted_semantics() {
let duplicate =
Index::from_i64_strided_values(Arc::new(vec![10, 99, 10, 99, 20]), 0, 2, 3).unwrap();
assert_eq!(
duplicate.labels(),
&[
IndexLabel::Int64(10),
IndexLabel::Int64(10),
IndexLabel::Int64(20),
]
);
assert!(duplicate.has_duplicates());
assert!(!duplicate.is_sorted());
assert_eq!(duplicate.position(&IndexLabel::Int64(20)), Some(2));
let unsorted =
Index::from_i64_strided_values(Arc::new(vec![30, 99, 10, 99, 20]), 0, 2, 3).unwrap();
assert_eq!(int64_labels(&unsorted), vec![30, 10, 20]);
assert!(!unsorted.has_duplicates());
assert!(!unsorted.is_sorted());
assert_eq!(unsorted.position(&IndexLabel::Int64(10)), Some(1));
}
#[test]
fn index_variant_wrappers_expose_public_type_surface() {
let range = RangeIndex::new(1, 7, 2).unwrap().set_name("row");
assert_eq!(range.values().to_vec(), vec![1, 3, 5]);
assert_eq!(range.to_list(), range.values().to_vec());
assert_eq!(range.tolist(), range.values().to_vec());
assert_eq!(range.to_numpy(), range.values().to_vec());
assert_eq!(range.array(), range.values().to_vec());
assert_eq!(range.len(), 3);
assert_eq!(range.size(), 3);
assert_eq!(range.shape(), (3,));
assert!(!range.empty());
assert_eq!(range.dtype(), "int64");
assert_eq!(range.dtypes(), vec!["int64"]);
assert_eq!(range.names(), vec![Some("row".to_owned())]);
assert_eq!(range.copy(), range);
assert_eq!(range.rename_index(None::<&str>).name(), None);
assert_eq!(range.nbytes(), 3 * std::mem::size_of::<i64>());
assert_eq!(range.to_index().name().map(|n| n.as_str()), Some("row"));
assert!(RangeIndex::new(0, 5, 0).is_err());
let dt = DatetimeIndex::new(vec![1_706_918_400_000_000_000, i64::MIN]).set_name("when");
assert_eq!(dt.year(), vec![Some(2024), None]);
assert_eq!(dt.month(), vec![Some(2), None]);
assert_eq!(dt.day(), vec![Some(3), None]);
assert_eq!(dt.values(), vec![Some(1_706_918_400_000_000_000), None]);
assert_eq!(dt.to_list(), dt.values());
assert_eq!(dt.tolist(), dt.values());
assert_eq!(dt.to_numpy(), dt.values());
assert_eq!(dt.array(), dt.values());
assert_eq!(dt.size(), 2);
assert_eq!(dt.shape(), (2,));
assert!(!dt.empty());
assert_eq!(dt.dtype(), "datetime64[ns]");
assert_eq!(dt.dtypes(), vec!["datetime64[ns]"]);
assert_eq!(dt.names(), vec![Some("when".to_owned())]);
assert_eq!(dt.copy(), dt);
assert!(dt.hasnans());
assert_eq!(dt.isna(), vec![false, true]);
assert_eq!(dt.notna(), vec![true, false]);
assert!(dt.nbytes() <= dt.memory_usage(true));
assert!(DatetimeIndex::from_index(Index::from_i64(vec![1])).is_err());
let td = TimedeltaIndex::new(vec![90_061_000_000_000, Timedelta::NAT]).set_name("delta");
assert_eq!(td.days(), vec![Some(1), None]);
assert_eq!(td.seconds(), vec![Some(3661), None]);
assert_eq!(td.total_seconds(), vec![Some(90061.0), None]);
assert_eq!(td.values(), vec![Some(90_061_000_000_000), None]);
assert_eq!(td.to_list(), td.values());
assert_eq!(td.tolist(), td.values());
assert_eq!(td.to_numpy(), td.values());
assert_eq!(td.array(), td.values());
assert_eq!(td.size(), 2);
assert_eq!(td.shape(), (2,));
assert!(!td.empty());
assert_eq!(td.dtype(), "timedelta64[ns]");
assert_eq!(td.dtypes(), vec!["timedelta64[ns]"]);
assert_eq!(td.names(), vec![Some("delta".to_owned())]);
assert_eq!(td.copy(), td);
assert!(td.hasnans());
assert_eq!(td.isna(), vec![false, true]);
assert_eq!(td.notna(), vec![true, false]);
let period =
PeriodIndex::from_range(Period::new(10, PeriodFreq::Monthly), 3).set_name("period");
assert_eq!(period.freq(), Some(PeriodFreq::Monthly));
assert_eq!(
period.values(),
&[
Period::new(10, PeriodFreq::Monthly),
Period::new(11, PeriodFreq::Monthly),
Period::new(12, PeriodFreq::Monthly),
]
);
assert_eq!(period.to_list(), period.values());
assert_eq!(period.tolist(), period.values());
assert_eq!(period.to_numpy(), period.values());
assert_eq!(period.array(), period.values());
assert_eq!(period.size(), 3);
assert_eq!(period.shape(), (3,));
assert!(!period.empty());
assert_eq!(period.dtype(), "period[M]");
assert_eq!(period.dtypes(), vec!["period[M]".to_owned()]);
assert_eq!(period.names(), vec![Some("period".to_owned())]);
assert_eq!(period.copy(), period);
assert_eq!(period.rename_index(None::<&str>).name(), None);
assert!(period.nbytes() <= period.memory_usage(true));
assert_eq!(period.to_index().name().map(|n| n.as_str()), Some("period"));
let period_width = std::mem::size_of::<Period>();
assert_eq!(period.nbytes(), 3 * period_width);
assert_eq!(period.memory_usage(true), 3 * period_width + "period".len());
assert_eq!(
super::fixed_width_label_memory_usage(usize::MAX, period_width),
usize::MAX
);
let categorical = CategoricalIndex::from_values(
vec!["low".to_owned(), "high".to_owned(), "low".to_owned()],
true,
)
.set_name("priority");
assert_eq!(
categorical.categories(),
&[IndexLabel::from("low"), IndexLabel::from("high")]
);
assert_eq!(categorical.codes(), vec![Some(0), Some(1), Some(0)]);
assert!(categorical.ordered());
assert_eq!(
categorical.values(),
vec![
IndexLabel::from("low"),
IndexLabel::from("high"),
IndexLabel::from("low")
]
);
assert_eq!(categorical.to_list(), categorical.values());
assert_eq!(categorical.tolist(), categorical.values());
assert_eq!(categorical.to_numpy(), categorical.values());
assert_eq!(categorical.array(), categorical.values());
assert_eq!(categorical.size(), 3);
assert_eq!(categorical.shape(), (3,));
assert!(!categorical.empty());
assert_eq!(categorical.dtype(), "category");
assert_eq!(categorical.dtypes(), vec!["category"]);
assert_eq!(categorical.names(), vec![Some("priority".to_owned())]);
assert_eq!(categorical.copy(), categorical);
assert_eq!(categorical.isna(), vec![false, false, false]);
assert_eq!(categorical.notna(), vec![true, true, true]);
assert!(categorical.nbytes() <= categorical.memory_usage(true));
assert_eq!(
categorical.to_index().name().map(|n| n.as_str()),
Some("priority")
);
// A label outside the categories is NaN, as pandas' constructor.
let outside = CategoricalIndex::with_categories(
vec!["missing".to_owned()],
vec!["known".to_owned()],
false,
)
.expect("a label outside the categories is NaN");
assert_eq!(
outside.labels(),
&[IndexLabel::Null(fp_types::NullKind::NaN)]
);
assert_eq!(outside.isna(), vec![true]);
assert_eq!(outside.categories(), &[IndexLabel::from("known")]);
// Repeated categories still reject.
assert!(
CategoricalIndex::with_categories(
vec!["known".to_owned()],
vec!["known".to_owned(), "known".to_owned()],
false,
)
.is_err()
);
}
#[test]
fn categorical_index_memory_usage_saturates_uza04180() -> Result<(), super::IndexError> {
let categorical = CategoricalIndex::from_values(
vec!["low".to_owned(), "high".to_owned(), "low".to_owned()],
true,
)
.set_name("priority");
let fixed = 5 * std::mem::size_of::<String>();
assert_eq!(categorical.nbytes(), fixed);
assert_eq!(categorical.memory_usage(false), fixed);
assert_eq!(
categorical.memory_usage(true),
fixed + "lowhighlow".len() + "lowhigh".len() + "priority".len()
);
assert_eq!(super::saturating_usize_sum([usize::MAX, 1]), usize::MAX);
Ok(())
}
#[test]
fn typed_index_str_accessors_forward_flat_labels_e7ms9() -> Result<(), super::IndexError> {
let flat = Index::new(vec!["Alpha".into(), 1_i64.into(), "".into()]);
assert_eq!(
flat.r#str().lower(),
vec![Some("alpha".to_owned()), None, Some(String::new())]
);
let range = RangeIndex::new(1, 4, 1)?;
assert_eq!(range.r#str().len(), vec![None, None, None]);
let dt = DatetimeIndex::new(vec![1_704_067_200_000_000_000]);
assert_eq!(dt.r#str().upper(), vec![None]);
let td = TimedeltaIndex::new(vec![90_061_000_000_000]);
assert_eq!(td.r#str().contains("day"), vec![None]);
// TEST-CHANGE (45fzr): period labels are periods now, not text, so
// the str accessor reads them as the instants and durations above
// do (pandas raises AttributeError for PeriodIndex.str).
let period = PeriodIndex::from_range(Period::new(10, PeriodFreq::Monthly), 2);
assert_eq!(period.r#str().lower(), vec![None, None]);
let categorical = CategoricalIndex::from_values(
vec!["Low".to_owned(), "HIGH".to_owned(), String::new()],
false,
);
assert_eq!(
categorical.r#str().lower(),
vec![
Some("low".to_owned()),
Some("high".to_owned()),
Some(String::new())
]
);
Ok(())
}
#[test]
fn period_index_from_fields_builds_period_ordinals_th1fd() -> Result<(), super::IndexError> {
let years = [2020, 2021];
let months = [1, 2];
let monthly = PeriodIndex::from_fields(PeriodFields {
month: Some(&months),
freq: Some(PeriodFreq::Monthly),
..PeriodFields::new(&years)
})?;
assert_eq!(
monthly.values(),
&[
Period::new(600, PeriodFreq::Monthly),
Period::new(613, PeriodFreq::Monthly)
]
);
let quarter_years = [2020];
let quarters = [2];
let quarterly = PeriodIndex::from_fields(PeriodFields {
quarter: Some(&quarters),
..PeriodFields::new(&quarter_years)
})?;
assert_eq!(
quarterly.values(),
&[Period::new(201, PeriodFreq::QUARTERLY)]
);
let single_year = [2020];
let single_month = [1];
let weekly = PeriodIndex::from_fields(PeriodFields {
month: Some(&single_month),
freq: Some(PeriodFreq::WEEKLY),
..PeriodFields::new(&single_year)
})?;
assert_eq!(weekly.values(), &[Period::new(2_610, PeriodFreq::WEEKLY)]);
let weekend_day = [4];
let business = PeriodIndex::from_fields(PeriodFields {
month: Some(&single_month),
day: Some(&weekend_day),
freq: Some(PeriodFreq::Business),
..PeriodFields::new(&single_year)
})?;
assert_eq!(
business.values(),
&[Period::new(13_047, PeriodFreq::Business)]
);
let days = [2];
let hours = [3];
let minutes = [4];
let seconds = [5];
let secondly = PeriodIndex::from_fields(PeriodFields {
month: Some(&single_month),
day: Some(&days),
hour: Some(&hours),
minute: Some(&minutes),
second: Some(&seconds),
freq: Some(PeriodFreq::Secondly),
..PeriodFields::new(&single_year)
})?;
let expected_date = chrono::NaiveDate::from_ymd_opt(2020, 1, 2)
.ok_or_else(|| super::IndexError::InvalidArgument("invalid test date".to_owned()))?;
let expected_time = chrono::NaiveTime::from_hms_opt(3, 4, 5)
.ok_or_else(|| super::IndexError::InvalidArgument("invalid test time".to_owned()))?;
let expected_nanos =
super::date_and_time_to_nanos(expected_date, super::time_to_nanos(expected_time))
.map_err(super::period_date_error)?;
assert_eq!(
secondly.values(),
&[Period::new(
super::datetime_period_ordinal(expected_nanos, PeriodFreq::Secondly)?,
PeriodFreq::Secondly
)]
);
assert!(
PeriodIndex::from_fields(PeriodFields {
month: Some(&months),
freq: Some(PeriodFreq::Monthly),
..PeriodFields::new(&single_year)
})
.is_err()
);
let invalid_month = [13];
assert!(
PeriodIndex::from_fields(PeriodFields {
month: Some(&invalid_month),
freq: Some(PeriodFreq::Monthly),
..PeriodFields::new(&single_year)
})
.is_err()
);
let invalid_day = [99];
assert_eq!(
PeriodIndex::from_fields(PeriodFields {
month: Some(&single_month),
day: Some(&invalid_day),
freq: Some(PeriodFreq::Monthly),
..PeriodFields::new(&single_year)
})?
.values(),
&[Period::new(600, PeriodFreq::Monthly)]
);
assert!(
PeriodIndex::from_fields(PeriodFields {
quarter: Some(&quarters),
month: Some(&single_month),
freq: Some(PeriodFreq::Monthly),
..PeriodFields::new(&single_year)
})
.is_err()
);
Ok(())
}
#[test]
fn index_variant_wrappers_expose_identity_and_type_surface() {
let range = RangeIndex::new(1, 7, 2).unwrap().set_name("row");
assert!(range.is_(&range));
assert!(range.equals(&range.copy()));
assert!(range.identical(&range.copy()));
assert!(!range.identical(&range.rename_index(None::<&str>)));
assert!(range.is_unique());
assert!(!range.has_duplicates());
assert!(range.is_monotonic_increasing());
assert!(!range.is_monotonic_decreasing());
assert_eq!(range.nunique(), 3);
assert_eq!(range.ndim(), 1);
assert_eq!(RangeIndex::new(4, 5, 1).unwrap().item().unwrap(), 4);
assert!(range.item().is_err());
assert!(range.holds_integer());
assert_eq!(range.inferred_type(), "integer");
assert!(range.is_integer());
assert!(range.is_numeric());
assert!(!range.is_boolean());
assert!(!range.is_categorical());
assert!(!range.is_floating());
assert!(!range.is_interval());
assert!(!range.is_object());
let dt = DatetimeIndex::new(vec![1_706_918_400_000_000_000, i64::MIN]).set_name("when");
assert!(dt.is_(&dt));
assert!(dt.equals(&dt.copy()));
assert!(dt.identical(&dt.copy()));
assert!(!dt.identical(&dt.rename_index(None::<&str>)));
assert!(dt.is_unique());
assert!(!dt.has_duplicates());
assert_eq!(dt.nunique(), 1);
assert_eq!(dt.nunique_with_dropna(false), 2);
assert_eq!(dt.ndim(), 1);
assert_eq!(
DatetimeIndex::new(vec![1_706_918_400_000_000_000])
.item()
.unwrap(),
Some(1_706_918_400_000_000_000)
);
assert_eq!(DatetimeIndex::new(vec![i64::MIN]).item().unwrap(), None);
assert_eq!(dt.inferred_type(), "datetime64");
assert!(!dt.holds_integer());
assert!(!dt.is_integer());
assert!(!dt.is_numeric());
assert!(!dt.is_boolean());
assert!(!dt.is_categorical());
assert!(!dt.is_floating());
assert!(!dt.is_interval());
assert!(!dt.is_object());
assert!(DatetimeIndex::new(vec![1, 2]).is_monotonic_increasing());
assert!(DatetimeIndex::new(vec![2, 1]).is_monotonic_decreasing());
let td = TimedeltaIndex::new(vec![1, Timedelta::NAT]).set_name("delta");
assert!(td.is_(&td));
assert!(td.equals(&td.copy()));
assert!(td.identical(&td.copy()));
assert!(!td.identical(&td.rename_index(None::<&str>)));
assert!(td.is_unique());
assert_eq!(td.nunique(), 1);
assert_eq!(td.nunique_with_dropna(false), 2);
assert_eq!(td.ndim(), 1);
assert_eq!(TimedeltaIndex::new(vec![7]).item().unwrap(), Some(7));
assert_eq!(
TimedeltaIndex::new(vec![Timedelta::NAT]).item().unwrap(),
None
);
assert_eq!(td.inferred_type(), "timedelta64");
assert!(!td.holds_integer());
assert!(!td.is_integer());
assert!(!td.is_numeric());
assert!(!td.is_boolean());
assert!(!td.is_categorical());
assert!(!td.is_floating());
assert!(!td.is_interval());
assert!(!td.is_object());
assert!(TimedeltaIndex::new(vec![1, 2]).is_monotonic_increasing());
assert!(TimedeltaIndex::new(vec![2, 1]).is_monotonic_decreasing());
let period =
PeriodIndex::from_range(Period::new(10, PeriodFreq::Monthly), 3).set_name("period");
assert!(period.is_(&period));
assert!(period.equals(&period.copy()));
assert!(period.identical(&period.copy()));
assert!(!period.identical(&period.rename_index(None::<&str>)));
assert!(period.is_unique());
assert!(!period.has_duplicates());
assert!(period.is_monotonic_increasing());
assert!(!period.is_monotonic_decreasing());
assert_eq!(period.nunique(), 3);
assert_eq!(period.ndim(), 1);
assert_eq!(
PeriodIndex::new(vec![Period::new(42, PeriodFreq::Daily)])
.item()
.unwrap(),
Period::new(42, PeriodFreq::Daily)
);
assert_eq!(period.inferred_type(), "period");
assert!(!period.holds_integer());
assert!(!period.is_integer());
assert!(!period.is_numeric());
assert!(!period.is_boolean());
assert!(!period.is_categorical());
assert!(!period.is_floating());
assert!(!period.is_interval());
assert!(!period.is_object());
let categorical = CategoricalIndex::from_values(
vec!["low".to_owned(), "high".to_owned(), "low".to_owned()],
true,
)
.set_name("priority");
assert!(categorical.is_(&categorical));
assert!(categorical.equals(&categorical.copy()));
assert!(categorical.identical(&categorical.copy()));
assert!(!categorical.identical(&categorical.rename_index(None::<&str>)));
assert!(!categorical.is_unique());
assert!(categorical.has_duplicates());
assert_eq!(categorical.nunique(), 2);
assert_eq!(categorical.ndim(), 1);
assert_eq!(
CategoricalIndex::from_values(vec!["high".to_owned()], true)
.item()
.unwrap(),
IndexLabel::from("high")
);
assert_eq!(categorical.inferred_type(), "categorical");
assert!(!categorical.holds_integer());
assert!(!categorical.is_integer());
assert!(!categorical.is_numeric());
assert!(!categorical.is_boolean());
assert!(categorical.is_categorical());
assert!(!categorical.is_floating());
assert!(!categorical.is_interval());
assert!(!categorical.is_object());
assert!(!categorical.is_monotonic_increasing());
assert!(!categorical.is_monotonic_decreasing());
assert!(
CategoricalIndex::from_values(vec!["low".to_owned(), "high".to_owned()], true)
.is_monotonic_increasing()
);
}
// === AG-13: Adaptive Index Backend Tests ===
#[test]
fn sorted_int64_index_detected() {
let index = Index::from_i64(vec![1, 2, 3, 4, 5]);
assert!(index.is_sorted());
}
#[test]
fn unsorted_int64_index_detected() {
let index = Index::from_i64(vec![3, 1, 2]);
assert!(!index.is_sorted());
}
#[test]
fn sorted_utf8_index_detected() {
let index = Index::from_utf8(vec!["a".into(), "b".into(), "c".into()]);
assert!(index.is_sorted());
}
#[test]
fn unsorted_utf8_index_detected() {
let index = Index::from_utf8(vec!["c".into(), "a".into(), "b".into()]);
assert!(!index.is_sorted());
}
#[test]
fn duplicate_int64_is_not_sorted() {
let index = Index::from_i64(vec![1, 2, 2, 3]);
assert!(!index.is_sorted());
}
#[test]
fn empty_index_is_sorted() {
let index = Index::new(vec![]);
assert!(index.is_sorted());
}
#[test]
fn single_element_is_sorted() {
let index = Index::from_i64(vec![42]);
assert!(index.is_sorted());
}
#[test]
fn binary_search_position_sorted_int64() {
let index = Index::from_i64(vec![10, 20, 30, 40, 50]);
assert_eq!(index.position(&IndexLabel::Int64(10)), Some(0));
assert_eq!(index.position(&IndexLabel::Int64(30)), Some(2));
assert_eq!(index.position(&IndexLabel::Int64(50)), Some(4));
assert_eq!(index.position(&IndexLabel::Int64(25)), None);
assert_eq!(index.position(&IndexLabel::Int64(0)), None);
assert_eq!(index.position(&IndexLabel::Int64(100)), None);
}
#[test]
fn binary_search_position_sorted_utf8() {
let index = Index::from_utf8(vec!["apple".into(), "banana".into(), "cherry".into()]);
assert_eq!(index.position(&IndexLabel::Utf8("apple".into())), Some(0));
assert_eq!(index.position(&IndexLabel::Utf8("banana".into())), Some(1));
assert_eq!(index.position(&IndexLabel::Utf8("cherry".into())), Some(2));
assert_eq!(index.position(&IndexLabel::Utf8("date".into())), None);
}
#[test]
fn type_mismatch_returns_none() {
let int_index = Index::from_i64(vec![1, 2, 3]);
// Looking for a Utf8 needle in an Int64 index
assert_eq!(int_index.position(&IndexLabel::Utf8("1".into())), None);
let utf8_index = Index::from_utf8(vec!["a".into(), "b".into()]);
// Looking for an Int64 needle in a Utf8 index
assert_eq!(utf8_index.position(&IndexLabel::Int64(1)), None);
}
#[test]
fn linear_fallback_for_unsorted_index() {
let index = Index::from_i64(vec![30, 10, 20]);
assert!(!index.is_sorted());
assert_eq!(index.position(&IndexLabel::Int64(30)), Some(0));
assert_eq!(index.position(&IndexLabel::Int64(10)), Some(1));
assert_eq!(index.position(&IndexLabel::Int64(20)), Some(2));
assert_eq!(index.position(&IndexLabel::Int64(99)), None);
}
#[test]
fn binary_search_large_sorted_index() {
// Verify binary search works correctly on a large sorted index.
let labels: Vec<i64> = (0..10_000).collect();
let index = Index::from_i64(labels);
assert!(index.is_sorted());
// Check first, middle, last, and missing positions.
assert_eq!(index.position(&IndexLabel::Int64(0)), Some(0));
assert_eq!(index.position(&IndexLabel::Int64(5000)), Some(5000));
assert_eq!(index.position(&IndexLabel::Int64(9999)), Some(9999));
assert_eq!(index.position(&IndexLabel::Int64(10_000)), None);
assert_eq!(index.position(&IndexLabel::Int64(-1)), None);
}
#[test]
fn sort_detection_is_cached() {
let index = Index::from_i64(vec![1, 2, 3]);
// First call computes and caches.
assert!(index.is_sorted());
// Second call should return same result from cache.
assert!(index.is_sorted());
}
#[test]
fn mixed_label_types_are_unsorted() {
let index = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Utf8("a".into())]);
assert!(!index.is_sorted());
}
#[test]
fn position_consistent_sorted_vs_unsorted() {
// Verify that for a sorted index, binary search gives the same
// results as a linear scan would.
let sorted = Index::from_i64(vec![5, 10, 15, 20, 25]);
assert!(sorted.is_sorted());
for &target in &[5, 10, 15, 20, 25, 0, 12, 30] {
let needle = IndexLabel::Int64(target);
let expected = sorted.labels().iter().position(|l| l == &needle);
assert_eq!(
sorted.position(&needle),
expected,
"mismatch for target={target}"
);
}
}
// === bd-2gi.15: Alignment mode tests ===
use super::{AlignMode, align, align_inner, align_left};
#[test]
fn align_inner_keeps_only_overlapping_labels() {
let left = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
let right = Index::new(vec![2_i64.into(), 3_i64.into(), 4_i64.into()]);
let plan = align_inner(&left, &right);
assert_eq!(
plan.union_index.labels(),
&[IndexLabel::Int64(2), IndexLabel::Int64(3)]
);
assert_eq!(plan.left_positions, vec![Some(1), Some(2)]);
assert_eq!(plan.right_positions, vec![Some(0), Some(1)]);
validate_alignment_plan(&plan).expect("valid");
}
#[test]
fn align_inner_disjoint_yields_empty() {
let left = Index::new(vec![1_i64.into(), 2_i64.into()]);
let right = Index::new(vec![3_i64.into(), 4_i64.into()]);
let plan = align_inner(&left, &right);
assert!(plan.union_index.is_empty());
assert!(plan.left_positions.is_empty());
assert!(plan.right_positions.is_empty());
}
#[test]
fn align_left_preserves_all_left_labels() {
let left = Index::new(vec!["a".into(), "b".into(), "c".into()]);
let right = Index::new(vec!["b".into(), "d".into()]);
let plan = align_left(&left, &right);
assert_eq!(
plan.union_index.labels(),
&["a".into(), "b".into(), "c".into()]
);
assert_eq!(plan.left_positions, vec![Some(0), Some(1), Some(2)]);
assert_eq!(plan.right_positions, vec![None, Some(0), None]);
validate_alignment_plan(&plan).expect("valid");
}
#[test]
fn align_right_preserves_all_right_labels() {
let left = Index::new(vec!["a".into(), "b".into()]);
let right = Index::new(vec!["b".into(), "c".into(), "d".into()]);
let plan = align(&left, &right, AlignMode::Right);
assert_eq!(
plan.union_index.labels(),
&["b".into(), "c".into(), "d".into()]
);
// Left has "b" at position 1.
assert_eq!(plan.left_positions, vec![Some(1), None, None]);
assert_eq!(plan.right_positions, vec![Some(0), Some(1), Some(2)]);
}
#[test]
fn align_mode_outer_matches_union() {
let left = Index::new(vec![1_i64.into(), 2_i64.into()]);
let right = Index::new(vec![2_i64.into(), 3_i64.into()]);
let plan_outer = align(&left, &right, AlignMode::Outer);
let plan_union = align_union(&left, &right);
assert_eq!(plan_outer, plan_union);
}
#[test]
fn align_inner_duplicate_labels_cartesian() {
let left = Index::new(vec!["a".into(), "b".into(), "a".into()]);
let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
let plan = align_inner(&left, &right);
assert_eq!(
plan.union_index.labels(),
&["a".into(), "a".into(), "a".into(), "a".into()]
);
assert_eq!(
plan.left_positions,
vec![Some(0), Some(0), Some(2), Some(2)]
);
assert_eq!(
plan.right_positions,
vec![Some(0), Some(1), Some(0), Some(1)]
);
validate_alignment_plan(&plan).expect("valid");
}
#[test]
fn align_left_duplicate_labels_expand_right_matches() {
let left = Index::new(vec!["a".into(), "b".into(), "a".into()]);
let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
let plan = align_left(&left, &right);
assert_eq!(
plan.union_index.labels(),
&["a".into(), "a".into(), "b".into(), "a".into(), "a".into()]
);
assert_eq!(
plan.left_positions,
vec![Some(0), Some(0), Some(1), Some(2), Some(2)]
);
assert_eq!(
plan.right_positions,
vec![Some(0), Some(1), None, Some(0), Some(1)]
);
validate_alignment_plan(&plan).expect("valid");
}
#[test]
fn align_right_duplicate_labels_expand_left_matches() {
let left = Index::new(vec!["a".into(), "b".into(), "a".into()]);
let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
let plan = align(&left, &right, AlignMode::Right);
assert_eq!(
plan.union_index.labels(),
&["a".into(), "a".into(), "a".into(), "a".into(), "c".into()]
);
assert_eq!(
plan.left_positions,
vec![Some(0), Some(2), Some(0), Some(2), None]
);
assert_eq!(
plan.right_positions,
vec![Some(0), Some(0), Some(1), Some(1), Some(2)]
);
validate_alignment_plan(&plan).expect("valid");
}
#[test]
fn align_outer_duplicate_labels_preserves_left_order_and_right_only() {
let left = Index::new(vec!["a".into(), "b".into(), "a".into()]);
let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
let plan = align_union(&left, &right);
assert_eq!(
plan.union_index.labels(),
&[
"a".into(),
"a".into(),
"b".into(),
"a".into(),
"a".into(),
"c".into()
]
);
assert_eq!(
plan.left_positions,
vec![Some(0), Some(0), Some(1), Some(2), Some(2), None]
);
assert_eq!(
plan.right_positions,
vec![Some(0), Some(1), None, Some(0), Some(1), Some(2)]
);
validate_alignment_plan(&plan).expect("valid");
}
#[test]
fn align_inner_identical_indexes() {
let left = Index::new(vec!["x".into(), "y".into()]);
let right = Index::new(vec!["x".into(), "y".into()]);
let plan = align_inner(&left, &right);
assert_eq!(plan.union_index.labels(), &["x".into(), "y".into()]);
assert_eq!(plan.left_positions, vec![Some(0), Some(1)]);
assert_eq!(plan.right_positions, vec![Some(0), Some(1)]);
}
#[test]
fn align_left_identical_indexes() {
let left = Index::new(vec![1_i64.into(), 2_i64.into()]);
let right = Index::new(vec![1_i64.into(), 2_i64.into()]);
let plan = align_left(&left, &right);
assert_eq!(plan.union_index.labels(), left.labels());
assert_eq!(plan.left_positions, vec![Some(0), Some(1)]);
assert_eq!(plan.right_positions, vec![Some(0), Some(1)]);
}
#[test]
fn align_inner_empty_input() {
let left = Index::new(Vec::new());
let right = Index::new(vec![1_i64.into()]);
let plan = align_inner(&left, &right);
assert!(plan.union_index.is_empty());
}
#[test]
fn align_left_empty_left() {
let left = Index::new(Vec::new());
let right = Index::new(vec![1_i64.into()]);
let plan = align_left(&left, &right);
assert!(plan.union_index.is_empty());
}
// === bd-2gi.13: Index model and indexer semantics ===
use super::DuplicateKeep;
#[test]
fn contains_finds_existing_label() {
let index = Index::from_i64(vec![10, 20, 30]);
assert!(index.contains(&IndexLabel::Int64(20)));
assert!(!index.contains(&IndexLabel::Int64(99)));
}
#[test]
fn get_indexer_bulk_lookup() {
let index = Index::new(vec!["a".into(), "b".into(), "c".into()]);
let target = Index::new(vec!["c".into(), "a".into(), "z".into()]);
assert_eq!(index.get_indexer(&target), vec![Some(2), Some(0), None]);
}
#[test]
fn isin_membership_mask() {
let index = Index::from_i64(vec![1, 2, 3, 4, 5]);
let values = vec![IndexLabel::Int64(2), IndexLabel::Int64(4)];
assert_eq!(index.isin(&values), vec![false, true, false, true, false]);
}
#[test]
fn unique_preserves_first_seen_order() {
let index = Index::new(vec![
"b".into(),
"a".into(),
"b".into(),
"c".into(),
"a".into(),
]);
let uniq = index.unique();
assert_eq!(uniq.labels(), &["b".into(), "a".into(), "c".into()]);
}
#[test]
fn duplicated_keep_first() {
let index = Index::from_i64(vec![1, 2, 1, 3, 2]);
assert_eq!(
index.duplicated(DuplicateKeep::First),
vec![false, false, true, false, true]
);
}
#[test]
fn duplicated_keep_last() {
let index = Index::from_i64(vec![1, 2, 1, 3, 2]);
assert_eq!(
index.duplicated(DuplicateKeep::Last),
vec![true, true, false, false, false]
);
}
#[test]
fn duplicated_keep_none_marks_all() {
let index = Index::from_i64(vec![1, 2, 1, 3, 2]);
assert_eq!(
index.duplicated(DuplicateKeep::None),
vec![true, true, true, false, true]
);
}
#[test]
fn drop_duplicates_equals_unique() {
let index = Index::from_i64(vec![3, 1, 3, 2, 1]);
assert_eq!(index.drop_duplicates(), index.unique());
}
#[test]
fn index_drop_duplicates_keep_last() {
let index = Index::new(vec![
"llama".into(),
"cow".into(),
"llama".into(),
"beetle".into(),
"llama".into(),
"hippo".into(),
])
.set_names(Some("animals"));
let deduped = index.drop_duplicates_keep(DuplicateKeep::Last);
assert_eq!(
deduped.labels(),
&[
IndexLabel::from("cow"),
IndexLabel::from("beetle"),
IndexLabel::from("llama"),
IndexLabel::from("hippo"),
]
);
assert_eq!(deduped.name().map(|n| n.as_str()), Some("animals"));
}
#[test]
fn index_drop_duplicates_keep_none_discards_all_duplicates() {
let index = Index::new(vec![
"llama".into(),
"cow".into(),
"llama".into(),
"beetle".into(),
"llama".into(),
"hippo".into(),
]);
let deduped = index.drop_duplicates_keep(DuplicateKeep::None);
assert_eq!(
deduped.labels(),
&[
IndexLabel::from("cow"),
IndexLabel::from("beetle"),
IndexLabel::from("hippo"),
]
);
}
#[test]
fn intersection_preserves_left_order() {
let left = Index::new(vec!["c".into(), "a".into(), "b".into()]);
let right = Index::new(vec!["b".into(), "d".into(), "a".into()]);
let result = left.intersection(&right);
assert_eq!(result.labels(), &["a".into(), "b".into()]);
}
#[test]
fn intersection_deduplicates() {
let left = Index::from_i64(vec![1, 1, 2]);
let right = Index::from_i64(vec![1, 2, 2]);
let result = left.intersection(&right);
assert_eq!(
result.labels(),
&[IndexLabel::Int64(1), IndexLabel::Int64(2)]
);
}
#[test]
fn union_with_combines_unique_labels() {
let left = Index::from_i64(vec![1, 2, 3]);
let right = Index::from_i64(vec![2, 4, 3]);
let result = left.union_with(&right);
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
]
);
}
#[test]
fn union_with_preserves_maximum_duplicate_multiplicity_lerb2() {
// pandas 2.2.3: Index([3, 1, 2, 1]).union(Index([2, 4, 2]),
// sort=False) -> [3, 1, 1, 2, 2, 4]. The output is neither a
// deduplicated set nor a concatenation: labels are first-seen ordered,
// then repeated by the larger input multiplicity.
let left = Index::from_i64_values(vec![3, 1, 2, 1]);
let right = Index::from_i64_values(vec![2, 4, 2]);
let result = left.union_with(&right);
assert_eq!(
result.labels.int64_view().unwrap().as_slice(),
&[3, 1, 1, 2, 2, 4]
);
assert_ne!(
result.labels.int64_view().unwrap().as_slice(),
&[3, 1, 2, 1, 2, 4, 2],
"negative: union must not concatenate the duplicate-bearing inputs"
);
}
#[test]
fn union_with_preserves_utf8_duplicate_multiplicity_lerb2() {
let left = Index::new(vec!["b".into(), "a".into(), "b".into()]);
let right = Index::new(vec!["a".into(), "a".into(), "c".into()]);
assert_eq!(
left.union_with(&right).labels(),
&[
IndexLabel::Utf8("b".to_owned()),
IndexLabel::Utf8("b".to_owned()),
IndexLabel::Utf8("a".to_owned()),
IndexLabel::Utf8("a".to_owned()),
IndexLabel::Utf8("c".to_owned()),
]
);
}
#[test]
fn difference_removes_other_labels() {
let left = Index::from_i64(vec![1, 2, 3, 4]);
let right = Index::from_i64(vec![2, 4]);
let result = left.difference(&right);
assert_eq!(
result.labels(),
&[IndexLabel::Int64(1), IndexLabel::Int64(3)]
);
}
#[test]
fn difference_preserves_self_name_even_when_other_differs_6r1lq() {
// Per br-frankenpandas-6r1lq: difference is asymmetric — pandas
// preserves self.name regardless of whether other has the same name.
let left = Index::from_i64(vec![1, 2, 3]).set_name("left_axis");
let right = Index::from_i64(vec![2, 3, 4]).set_name("right_axis");
let result = left.difference(&right);
assert_eq!(result.name().map(|n| n.as_str()), Some("left_axis"));
}
#[test]
fn symmetric_difference_xor() {
let left = Index::from_i64(vec![1, 2, 3]);
let right = Index::from_i64(vec![2, 3, 4]);
let result = left.symmetric_difference(&right);
assert_eq!(
result.labels(),
&[IndexLabel::Int64(1), IndexLabel::Int64(4)]
);
}
#[test]
fn argsort_returns_sorting_indices() {
let index = Index::from_i64(vec![30, 10, 20]);
assert_eq!(index.argsort(), vec![1, 2, 0]);
}
/// `get_loc_all` returns the position SET that pandas encodes three ways.
///
/// br-frankenpandas-lerb2. `pd.Index.get_loc` returns an int, a slice, or a
/// boolean mask depending on whether the index is unique and monotonic; all
/// three describe the same set of positions, and `get_loc` here can only ever
/// answer with one of them.
///
/// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
/// ```text
/// [10,20,30] get_loc(20) -> 1 => [1]
/// [10,20,20,30] get_loc(20) -> slice(1, 3) => [1, 2]
/// [20,10,20] get_loc(20) -> array([True,False,True]) => [0, 2]
/// [10,20] get_loc(99) -> KeyError => []
/// [1.0,NaN,2.0,NaN] get_loc(NaN) -> array([F,True,F,True]) => [1, 3]
/// ```
#[test]
fn get_loc_all_returns_every_position_lerb2() {
assert_eq!(
Index::from_i64(vec![10, 20, 30]).get_loc_all(&IndexLabel::Int64(20)),
vec![1]
);
// ⚠️ The duplicate rows are the point: `get_loc` collapses each of these to a
// single position, which is why they need their own accessor.
assert_eq!(
Index::from_i64(vec![10, 20, 20, 30]).get_loc_all(&IndexLabel::Int64(20)),
vec![1, 2]
);
assert_eq!(
Index::from_i64(vec![20, 10, 20]).get_loc_all(&IndexLabel::Int64(20)),
vec![0, 2]
);
// Missing is EMPTY, not an error — this crate's get_loc returns Option, so
// an absent key is not exceptional here the way pandas' KeyError is.
assert!(
Index::from_i64(vec![10, 20])
.get_loc_all(&IndexLabel::Int64(99))
.is_empty()
);
// ⚠️ NaN is findable, because OrderedF64 compares on a canonical bit pattern.
// A derived PartialEq over raw f64 would make this row return [] instead.
let floats = Index::new(vec![
IndexLabel::Float64(OrderedF64(1.0)),
IndexLabel::Float64(OrderedF64(f64::NAN)),
IndexLabel::Float64(OrderedF64(2.0)),
IndexLabel::Float64(OrderedF64(f64::NAN)),
]);
assert_eq!(
floats.get_loc_all(&IndexLabel::Float64(OrderedF64(f64::NAN))),
vec![1, 3]
);
}
/// `asof` on a NON-MONOTONIC index: FrankenPandas answers, pandas refuses.
///
/// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-19), `pd.Index([30,10,20])`:
/// every `.asof(k)` raises `ValueError: index must be monotonic increasing or
/// decreasing`. FrankenPandas returns `None` instead, because the scan breaks at
/// the first label greater than the key — it stops at 30 and never reaches the 20
/// that actually precedes 25.
///
/// ⚠️ THIS PINS FrankenPandas' ANSWER, NOT pandas'. It exists so the divergence is
/// visible and deliberate rather than discovered later: matching pandas means
/// raising, and `asof` returns `Option`, not `Result`. If that signature ever
/// changes, this test should change with it — do not read it as parity evidence.
#[test]
fn asof_on_a_non_monotonic_index_is_a_documented_divergence() {
let unsorted = Index::from_i64(vec![30, 10, 20]);
assert!(
!unsorted.is_sorted(),
"precondition: the index is non-monotonic"
);
// pandas: ValueError. Here: None, because the scan stops at 30.
assert_eq!(unsorted.asof(&IndexLabel::Int64(25)), None);
assert_eq!(unsorted.asof(&IndexLabel::Int64(5)), None);
// ⚠️ And the answer is not merely "conservative": 20 DOES precede 25 and is
// present in the index. Sorting first is what makes the lookup meaningful.
let sorted = unsorted.sort_values();
assert_eq!(
sorted.asof(&IndexLabel::Int64(25)),
Some(IndexLabel::Int64(20)),
"after sorting, the preceding label is found"
);
}
#[test]
fn int64_argsort_is_stable_and_keeps_typed_backing_6ubrp() {
let index = Index::from_i64_values(vec![3, 1, 2, 1, 3]);
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.argsort(), vec![1, 3, 2, 0, 4]);
assert!(
index.labels.materialized.get().is_none(),
"typed Int64 argsort should not materialize IndexLabel values"
);
}
#[test]
fn descending_int64_affine_argsort_does_not_materialize_6ubrp() {
let index = Index::new_known_unique_int64_affine_range(10, -2, 4).unwrap();
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.argsort(), vec![3, 2, 1, 0]);
assert!(
index.labels.materialized.get().is_none(),
"affine Int64 argsort should not materialize IndexLabel values"
);
}
#[test]
fn sort_values_produces_sorted_index() {
let index = Index::new(vec!["c".into(), "a".into(), "b".into()]);
let sorted = index.sort_values();
assert_eq!(sorted.labels(), &["a".into(), "b".into(), "c".into()]);
}
#[test]
fn int64_sort_values_preserves_name_and_stable_duplicates_6ubrp() {
let index = Index::from_i64_values(vec![3, 1, 2, 1, 3]).set_name("rows");
let sorted = index.sort_values();
assert_eq!(sorted.name().map(|n| n.as_str()), Some("rows"));
assert_eq!(
sorted.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(3),
]
);
}
#[test]
fn descending_int64_affine_sort_values_reuses_affine_backing_6ubrp() {
let index = Index::new_known_unique_int64_affine_range(10, -2, 4)
.unwrap()
.set_name("axis");
let sorted = index.sort_values();
assert_eq!(sorted.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
sorted.labels.int64_affine_range(),
Some(Int64AffineLabels {
start: 4,
step: 2,
len: 4
})
);
assert!(
sorted.labels.materialized.get().is_none(),
"descending affine sort_values should keep affine Int64 backing"
);
assert_eq!(
sorted.labels(),
&[
IndexLabel::Int64(4),
IndexLabel::Int64(6),
IndexLabel::Int64(8),
IndexLabel::Int64(10),
]
);
}
#[test]
fn take_selects_by_position() {
let index = Index::from_i64(vec![10, 20, 30, 40, 50]);
let taken = index.take(&[4, 0, 2]);
assert_eq!(
taken.labels(),
&[
IndexLabel::Int64(50),
IndexLabel::Int64(10),
IndexLabel::Int64(30),
]
);
}
#[test]
fn int64_take_preserves_typed_backing_without_materializing_vbmsv() {
let index = Index::from_i64_values(vec![10, 20, 30, 40]).set_name("rows");
assert!(index.labels.materialized.get().is_none());
let taken = index.take(&[2, 0, 2]);
assert_eq!(taken.name().map(|n| n.as_str()), Some("rows"));
assert_eq!(taken.labels.int64_view().unwrap().as_slice(), &[30, 10, 30]);
assert!(index.labels.materialized.get().is_none());
assert!(
taken.labels.materialized.get().is_none(),
"typed Int64 take should keep typed output backing"
);
}
#[test]
fn affine_int64_take_gathers_raw_values_without_materializing_vbmsv() {
let index = Index::new_known_unique_int64_affine_range(5, 3, 4)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let taken = index.take(&[3, 1]);
assert_eq!(taken.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(taken.labels.int64_view().unwrap().as_slice(), &[14, 8]);
assert!(index.labels.materialized.get().is_none());
assert!(
taken.labels.materialized.get().is_none(),
"affine Int64 take should gather into typed output backing"
);
}
#[test]
fn slice_extracts_subrange() {
let index = Index::from_i64(vec![10, 20, 30, 40, 50]);
let sliced = index.slice(1, 3);
assert_eq!(
sliced.labels(),
&[
IndexLabel::Int64(20),
IndexLabel::Int64(30),
IndexLabel::Int64(40),
]
);
}
#[test]
fn slice_of_materialized_index_keeps_shared_label_view() {
let index = Index::new(vec![
IndexLabel::Utf8("a".into()),
IndexLabel::Utf8("b".into()),
IndexLabel::Utf8("c".into()),
IndexLabel::Utf8("d".into()),
]);
let sliced = index.slice(1, 2);
assert!(sliced.labels.materialized_slice.is_some());
assert!(sliced.labels.materialized.get().is_none());
assert_eq!(
sliced.labels(),
&[IndexLabel::Utf8("b".into()), IndexLabel::Utf8("c".into()),]
);
}
#[test]
fn slice_clamps_to_bounds() {
let index = Index::from_i64(vec![1, 2, 3]);
let sliced = index.slice(1, 100);
assert_eq!(
sliced.labels(),
&[IndexLabel::Int64(2), IndexLabel::Int64(3)]
);
}
#[test]
fn from_range_basic() {
let index = Index::from_range(0, 5, 1);
assert_eq!(
index.labels.int64_affine_range(),
Some(Int64AffineLabels {
start: 0,
step: 1,
len: 5
})
);
assert!(
index.labels.materialized.get().is_none(),
"from_range should keep unit Int64 range labels lazy"
);
assert_eq!(
index.labels(),
&[
IndexLabel::Int64(0),
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
]
);
}
#[test]
fn from_range_step_2() {
let index = Index::from_range(0, 10, 3);
assert_eq!(
index.labels.int64_affine_range(),
Some(Int64AffineLabels {
start: 0,
step: 3,
len: 4
})
);
assert!(
index.labels.materialized.get().is_none(),
"from_range should keep strided Int64 labels lazy"
);
assert_eq!(
index.labels(),
&[
IndexLabel::Int64(0),
IndexLabel::Int64(3),
IndexLabel::Int64(6),
IndexLabel::Int64(9),
]
);
}
#[test]
fn from_range_negative_step() {
let index = Index::from_range(5, 0, -2);
assert_eq!(
index.labels.int64_affine_range(),
Some(Int64AffineLabels {
start: 5,
step: -2,
len: 3
})
);
assert!(
index.labels.materialized.get().is_none(),
"from_range should keep descending Int64 labels lazy"
);
assert_eq!(
index.labels(),
&[
IndexLabel::Int64(5),
IndexLabel::Int64(3),
IndexLabel::Int64(1),
]
);
}
#[test]
fn from_range_empty_when_step_zero() {
let index = Index::from_range(0, 5, 0);
assert_eq!(
index.labels.int64_affine_range(),
Some(Int64AffineLabels {
start: 0,
step: 0,
len: 0
})
);
assert!(
index.labels.materialized.get().is_none(),
"from_range step=0 should keep empty Int64 labels lazy"
);
assert!(index.is_empty());
}
#[test]
fn set_ops_empty_inputs() {
let empty = Index::new(Vec::new());
let non_empty = Index::from_i64(vec![1, 2]);
assert!(empty.intersection(&non_empty).is_empty());
assert_eq!(empty.union_with(&non_empty), non_empty);
assert!(empty.difference(&non_empty).is_empty());
assert_eq!(empty.symmetric_difference(&non_empty), non_empty);
}
#[test]
fn int64_set_ops_match_pandas_reference_c6wel() {
fn labels_i64(index: &Index) -> Vec<i64> {
let mut out = Vec::with_capacity(index.len());
for label in index.labels() {
if let IndexLabel::Int64(value) = label {
out.push(*value);
} else {
out.push(i64::MIN);
}
}
out
}
fn intersection_ref(a: &[i64], b: &[i64]) -> Vec<i64> {
let bset: std::collections::BTreeSet<i64> = b.iter().copied().collect();
let mut seen = std::collections::BTreeSet::new();
let mut out = Vec::new();
for &value in a {
if bset.contains(&value) && seen.insert(value) {
out.push(value);
}
}
out
}
fn union_ref(a: &[i64], b: &[i64]) -> Vec<i64> {
let b_unique = b
.iter()
.copied()
.collect::<std::collections::BTreeSet<_>>()
.len()
== b.len();
if b_unique {
let mut out = a.to_vec();
let mut seen = a.iter().copied().collect::<std::collections::BTreeSet<_>>();
for &value in b {
if seen.insert(value) {
out.push(value);
}
}
return out;
}
let mut counts = std::collections::BTreeMap::<i64, (usize, usize)>::new();
let mut order = Vec::new();
for &value in a {
let entry = counts.entry(value).or_insert((0, 0));
if entry.0 == 0 && entry.1 == 0 {
order.push(value);
}
entry.0 += 1;
}
for &value in b {
let entry = counts.entry(value).or_insert((0, 0));
if entry.0 == 0 && entry.1 == 0 {
order.push(value);
}
entry.1 += 1;
}
let mut out = Vec::with_capacity(super::combined_output_capacity(a.len(), b.len()));
for value in order {
let (left_count, right_count) = counts[&value];
out.extend(std::iter::repeat_n(value, left_count.max(right_count)));
}
out
}
fn difference_ref(a: &[i64], b: &[i64]) -> Vec<i64> {
let bset: std::collections::BTreeSet<i64> = b.iter().copied().collect();
let mut seen = std::collections::BTreeSet::new();
let mut out = Vec::new();
for &value in a {
if !bset.contains(&value) && seen.insert(value) {
out.push(value);
}
}
out
}
fn symmetric_difference_ref(a: &[i64], b: &[i64]) -> Vec<i64> {
let aset: std::collections::BTreeSet<i64> = a.iter().copied().collect();
let bset: std::collections::BTreeSet<i64> = b.iter().copied().collect();
let mut seen = std::collections::BTreeSet::new();
let mut out = Vec::new();
for &value in a {
if !bset.contains(&value) && seen.insert(value) {
out.push(value);
}
}
for &value in b {
if !aset.contains(&value) && seen.insert(value) {
out.push(value);
}
}
out
}
let mut state: u64 = 0xc6e1_f157_e700_0001;
let mut next = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
u32::try_from(state >> 33).unwrap_or(0)
};
let values = |len: usize, next: &mut dyn FnMut() -> u32| {
let mut vals: Vec<i64> = (0..len).map(|_| i64::from(next() % 11) - 5).collect();
match next() % 5 {
0 => vals.sort_unstable(),
1 => vals.sort_unstable_by(|a, b| b.cmp(a)),
2 if vals.len() > 1 => {
let shift = usize::try_from(next()).unwrap_or(0) % vals.len();
vals.rotate_left(shift);
}
_ => {}
}
vals
};
for iter in 0..2500u32 {
let a = values(usize::try_from(next() % 15).unwrap_or(0), &mut next);
let b = values(usize::try_from(next() % 15).unwrap_or(0), &mut next);
let ia = Index::from_i64_values(a.clone());
let ib = Index::from_i64_values(b.clone());
assert_eq!(
labels_i64(&ia.intersection(&ib)),
intersection_ref(&a, &b),
"intersection iter={iter} a={a:?} b={b:?}"
);
assert_eq!(
labels_i64(&ia.union_with(&ib)),
union_ref(&a, &b),
"union iter={iter} a={a:?} b={b:?}"
);
assert_eq!(
labels_i64(&ia.difference(&ib)),
difference_ref(&a, &b),
"difference iter={iter} a={a:?} b={b:?}"
);
assert_eq!(
labels_i64(&ia.symmetric_difference(&ib)),
symmetric_difference_ref(&a, &b),
"symmetric_difference iter={iter} a={a:?} b={b:?}"
);
}
}
#[test]
fn unsorted_int64_set_ops_keep_typed_backing_without_materializing_m8x4p() {
let left = Index::from_i64_values(vec![3, 1, 3, 2]).set_name("axis");
let right = Index::from_i64_values(vec![2, 4, 1]).set_name("axis");
assert!(left.labels.materialized.get().is_none());
assert!(right.labels.materialized.get().is_none());
let intersection = left.intersection(&right);
let union = left.union_with(&right);
let difference = left.difference(&right);
let symmetric = left.symmetric_difference(&right);
assert_eq!(intersection.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(union.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(difference.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(symmetric.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
intersection.labels.int64_view().unwrap().as_slice(),
&[1, 2]
);
assert_eq!(
union.labels.int64_view().unwrap().as_slice(),
&[3, 1, 3, 2, 4],
"pandas preserves the duplicate left occurrence when the right index is unique"
);
assert_ne!(
union.labels.int64_view().unwrap().as_slice(),
&[3, 3, 1, 2, 4],
"negative: grouping left duplicates by label is not pandas union ordering"
);
assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[3]);
assert_eq!(symmetric.labels.int64_view().unwrap().as_slice(), &[3, 4]);
assert!(
left.labels.materialized.get().is_none(),
"hash Int64 set ops should not materialize the left input"
);
assert!(
right.labels.materialized.get().is_none(),
"hash Int64 set ops should not materialize the right input"
);
for output in [&intersection, &union, &difference, &symmetric] {
assert!(
output.labels.materialized.get().is_none(),
"Int64 set op output should stay typed"
);
}
}
// === AG-11: Leapfrog Triejoin Tests ===
use super::{leapfrog_intersection, leapfrog_union, multi_way_align};
#[test]
fn leapfrog_union_three_indexes() {
let a = Index::from_i64(vec![1, 3, 5]);
let b = Index::from_i64(vec![2, 3, 6]);
let c = Index::from_i64(vec![4, 5, 6]);
let result = leapfrog_union(&[&a, &b, &c]);
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
IndexLabel::Int64(5),
IndexLabel::Int64(6),
]
);
}
#[test]
fn leapfrog_union_deduplicates() {
let a = Index::from_i64(vec![1, 1, 2]);
let b = Index::from_i64(vec![2, 2, 3]);
let result = leapfrog_union(&[&a, &b]);
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
]
);
}
#[test]
fn leapfrog_union_single_index() {
let a = Index::from_i64(vec![3, 1, 2]);
let result = leapfrog_union(&[&a]);
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
]
);
}
#[test]
fn leapfrog_union_empty() {
let result = leapfrog_union(&[]);
assert!(result.is_empty());
}
#[test]
fn leapfrog_union_with_empty_input() {
let a = Index::from_i64(vec![1, 2]);
let b = Index::new(Vec::new());
let result = leapfrog_union(&[&a, &b]);
assert_eq!(
result.labels(),
&[IndexLabel::Int64(1), IndexLabel::Int64(2)]
);
}
#[test]
fn leapfrog_intersection_three_indexes() {
let a = Index::from_i64(vec![1, 2, 3, 4, 5]);
let b = Index::from_i64(vec![2, 3, 5, 7]);
let c = Index::from_i64(vec![3, 5, 8]);
let result = leapfrog_intersection(&[&a, &b, &c]);
assert_eq!(
result.labels(),
&[IndexLabel::Int64(3), IndexLabel::Int64(5)]
);
}
#[test]
fn leapfrog_intersection_disjoint() {
let a = Index::from_i64(vec![1, 2]);
let b = Index::from_i64(vec![3, 4]);
let result = leapfrog_intersection(&[&a, &b]);
assert!(result.is_empty());
}
#[test]
fn leapfrog_intersection_identical() {
let a = Index::from_i64(vec![1, 2, 3]);
let b = Index::from_i64(vec![1, 2, 3]);
let result = leapfrog_intersection(&[&a, &b]);
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
]
);
}
#[test]
fn leapfrog_intersection_with_unsorted_input() {
let a = Index::from_i64(vec![5, 3, 1, 4, 2]);
let b = Index::from_i64(vec![4, 2, 6, 1]);
let result = leapfrog_intersection(&[&a, &b]);
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(4),
]
);
}
#[test]
fn leapfrog_intersection_empty_input() {
let a = Index::from_i64(vec![1, 2, 3]);
let b = Index::new(Vec::new());
let result = leapfrog_intersection(&[&a, &b]);
assert!(result.is_empty());
}
#[test]
fn multi_way_align_three_indexes() {
let a = Index::from_i64(vec![1, 3]);
let b = Index::from_i64(vec![2, 3]);
let c = Index::from_i64(vec![1, 2]);
assert_eq!(
super::aggregate_output_capacity([a.len(), b.len(), c.len()]),
6
);
let plan = multi_way_align(&[&a, &b, &c]);
assert_eq!(
plan.union_index.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(2),
]
);
assert_eq!(plan.positions.len(), 3);
// a has 1 at pos 0, 3 at pos 1, no 2
assert_eq!(plan.positions[0], vec![Some(0), Some(1), None]);
// b has no 1, 3 at pos 1, 2 at pos 0
assert_eq!(plan.positions[1], vec![None, Some(1), Some(0)]);
// c has 1 at pos 0, no 3, 2 at pos 1
assert_eq!(plan.positions[2], vec![Some(0), None, Some(1)]);
}
#[test]
fn multi_way_align_deduplicates_repeated_labels_uza04186() {
let a = Index::from_i64(vec![1, 1, 3]);
let b = Index::from_i64(vec![3, 2, 2]);
let plan = multi_way_align(&[&a, &b]);
assert_eq!(
plan.union_index.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(2)
]
);
assert_eq!(plan.positions[0], vec![Some(0), Some(2), None]);
assert_eq!(plan.positions[1], vec![None, Some(0), Some(1)]);
}
#[test]
fn multi_way_align_empty() {
let plan = multi_way_align(&[]);
assert!(plan.union_index.is_empty());
assert!(plan.positions.is_empty());
}
#[test]
fn multi_way_align_isomorphic_with_pairwise() {
// AG-11 contract: multi-way union produces same label set as
// iterative pairwise union (associativity + commutativity).
let a = Index::from_i64(vec![1, 4, 7]);
let b = Index::from_i64(vec![2, 4, 8]);
let c = Index::from_i64(vec![3, 7, 8]);
let multi = leapfrog_union(&[&a, &b, &c]);
// Iterative pairwise
let ab = a.union_with(&b);
let abc = ab.union_with(&c);
let pairwise = abc.sort_values();
assert_eq!(multi.labels(), pairwise.labels());
}
#[test]
fn leapfrog_union_utf8_labels() {
let a = Index::new(vec!["c".into(), "a".into()]);
let b = Index::new(vec!["b".into(), "d".into()]);
let result = leapfrog_union(&[&a, &b]);
assert_eq!(
result.labels(),
&["a".into(), "b".into(), "c".into(), "d".into()]
);
}
#[test]
fn leapfrog_large_multi_way() {
// 5 indexes, each 1000 labels, overlapping ranges
let indexes: Vec<Index> = (0..5)
.map(|i| {
let start = i * 200;
let end = start + 1000;
Index::from_i64((start..end).collect())
})
.collect();
let refs: Vec<&Index> = indexes.iter().collect();
let union = leapfrog_union(&refs);
// Range is 0..1800 (0-999, 200-1199, 400-1399, 600-1599, 800-1799)
assert_eq!(union.len(), 1800);
let intersection = leapfrog_intersection(&refs);
// Intersection is 800..999 (all 5 overlap)
assert_eq!(intersection.len(), 200);
}
// === AG-11-T: Full test plan (bd-2t5e.17) ===
#[test]
fn ag11t_two_sorted_identical() {
let a = Index::from_i64(vec![1, 2, 3]);
let b = Index::from_i64(vec![1, 2, 3]);
let result = leapfrog_union(&[&a, &b]);
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3)
]
);
let plan = multi_way_align(&[&a, &b]);
// Both map to identity positions
assert_eq!(plan.positions[0], vec![Some(0), Some(1), Some(2)]);
assert_eq!(plan.positions[1], vec![Some(0), Some(1), Some(2)]);
eprintln!("[AG-11-T] two_sorted_identical | in=[3,3] out=3 | PASS");
}
#[test]
fn ag11t_two_sorted_disjoint() {
let a = Index::from_i64(vec![1, 2, 3]);
let b = Index::from_i64(vec![4, 5, 6]);
let result = leapfrog_union(&[&a, &b]);
assert_eq!(result.len(), 6);
assert_eq!(result.labels()[0], IndexLabel::Int64(1));
assert_eq!(result.labels()[5], IndexLabel::Int64(6));
eprintln!("[AG-11-T] two_sorted_disjoint | in=[3,3] out=6 | PASS");
}
#[test]
fn ag11t_two_sorted_overlapping_with_positions() {
let a = Index::from_i64(vec![1, 3, 5]);
let b = Index::from_i64(vec![2, 3, 4]);
let plan = multi_way_align(&[&a, &b]);
assert_eq!(
plan.union_index.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(5),
IndexLabel::Int64(2),
IndexLabel::Int64(4),
]
);
assert_eq!(
plan.positions[0],
vec![Some(0), Some(1), Some(2), None, None]
);
assert_eq!(
plan.positions[1],
vec![None, Some(1), None, Some(0), Some(2)]
);
eprintln!("[AG-11-T] two_sorted_overlapping | in=[3,3] out=5 | PASS");
}
#[test]
fn ag11t_five_way_union_vs_pairwise() {
let indexes: Vec<Index> = (0..5)
.map(|i| Index::from_i64(vec![i * 10, i * 10 + 1, i * 10 + 2]))
.collect();
let refs: Vec<&Index> = indexes.iter().collect();
let leapfrog = leapfrog_union(&refs);
// Iterative pairwise
let mut pairwise = indexes[0].clone();
for idx in &indexes[1..] {
pairwise = pairwise.union_with(idx);
}
let pairwise = pairwise.sort_values();
assert_eq!(leapfrog.labels(), pairwise.labels());
eprintln!(
"[AG-11-T] five_way_union_vs_pairwise | in=[3x5] out={} | PASS",
leapfrog.len()
);
}
#[test]
fn ag11t_single_element_indexes() {
let indexes: Vec<Index> = (0..10).map(|i| Index::from_i64(vec![i])).collect();
let refs: Vec<&Index> = indexes.iter().collect();
let result = leapfrog_union(&refs);
assert_eq!(result.len(), 10);
for (i, label) in result.labels().iter().enumerate() {
assert_eq!(*label, IndexLabel::Int64(i as i64));
}
eprintln!("[AG-11-T] single_element_indexes | in=[1x10] out=10 | PASS");
}
#[test]
fn ag11t_all_same_labels() {
let base = Index::from_i64(vec![1, 2, 3]);
let refs: Vec<&Index> = (0..5).map(|_| &base).collect();
let plan = multi_way_align(&refs);
assert_eq!(
plan.union_index.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3)
]
);
// All 5 inputs should have identity positions
for pos_vec in &plan.positions {
assert_eq!(*pos_vec, vec![Some(0), Some(1), Some(2)]);
}
eprintln!("[AG-11-T] all_same_labels | in=[3x5] out=3 | PASS");
}
#[test]
fn ag11t_iso_associativity() {
let a = Index::from_i64(vec![1, 4, 7, 10]);
let b = Index::from_i64(vec![2, 4, 8, 10]);
let c = Index::from_i64(vec![3, 7, 8, 10]);
let leapfrog_result = leapfrog_union(&[&a, &b, &c]);
// union(A, union(B, C))
let bc = b.union_with(&c).sort_values();
let a_bc = a.union_with(&bc).sort_values();
// union(union(A, B), C)
let ab = a.union_with(&b).sort_values();
let ab_c = ab.union_with(&c).sort_values();
assert_eq!(leapfrog_result.labels(), a_bc.labels());
assert_eq!(leapfrog_result.labels(), ab_c.labels());
eprintln!("[AG-11-T] iso_associativity | verified | PASS");
}
#[test]
fn ag11t_iso_commutativity() {
let a = Index::from_i64(vec![1, 5, 9]);
let b = Index::from_i64(vec![2, 5, 8]);
let c = Index::from_i64(vec![3, 5, 7]);
let abc = leapfrog_union(&[&a, &b, &c]);
let cab = leapfrog_union(&[&c, &a, &b]);
let bca = leapfrog_union(&[&b, &c, &a]);
// All orderings produce same sorted output
assert_eq!(abc.labels(), cab.labels());
assert_eq!(abc.labels(), bca.labels());
eprintln!("[AG-11-T] iso_commutativity | verified | PASS");
}
// ── Index: min/max/argmin/argmax ──
#[test]
fn index_min_max_int() {
let idx = Index::new(vec![3_i64.into(), 1_i64.into(), 2_i64.into()]);
assert_eq!(idx.min(), Some(IndexLabel::Int64(1)));
assert_eq!(idx.max(), Some(IndexLabel::Int64(3)));
assert_eq!(idx.argmin(), Some(1));
assert_eq!(idx.argmax(), Some(0));
}
#[test]
fn index_min_max_utf8() {
let idx = Index::new(vec!["c".into(), "a".into(), "b".into()]);
assert_eq!(idx.min(), Some(IndexLabel::Utf8("a".into())));
assert_eq!(idx.max(), Some(IndexLabel::Utf8("c".into())));
assert_eq!(idx.argmin(), Some(1));
assert_eq!(idx.argmax(), Some(0));
}
#[test]
fn index_min_max_empty() {
let idx = Index::new(vec![]);
assert_eq!(idx.min(), None);
assert_eq!(idx.max(), None);
assert_eq!(idx.argmin(), None);
assert_eq!(idx.argmax(), None);
}
#[test]
fn index_nunique() {
let idx = Index::new(vec![1_i64.into(), 2_i64.into(), 1_i64.into()]);
assert_eq!(idx.nunique(), 2);
}
#[test]
fn typed_int64_nunique_counts_without_label_materialization_codb() {
let index = Index::from_i64_values(vec![3, 1, 3, 2, 1, 4]).set_name("row");
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.nunique(), 4);
assert_eq!(index.nunique_with_dropna(false), 4);
assert!(
index.labels.materialized.get().is_none(),
"typed Int64 nunique should count raw values without materializing labels"
);
let materialized = Index::new(vec![
IndexLabel::Int64(3),
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(2),
IndexLabel::Int64(1),
IndexLabel::Int64(4),
]);
assert_eq!(index.nunique(), materialized.nunique());
assert_eq!(
index.nunique_with_dropna(false),
materialized.nunique_with_dropna(false)
);
}
#[test]
fn sparse_int64_nunique_counts_without_label_materialization_codb() {
let index = Index::from_i64_values(vec![0, 1_000_000, -500_000, 0, 1_000_000]);
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.nunique(), 3);
assert_eq!(index.nunique_with_dropna(false), 3);
assert!(
index.labels.materialized.get().is_none(),
"wide-span Int64 nunique should use raw hash keys without materializing labels"
);
}
#[test]
fn index_nunique_dropna_false_counts_timedelta_nat_once() {
let idx = Index::from_timedelta64(vec![Timedelta::NAT, Timedelta::NAT, 5]);
assert_eq!(idx.nunique(), 1);
assert_eq!(idx.nunique_with_dropna(false), 2);
}
#[test]
fn index_nunique_dropna_false_counts_datetime_nat_once() {
let idx = Index::new(vec![
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Datetime64(1_700_000_000_000_000_000),
]);
assert_eq!(idx.nunique(), 1);
assert_eq!(idx.nunique_with_dropna(false), 2);
}
// ── Index: map/rename/drop/astype ──
#[test]
fn index_map() {
let idx = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]);
let mapped = idx.map(|l| match l {
IndexLabel::Int64(v) => IndexLabel::Int64(v * 10),
other => other.clone(),
});
assert_eq!(mapped.labels()[0], IndexLabel::Int64(10));
assert_eq!(mapped.labels()[2], IndexLabel::Int64(30));
}
#[test]
fn index_drop_labels() {
let idx = Index::new(vec!["a".into(), "b".into(), "c".into()]);
let dropped = idx.drop_labels(&["b".into()]);
assert_eq!(dropped.len(), 2);
assert_eq!(dropped.labels()[0], IndexLabel::Utf8("a".into()));
assert_eq!(dropped.labels()[1], IndexLabel::Utf8("c".into()));
}
#[test]
fn float_index_dedups_through_spread_keys_bss5q3() {
// br-frankenpandas-bss5q.3: a float index's duplicated / unique /
// drop_duplicates run through the i64 masks over its spread canonical
// bits - -0.0 one label with 0.0, every NaN one label, each keep
// mode as pandas answers it. NEGATIVE: a Float64 beside an Int64
// label gives no float keys (the label map answers).
let float = |value: f64| IndexLabel::Float64(OrderedF64(value));
let index = crate::Index::new(vec![
float(3.0),
float(-0.0),
float(f64::NAN),
float(0.0),
float(3.0),
float(f64::NAN),
float(1024.0),
]);
assert_eq!(
index.duplicated(crate::DuplicateKeep::First),
vec![false, false, false, true, true, true, false]
);
assert_eq!(
index.duplicated(crate::DuplicateKeep::Last),
vec![true, true, true, false, false, false, false]
);
assert_eq!(
index.duplicated(crate::DuplicateKeep::None),
vec![true, true, true, true, true, true, false]
);
let unique = index.unique();
assert_eq!(unique.len(), 4);
assert_eq!(unique.labels()[1], float(-0.0));
assert_eq!(
index.drop_duplicates_keep(crate::DuplicateKeep::None).len(),
1
);
let mixed = crate::Index::new(vec![float(1.0), IndexLabel::Int64(1)]);
assert!(mixed.float_label_keys().is_none());
}
#[test]
fn generic_drop_labels_hash_preserves_mixed_identity_arboe() {
let labels = vec![
IndexLabel::Utf8("duplicate".into()),
IndexLabel::Int64(7),
IndexLabel::Float64(OrderedF64(f64::NAN)),
IndexLabel::Float64(OrderedF64(-0.0)),
IndexLabel::Float64(OrderedF64(0.0)),
IndexLabel::Bool(true),
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Timedelta64(Timedelta::NAT),
IndexLabel::Null(fp_types::NullKind::Null),
IndexLabel::Utf8("duplicate".into()),
IndexLabel::Utf8("keep".into()),
];
let drops = vec![
IndexLabel::Utf8("duplicate".into()),
IndexLabel::Float64(OrderedF64(f64::from_bits(0x7ff8_0000_0000_0001))),
IndexLabel::Float64(OrderedF64(0.0)),
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Null(fp_types::NullKind::NaN),
IndexLabel::Utf8("absent".into()),
IndexLabel::Int64(999),
IndexLabel::Bool(false),
IndexLabel::Timedelta64(123),
];
let expected = labels
.iter()
.filter(|label| !drops.contains(label))
.cloned()
.collect::<Vec<_>>();
let dropped = Index::new(labels).set_name("mixed").drop_labels(&drops);
assert_eq!(dropped.labels(), expected.as_slice());
assert_eq!(dropped.name().map(|n| n.as_str()), Some("mixed"));
}
#[test]
#[ignore = "foreground profile-first A/B"]
fn generic_drop_labels_hash_profile_arboe() {
use std::{hint::black_box, time::Instant};
fn former(input: &Index, drops: &[IndexLabel]) -> Index {
let kept = input
.labels
.iter()
.filter(|label| !drops.contains(label))
.cloned()
.collect();
input.propagate_name(Index::new(kept))
}
fn candidate(input: &Index, drops: &[IndexLabel]) -> Index {
input.drop_labels(drops)
}
fn elapsed(
input: &Index,
drops: &[IndexLabel],
dropper: fn(&Index, &[IndexLabel]) -> Index,
) -> u128 {
let started = Instant::now();
let output = dropper(black_box(input), black_box(drops));
black_box(&output);
let elapsed = started.elapsed().as_nanos();
black_box(output);
elapsed
}
fn samples(input: &Index, drops: &[IndexLabel]) -> (Vec<u128>, Vec<u128>) {
const SAMPLES: usize = 12;
for _ in 0..2 {
black_box(elapsed(input, drops, former));
black_box(elapsed(input, drops, candidate));
}
let mut former_ns = Vec::with_capacity(SAMPLES);
let mut candidate_ns = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample % 2 == 0 {
former_ns.push(elapsed(input, drops, former));
candidate_ns.push(elapsed(input, drops, candidate));
} else {
candidate_ns.push(elapsed(input, drops, candidate));
former_ns.push(elapsed(input, drops, former));
}
}
(former_ns, candidate_ns)
}
fn percentile(samples: &[u128], percent: usize) -> u128 {
let mut sorted = samples.to_vec();
sorted.sort_unstable();
let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
sorted[rank]
}
let parity_input = vec![
IndexLabel::Utf8("a".into()),
IndexLabel::Int64(7),
IndexLabel::Float64(OrderedF64(f64::NAN)),
IndexLabel::Float64(OrderedF64(-0.0)),
IndexLabel::Float64(OrderedF64(0.0)),
IndexLabel::Bool(true),
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Timedelta64(Timedelta::NAT),
IndexLabel::Null(fp_types::NullKind::Null),
IndexLabel::Utf8("a".into()),
];
let parity_drops = vec![
IndexLabel::Utf8("a".into()),
IndexLabel::Float64(OrderedF64(f64::from_bits(0x7ff8_0000_0000_0001))),
IndexLabel::Float64(OrderedF64(0.0)),
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Null(fp_types::NullKind::NaN),
IndexLabel::Utf8("absent".into()),
IndexLabel::Int64(999),
IndexLabel::Bool(false),
IndexLabel::Timedelta64(123),
];
let parity_input = Index::new(parity_input).set_name("mixed");
let expected = former(&parity_input, &parity_drops);
let actual = candidate(&parity_input, &parity_drops);
assert_eq!(actual.labels(), expected.labels());
assert_eq!(actual.name(), expected.name());
const ROWS: usize = 16_384;
const DROP_COUNT: usize = 4_096;
let input = Index::new(
(0..ROWS)
.map(|index| IndexLabel::Utf8(format!("key-{:08}", index % (ROWS / 2))))
.collect::<Vec<_>>(),
)
.set_name("bench");
let large_drops = (0..DROP_COUNT)
.map(|index| IndexLabel::Utf8(format!("key-{:08}", index * 2)))
.collect::<Vec<_>>();
let small_drops = large_drops[..4].to_vec();
let large_expected = former(&input, &large_drops);
let large_actual = candidate(&input, &large_drops);
assert_eq!(large_actual.labels(), large_expected.labels());
assert_eq!(large_actual.name(), large_expected.name());
let small_expected = former(&input, &small_drops);
let small_actual = candidate(&input, &small_drops);
assert_eq!(small_actual.labels(), small_expected.labels());
assert_eq!(small_actual.name(), small_expected.name());
let (large_former, large_candidate) = samples(&input, &large_drops);
let (small_former, small_candidate) = samples(&input, &small_drops);
let large_former_p50 = percentile(&large_former, 50);
let large_former_p95 = percentile(&large_former, 95);
let large_former_p99 = percentile(&large_former, 99);
let large_candidate_p50 = percentile(&large_candidate, 50);
let large_candidate_p95 = percentile(&large_candidate, 95);
let large_candidate_p99 = percentile(&large_candidate, 99);
let small_former_p50 = percentile(&small_former, 50);
let small_candidate_p50 = percentile(&small_candidate, 50);
println!(
"GENERIC_DROP_HASH rows={ROWS} drops={DROP_COUNT} former_p50_ns={large_former_p50} candidate_p50_ns={large_candidate_p50} speedup_p50={:.6} former_p95_ns={large_former_p95} candidate_p95_ns={large_candidate_p95} speedup_p95={:.6} former_p99_ns={large_former_p99} candidate_p99_ns={large_candidate_p99} speedup_p99={:.6} small_drops=4 small_former_p50_ns={small_former_p50} small_candidate_p50_ns={small_candidate_p50} small_speedup_p50={:.6} former_samples={large_former:?} candidate_samples={large_candidate:?} small_former_samples={small_former:?} small_candidate_samples={small_candidate:?}",
large_former_p50 as f64 / large_candidate_p50 as f64,
large_former_p95 as f64 / large_candidate_p95 as f64,
large_former_p99 as f64 / large_candidate_p99 as f64,
small_former_p50 as f64 / small_candidate_p50 as f64,
);
}
#[test]
fn int64_drop_labels_preserves_typed_backing_codb() {
let index = Index::from_i64_values(vec![1, 2, 1, 3, 4]).set_name("row");
assert!(index.labels.materialized.get().is_none());
let dropped = index.drop_labels(&[IndexLabel::Int64(1), IndexLabel::Utf8("1".into())]);
assert_eq!(dropped.name().map(|n| n.as_str()), Some("row"));
assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[2, 3, 4]);
assert!(index.labels.materialized.get().is_none());
assert!(
dropped.labels.materialized.get().is_none(),
"typed Int64 drop_labels should keep typed output backing"
);
let materialized = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
]);
assert_eq!(
dropped.labels(),
materialized
.drop_labels(&[IndexLabel::Int64(1), IndexLabel::Utf8("1".into())])
.labels()
);
}
#[test]
fn sorted_int64_drop_labels_preserves_typed_backing_codb() {
let index = Index::from_i64_values(vec![0, 1, 1, 2, 3, 4, 5, 6]).set_name("row");
assert!(index.labels.materialized.get().is_none());
let dropped = index.drop_labels(&[
IndexLabel::Int64(4),
IndexLabel::Int64(1),
IndexLabel::Int64(100),
IndexLabel::Utf8("2".into()),
]);
assert_eq!(dropped.name().map(|n| n.as_str()), Some("row"));
assert_eq!(
dropped.labels.int64_view().unwrap().as_slice(),
&[0, 2, 3, 5, 6]
);
assert!(index.labels.materialized.get().is_none());
assert!(
dropped.labels.materialized.get().is_none(),
"sorted Int64 drop_labels should keep typed output backing"
);
}
#[test]
fn affine_int64_drop_labels_preserves_typed_backing_codb() {
let index = Index::new_known_unique_int64_affine_range(10, -2, 5)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let dropped = index.drop_labels(&[IndexLabel::Int64(8), IndexLabel::Int64(2)]);
assert_eq!(dropped.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[10, 6, 4]);
assert!(index.labels.materialized.get().is_none());
assert!(
dropped.labels.materialized.get().is_none(),
"affine Int64 drop_labels should gather raw values into typed output"
);
}
#[test]
fn index_astype_str() {
let idx = Index::new(vec![1_i64.into(), 2_i64.into()]);
let str_idx = idx.astype_str();
assert_eq!(str_idx.labels()[0], IndexLabel::Utf8("1".into()));
assert_eq!(str_idx.labels()[1], IndexLabel::Utf8("2".into()));
}
#[test]
fn typed_int64_astype_str_avoids_source_materialization_codb() {
let index = Index::from_i64_values(vec![7, -5, 0]).set_name("row");
assert!(index.labels.materialized.get().is_none());
let str_idx = index.astype_str();
assert_eq!(str_idx.name().map(|n| n.as_str()), Some("row"));
assert_eq!(
str_idx.labels(),
&[
IndexLabel::Utf8("7".into()),
IndexLabel::Utf8("-5".into()),
IndexLabel::Utf8("0".into()),
]
);
assert!(
index.labels.materialized.get().is_none(),
"astype_str should stringify raw Int64 values without materializing source labels"
);
let materialized = Index::new(vec![
IndexLabel::Int64(7),
IndexLabel::Int64(-5),
IndexLabel::Int64(0),
])
.set_name("row");
assert_eq!(str_idx.labels(), materialized.astype_str().labels());
}
#[test]
fn affine_int64_astype_str_avoids_source_materialization_codb() {
let index = Index::new_known_unique_int64_affine_range(4, -3, 3)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let str_idx = index.astype_str();
assert_eq!(str_idx.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
str_idx.labels(),
&[
IndexLabel::Utf8("4".into()),
IndexLabel::Utf8("1".into()),
IndexLabel::Utf8("-2".into()),
]
);
assert!(
index.labels.materialized.get().is_none(),
"affine astype_str should not materialize source labels"
);
}
#[test]
fn index_astype_int() {
let idx = Index::new(vec![
IndexLabel::Utf8("10".into()),
IndexLabel::Utf8("20".into()),
]);
let int_idx = idx.astype_int();
assert_eq!(int_idx.labels()[0], IndexLabel::Int64(10));
assert_eq!(int_idx.labels()[1], IndexLabel::Int64(20));
}
/// pandas 2.2.3: Index([1, 2]).astype('float64') -> Index([1.0, 2.0],
/// dtype='float64'); astype(bool) -> [True, False] for [3, 0]; a
/// non-numeric string refuses the float cast. Index.astype used to accept
/// only int/str (and the binding ignored the dtype altogether). (fvsao.4)
#[test]
fn index_astype_float_and_bool_fvsao4() {
let ints = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]).set_name("n");
let floats = ints.astype("float64").expect("float cast");
assert_eq!(
floats.labels(),
&[
IndexLabel::Float64(OrderedF64(1.0)),
IndexLabel::Float64(OrderedF64(2.0))
]
);
assert_eq!(floats.dtype(), "float64");
assert_eq!(floats.name().map(|n| n.as_str()), Some("n"));
let flags = Index::new(vec![IndexLabel::Int64(3), IndexLabel::Int64(0)])
.astype("bool")
.expect("bool cast");
assert_eq!(
flags.labels(),
&[IndexLabel::Bool(true), IndexLabel::Bool(false)]
);
assert_eq!(flags.dtype(), "bool");
assert!(
Index::new(vec![IndexLabel::Utf8("x".into())])
.astype("float64")
.is_err()
);
assert!(
Index::new(vec![IndexLabel::Datetime64(0)])
.astype("float64")
.is_err()
);
}
#[test]
fn typed_int64_astype_int_avoids_label_materialization_ntqtf() {
let index = Index::from_i64_values(vec![7, 5, 7]).set_name("rows");
assert!(index.labels.materialized.get().is_none());
let cast = index.astype_int();
assert_eq!(cast.name().map(|n| n.as_str()), Some("rows"));
assert_eq!(cast.labels.int64_view().unwrap().as_slice(), &[7, 5, 7]);
assert!(index.labels.materialized.get().is_none());
assert!(
cast.labels.materialized.get().is_none(),
"already-Int64 astype_int should keep typed output backing"
);
}
#[test]
fn affine_int64_astype_int_avoids_label_materialization_ntqtf() {
let index = Index::new_known_unique_int64_affine_range(2, 4, 3)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let cast = index.astype_int();
assert_eq!(cast.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(cast.labels.int64_view().unwrap().as_slice(), &[2, 6, 10]);
assert!(index.labels.materialized.get().is_none());
assert!(
cast.labels.materialized.get().is_none(),
"affine Int64 astype_int should keep typed output backing"
);
}
#[test]
fn index_isna_notna() {
let idx = Index::new(vec![1_i64.into(), 2_i64.into()]);
assert_eq!(idx.isna(), vec![false, false]);
assert_eq!(idx.notna(), vec![true, true]);
}
#[test]
fn typed_int64_missing_helpers_avoid_label_materialization_zyoot() {
let index = Index::from_i64_values(vec![1, 0, -4]).set_name("rows");
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.isna(), vec![false, false, false]);
assert_eq!(index.notna(), vec![true, true, true]);
assert!(
index.labels.materialized.get().is_none(),
"isna/notna should not materialize typed Int64 labels"
);
let dropped = index.dropna();
assert_eq!(dropped.name().map(|n| n.as_str()), Some("rows"));
assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[1, 0, -4]);
assert!(index.labels.materialized.get().is_none());
assert!(
dropped.labels.materialized.get().is_none(),
"dropna should preserve typed Int64 backing"
);
let filled = index.fillna(&IndexLabel::Utf8("missing".into()));
assert_eq!(filled.name().map(|n| n.as_str()), Some("rows"));
assert_eq!(filled.labels.int64_view().unwrap().as_slice(), &[1, 0, -4]);
assert!(index.labels.materialized.get().is_none());
assert!(
filled.labels.materialized.get().is_none(),
"fillna should preserve typed Int64 backing when there are no missing labels"
);
}
#[test]
fn affine_int64_missing_helpers_avoid_label_materialization_zyoot() {
let index = Index::new_known_unique_int64_affine_range(4, -2, 3)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.isna(), vec![false, false, false]);
assert_eq!(index.notna(), vec![true, true, true]);
assert!(index.labels.materialized.get().is_none());
let dropped = index.dropna();
assert_eq!(dropped.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[4, 2, 0]);
assert!(index.labels.materialized.get().is_none());
assert!(
dropped.labels.materialized.get().is_none(),
"dropna should preserve affine Int64 backing"
);
let empty = Index::new_known_unique_int64_affine_range(0, 0, 0).unwrap();
assert_eq!(empty.isna(), Vec::<bool>::new());
assert_eq!(empty.notna(), Vec::<bool>::new());
let filled_empty = empty.fillna(&IndexLabel::Int64(99));
assert!(filled_empty.labels.int64_view().unwrap().is_empty());
assert!(empty.labels.materialized.get().is_none());
assert!(filled_empty.labels.materialized.get().is_none());
}
#[test]
fn int64_hasnans_avoids_label_materialization_99qun() {
let typed = Index::from_i64_values(vec![7, 0, -3]);
assert!(typed.labels.materialized.get().is_none());
assert!(!typed.hasnans());
assert!(
typed.labels.materialized.get().is_none(),
"hasnans should not materialize typed Int64 labels"
);
let affine = Index::new_known_unique_int64_affine_range(9, -3, 4).unwrap();
assert!(affine.labels.materialized.get().is_none());
assert!(!affine.hasnans());
assert!(
affine.labels.materialized.get().is_none(),
"hasnans should not materialize affine Int64 labels"
);
}
#[test]
fn index_isna_notna_detects_datetimelike_nat() {
let datetime_idx = Index::new(vec![
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Datetime64(1_700_000_000_000_000_000),
]);
assert_eq!(datetime_idx.isna(), vec![true, false]);
assert_eq!(datetime_idx.notna(), vec![false, true]);
let timedelta_idx = Index::from_timedelta64(vec![Timedelta::NAT, 5]);
assert_eq!(timedelta_idx.isna(), vec![true, false]);
assert_eq!(timedelta_idx.notna(), vec![false, true]);
}
#[test]
fn index_fillna_replaces_datetime_nat_and_preserves_name() {
let idx = Index::new(vec![
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Datetime64(1_700_000_000_000_000_000),
IndexLabel::Datetime64(i64::MIN),
])
.set_name("when");
let filled = idx.fillna(&IndexLabel::Datetime64(1_800_000_000_000_000_000));
assert_eq!(
filled.labels(),
&[
IndexLabel::Datetime64(1_800_000_000_000_000_000),
IndexLabel::Datetime64(1_700_000_000_000_000_000),
IndexLabel::Datetime64(1_800_000_000_000_000_000),
]
);
assert_eq!(filled.name().map(|n| n.as_str()), Some("when"));
}
#[test]
fn index_fillna_replaces_timedelta_nat() {
let idx = Index::from_timedelta64(vec![Timedelta::NAT, 5, Timedelta::NAT]);
let filled = idx.fillna(&IndexLabel::Timedelta64(42));
assert_eq!(
filled.labels(),
&[
IndexLabel::Timedelta64(42),
IndexLabel::Timedelta64(5),
IndexLabel::Timedelta64(42),
]
);
}
#[test]
fn index_dropna_removes_missing_and_preserves_name() {
let idx =
Index::from_timedelta64(vec![1, Timedelta::NAT, 3, Timedelta::NAT, 5]).set_name("t");
let dropped = idx.dropna();
assert_eq!(
dropped.labels(),
&[
IndexLabel::Timedelta64(1),
IndexLabel::Timedelta64(3),
IndexLabel::Timedelta64(5),
]
);
assert_eq!(dropped.name().map(|n| n.as_str()), Some("t"));
}
#[test]
fn index_dropna_all_present_is_noop() {
let idx = Index::from_i64(vec![1, 2, 3]);
let dropped = idx.dropna();
assert_eq!(
dropped.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
]
);
}
#[test]
fn index_insert_at_middle_position() {
let idx = Index::from_i64(vec![1, 3, 4]);
let result = idx.insert(1, IndexLabel::Int64(2)).unwrap();
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
]
);
}
#[test]
fn index_insert_at_end_appends() {
let idx = Index::from_i64(vec![1, 2]);
let result = idx.insert(2, IndexLabel::Int64(3)).unwrap();
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
]
);
}
#[test]
fn typed_int64_insert_avoids_label_materialization_uza04152() {
let index = Index::from_i64_values(vec![10, 20, 30]).set_name("rows");
assert!(index.labels.materialized.get().is_none());
let result = index.insert(1, IndexLabel::Int64(15)).unwrap();
assert_eq!(result.name().map(|n| n.as_str()), Some("rows"));
assert_eq!(
result.labels.int64_view().unwrap().as_slice(),
&[10, 15, 20, 30]
);
assert!(index.labels.materialized.get().is_none());
assert!(
result.labels.materialized.get().is_none(),
"typed Int64 insert should keep typed output backing"
);
}
#[test]
fn affine_int64_insert_avoids_label_materialization_uza04152() {
let index = Index::new_known_unique_int64_affine_range(2, 3, 3)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let result = index.insert(2, IndexLabel::Int64(7)).unwrap();
assert_eq!(result.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
result.labels.int64_view().unwrap().as_slice(),
&[2, 5, 7, 8]
);
assert!(index.labels.materialized.get().is_none());
assert!(
result.labels.materialized.get().is_none(),
"affine Int64 insert should rebuild typed output without materializing labels"
);
}
#[test]
fn index_insert_past_end_errors() {
let idx = Index::from_i64(vec![1, 2]);
let err = idx.insert(5, IndexLabel::Int64(9)).unwrap_err();
assert!(matches!(err, crate::IndexError::OutOfBounds { .. }));
}
#[test]
fn index_delete_removes_position() {
let idx = Index::from_i64(vec![10, 20, 30]).set_name("k");
let result = idx.delete(1).unwrap();
assert_eq!(
result.labels(),
&[IndexLabel::Int64(10), IndexLabel::Int64(30)]
);
assert_eq!(result.name().map(|n| n.as_str()), Some("k"));
}
#[test]
fn typed_int64_delete_avoids_label_materialization_uza04150() {
let index = Index::from_i64_values(vec![10, 20, 30, 40]).set_name("rows");
assert!(index.labels.materialized.get().is_none());
let result = index.delete(2).unwrap();
assert_eq!(result.name().map(|n| n.as_str()), Some("rows"));
assert_eq!(
result.labels.int64_view().unwrap().as_slice(),
&[10, 20, 40]
);
assert!(index.labels.materialized.get().is_none());
assert!(
result.labels.materialized.get().is_none(),
"typed Int64 delete should keep typed output backing"
);
}
#[test]
fn affine_int64_delete_avoids_label_materialization_uza04150() {
let index = Index::new_known_unique_int64_affine_range(2, 3, 4)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let result = index.delete(1).unwrap();
assert_eq!(result.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(result.labels.int64_view().unwrap().as_slice(), &[2, 8, 11]);
assert!(index.labels.materialized.get().is_none());
assert!(
result.labels.materialized.get().is_none(),
"affine Int64 delete should rebuild typed output without materializing labels"
);
}
#[test]
fn index_delete_out_of_bounds_errors() {
let idx = Index::from_i64(vec![1]);
let err = idx.delete(1).unwrap_err();
assert!(matches!(err, crate::IndexError::OutOfBounds { .. }));
}
#[test]
fn index_append_concatenates() {
let a = Index::from_i64(vec![1, 2]).set_name("left");
let b = Index::from_i64(vec![3, 4]);
let result = a.append(&b);
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
]
);
assert_eq!(result.name().map(|n| n.as_str()), Some("left"));
}
#[test]
fn index_append_empty_is_noop() {
let a = Index::from_i64(vec![1, 2]);
let empty = Index::new(Vec::new());
let result = a.append(&empty);
assert_eq!(result.labels(), a.labels());
}
#[test]
fn int64_append_preserves_typed_backing_codb() {
let left = Index::from_i64_values(vec![1, 2, 3]).set_name("row");
let right = Index::from_i64_values(vec![4, 5]);
assert!(left.labels.materialized.get().is_none());
assert!(right.labels.materialized.get().is_none());
let appended = left.append(&right);
assert_eq!(appended.name().map(|n| n.as_str()), Some("row"));
assert_eq!(
appended.labels.int64_view().unwrap().as_slice(),
&[1, 2, 3, 4, 5]
);
assert!(left.labels.materialized.get().is_none());
assert!(right.labels.materialized.get().is_none());
assert!(
appended.labels.materialized.get().is_none(),
"Int64 append should keep typed output backing"
);
}
#[test]
fn affine_int64_append_preserves_typed_backing_codb() {
let left = Index::new_known_unique_int64_affine_range(10, -2, 3)
.unwrap()
.set_name("axis");
let right = Index::new_known_unique_int64_affine_range(1, 3, 3).unwrap();
assert!(left.labels.materialized.get().is_none());
assert!(right.labels.materialized.get().is_none());
let appended = left.append(&right);
assert_eq!(appended.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
appended.labels.int64_view().unwrap().as_slice(),
&[10, 8, 6, 1, 4, 7]
);
assert!(left.labels.materialized.get().is_none());
assert!(right.labels.materialized.get().is_none());
assert!(
appended.labels.materialized.get().is_none(),
"affine Int64 append should gather raw values into typed output"
);
}
#[test]
fn index_repeat_duplicates_each_label() {
let idx = Index::from_i64(vec![1, 2, 3]).set_name("k");
let result = idx.repeat(2);
assert_eq!(
result.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(3),
]
);
assert_eq!(result.name().map(|n| n.as_str()), Some("k"));
}
#[test]
fn index_repeat_zero_yields_empty() {
let idx = Index::from_i64(vec![1, 2, 3]);
let result = idx.repeat(0);
assert!(result.labels().is_empty());
}
#[test]
fn index_repeat_one_is_clone() {
let idx = Index::from_i64(vec![1, 2]);
let result = idx.repeat(1);
assert_eq!(result.labels(), idx.labels());
}
#[test]
fn int64_repeat_preserves_typed_backing_codb() {
let index = Index::from_i64_values(vec![2, 4, 6]).set_name("row");
assert!(index.labels.materialized.get().is_none());
let repeated = index.repeat(3);
assert_eq!(repeated.name().map(|n| n.as_str()), Some("row"));
assert_eq!(
repeated.labels.int64_view().unwrap().as_slice(),
&[2, 2, 2, 4, 4, 4, 6, 6, 6]
);
assert!(index.labels.materialized.get().is_none());
assert!(
repeated.labels.materialized.get().is_none(),
"typed Int64 repeat should keep typed output backing"
);
}
#[test]
fn affine_int64_repeat_zero_preserves_empty_typed_backing_codb() {
let index = Index::new_known_unique_int64_affine_range(3, 5, 4)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let repeated = index.repeat(0);
assert_eq!(repeated.name().map(|n| n.as_str()), Some("axis"));
assert!(repeated.labels.int64_view().unwrap().is_empty());
assert!(index.labels.materialized.get().is_none());
assert!(
repeated.labels.materialized.get().is_none(),
"zero-repeat Int64 output should stay typed-empty"
);
}
#[test]
fn index_equals_same_labels_ignores_name() {
let a = Index::from_i64(vec![1, 2, 3]).set_name("x");
let b = Index::from_i64(vec![1, 2, 3]).set_name("y");
assert!(a.equals(&b));
}
#[test]
fn index_equals_differing_labels_false() {
let a = Index::from_i64(vec![1, 2, 3]);
let b = Index::from_i64(vec![1, 2]);
assert!(!a.equals(&b));
}
#[test]
fn index_identical_requires_matching_name() {
let a = Index::from_i64(vec![1, 2]).set_name("x");
let b = Index::from_i64(vec![1, 2]).set_name("y");
assert!(a.equals(&b));
assert!(!a.identical(&b));
let c = Index::from_i64(vec![1, 2]).set_name("x");
assert!(a.identical(&c));
}
#[test]
fn index_value_counts_sorts_by_descending_count() {
let idx = Index::new(vec![
"a".into(),
"b".into(),
"a".into(),
"c".into(),
"a".into(),
"b".into(),
]);
let counts = idx.value_counts();
assert_eq!(counts[0].0, IndexLabel::Utf8("a".into()));
assert_eq!(counts[0].1, 3);
assert_eq!(counts[1].0, IndexLabel::Utf8("b".into()));
assert_eq!(counts[1].1, 2);
assert_eq!(counts[2].0, IndexLabel::Utf8("c".into()));
assert_eq!(counts[2].1, 1);
}
#[test]
fn index_value_counts_empty() {
let idx = Index::new(Vec::<IndexLabel>::new());
assert!(idx.value_counts().is_empty());
}
#[test]
fn index_value_counts_drops_missing_by_default() {
let idx = Index::new(vec![
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Utf8("a".into()),
IndexLabel::Utf8("a".into()),
IndexLabel::Datetime64(i64::MIN),
]);
let counts = idx.value_counts();
assert_eq!(counts, vec![(IndexLabel::Utf8("a".into()), 2)]);
}
#[test]
fn index_value_counts_with_options_preserves_first_seen_order_when_unsorted() {
let idx = Index::new(vec![
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Utf8("b".into()),
IndexLabel::Utf8("a".into()),
IndexLabel::Utf8("b".into()),
]);
let counts = idx.value_counts_with_options(false, false, false, false);
assert_eq!(
counts,
vec![
(IndexLabel::Datetime64(i64::MIN), Scalar::Int64(1)),
(IndexLabel::Utf8("b".into()), Scalar::Int64(2)),
(IndexLabel::Utf8("a".into()), Scalar::Int64(1)),
]
);
}
#[test]
fn index_value_counts_with_options_normalize_excludes_missing_from_denominator() {
let idx = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Datetime64(i64::MIN),
]);
let counts = idx.value_counts_with_options(true, true, false, true);
assert!(matches!(
counts.as_slice(),
[
(IndexLabel::Int64(1), Scalar::Float64(_)),
(IndexLabel::Int64(2), Scalar::Float64(_))
]
));
let [
(IndexLabel::Int64(1), Scalar::Float64(first)),
(IndexLabel::Int64(2), Scalar::Float64(second)),
] = counts.as_slice()
else {
return;
};
assert!((first - (2.0 / 3.0)).abs() < 1e-12);
assert!((second - (1.0 / 3.0)).abs() < 1e-12);
}
#[test]
fn index_shift_positive_pads_left() {
let idx = Index::from_i64(vec![1, 2, 3, 4]).set_name("k");
let shifted = idx.shift(2, IndexLabel::Int64(-1));
assert_eq!(
shifted.labels(),
&[
IndexLabel::Int64(-1),
IndexLabel::Int64(-1),
IndexLabel::Int64(1),
IndexLabel::Int64(2),
]
);
assert_eq!(shifted.name().map(|n| n.as_str()), Some("k"));
}
#[test]
fn index_shift_negative_pads_right() {
let idx = Index::from_i64(vec![1, 2, 3, 4]);
let shifted = idx.shift(-1, IndexLabel::Int64(0));
assert_eq!(
shifted.labels(),
&[
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
IndexLabel::Int64(0),
]
);
}
#[test]
fn index_shift_zero_is_clone() {
let idx = Index::from_i64(vec![1, 2, 3]);
let shifted = idx.shift(0, IndexLabel::Int64(-1));
assert_eq!(shifted.labels(), idx.labels());
}
#[test]
fn index_shift_larger_than_len_fills_all() {
let idx = Index::from_i64(vec![1, 2, 3]);
let shifted = idx.shift(10, IndexLabel::Int64(-1));
assert_eq!(
shifted.labels(),
&[
IndexLabel::Int64(-1),
IndexLabel::Int64(-1),
IndexLabel::Int64(-1),
]
);
}
#[test]
fn typed_int64_shift_preserves_typed_backing_codb() {
let index = Index::from_i64_values(vec![1, 2, 3, 4]).set_name("k");
assert!(index.labels.materialized.get().is_none());
let shifted = index.shift(2, IndexLabel::Int64(-1));
assert_eq!(shifted.name().map(|n| n.as_str()), Some("k"));
assert_eq!(
shifted.labels.int64_view().unwrap().as_slice(),
&[-1, -1, 1, 2]
);
assert!(index.labels.materialized.get().is_none());
assert!(
shifted.labels.materialized.get().is_none(),
"typed Int64 shift should keep typed output backing"
);
let materialized = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
])
.set_name("k");
assert_eq!(
shifted.labels(),
materialized.shift(2, IndexLabel::Int64(-1)).labels()
);
let filled = index.shift(10, IndexLabel::Int64(0));
assert_eq!(
filled.labels.int64_view().unwrap().as_slice(),
&[0, 0, 0, 0]
);
assert!(index.labels.materialized.get().is_none());
}
#[test]
fn affine_int64_shift_preserves_typed_backing_codb() {
let index = Index::new_known_unique_int64_affine_range(10, -2, 4)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let shifted = index.shift(-1, IndexLabel::Int64(99));
assert_eq!(shifted.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
shifted.labels.int64_view().unwrap().as_slice(),
&[8, 6, 4, 99]
);
assert!(index.labels.materialized.get().is_none());
assert!(
shifted.labels.materialized.get().is_none(),
"affine Int64 shift should gather raw values into typed output"
);
}
#[test]
fn index_any_all_basic() {
let idx = Index::from_i64(vec![0, 0, 1]);
assert!(idx.any());
assert!(!idx.all());
let all_nonzero = Index::from_i64(vec![1, 2, 3]);
assert!(all_nonzero.all());
assert!(all_nonzero.any());
let all_zero = Index::from_i64(vec![0, 0]);
assert!(!all_zero.any());
assert!(!all_zero.all());
}
#[test]
fn typed_int64_any_all_avoid_label_materialization_c1ikv() {
let mixed = Index::from_i64_values(vec![0, 3, 0]);
assert!(mixed.labels.materialized.get().is_none());
assert!(mixed.any());
assert!(!mixed.all());
assert!(
mixed.labels.materialized.get().is_none(),
"any/all should read typed Int64 values without materializing labels"
);
let all_nonzero = Index::from_i64_values(vec![-2, 1, 5]);
assert!(all_nonzero.labels.materialized.get().is_none());
assert!(all_nonzero.any());
assert!(all_nonzero.all());
assert!(all_nonzero.labels.materialized.get().is_none());
}
#[test]
fn affine_int64_any_all_avoid_label_materialization_c1ikv() {
let zeros = Index::new_known_unique_int64_affine_range(0, 0, 0).unwrap();
assert!(zeros.labels.materialized.get().is_none());
assert!(!zeros.any());
assert!(zeros.all());
assert!(zeros.labels.materialized.get().is_none());
let values = Index::new_known_unique_int64_affine_range(2, 2, 3).unwrap();
assert!(values.labels.materialized.get().is_none());
assert!(values.any());
assert!(values.all());
assert!(values.labels.materialized.get().is_none());
}
#[test]
fn index_all_empty_is_true() {
let idx = Index::new(Vec::<IndexLabel>::new());
assert!(idx.all());
assert!(!idx.any());
}
#[test]
fn index_any_string_nonempty_truthy() {
let idx = Index::new(vec!["".into(), "".into(), "x".into()]);
assert!(idx.any());
assert!(!idx.all());
}
#[test]
fn index_to_list_returns_owned_labels() {
let idx = Index::from_i64(vec![1, 2, 3]);
assert_eq!(
idx.to_list(),
vec![
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
]
);
}
#[test]
fn index_format_stringifies_labels() {
let idx = Index::new(vec![
IndexLabel::Int64(10),
IndexLabel::Utf8("abc".into()),
IndexLabel::Int64(-5),
]);
assert_eq!(idx.format(), vec!["10", "abc", "-5"]);
}
#[test]
fn typed_int64_format_avoids_label_materialization_ye9dl() {
let index = Index::from_i64_values(vec![10, -5, 0]);
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.format(), vec!["10", "-5", "0"]);
assert!(
index.labels.materialized.get().is_none(),
"format should read typed Int64 values without materializing labels"
);
}
#[test]
fn affine_int64_format_avoids_label_materialization_ye9dl() {
let index = Index::new_known_unique_int64_affine_range(10, -3, 4).unwrap();
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.format(), vec!["10", "7", "4", "1"]);
assert!(
index.labels.materialized.get().is_none(),
"format should read affine Int64 values without materializing labels"
);
}
#[test]
fn index_putmask_replaces_true_positions() {
let idx = Index::from_i64(vec![1, 2, 3, 4]).set_name("k");
let cond = vec![false, true, false, true];
let replaced = idx.putmask(&cond, &IndexLabel::Int64(0));
assert_eq!(
replaced.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(0),
IndexLabel::Int64(3),
IndexLabel::Int64(0),
]
);
assert_eq!(replaced.name().map(|n| n.as_str()), Some("k"));
}
#[test]
fn index_putmask_short_cond_leaves_tail_unchanged() {
let idx = Index::from_i64(vec![1, 2, 3, 4]);
// cond shorter than index — trailing positions keep original
// labels (matches pandas lenient alignment).
let cond = vec![true];
let replaced = idx.putmask(&cond, &IndexLabel::Int64(-1));
assert_eq!(
replaced.labels(),
&[
IndexLabel::Int64(-1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
]
);
}
#[test]
fn index_putmask_empty_cond_is_noop() {
let idx = Index::from_i64(vec![1, 2]);
let replaced = idx.putmask(&[], &IndexLabel::Int64(0));
assert_eq!(replaced.labels(), idx.labels());
}
#[test]
fn int64_putmask_avoids_label_materialization_codb() {
let index = Index::from_i64_values(vec![1, 2, 3, 4]).set_name("row");
assert!(index.labels.materialized.get().is_none());
let replaced = index.putmask(&[false, true, false, true], &IndexLabel::Int64(9));
assert_eq!(replaced.name().map(|n| n.as_str()), Some("row"));
assert_eq!(
replaced.labels.int64_view().unwrap().as_slice(),
&[1, 9, 3, 9]
);
assert!(index.labels.materialized.get().is_none());
assert!(
replaced.labels.materialized.get().is_none(),
"typed Int64 putmask should keep typed output backing"
);
let materialized = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(4),
]);
assert_eq!(
replaced.labels(),
materialized
.putmask(&[false, true, false, true], &IndexLabel::Int64(9))
.labels()
);
}
#[test]
fn affine_int64_putmask_avoids_label_materialization_codb() {
let index = Index::new_known_unique_int64_affine_range(10, -2, 4)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let replaced = index.putmask(&[true, false, true], &IndexLabel::Int64(5));
assert_eq!(replaced.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
replaced.labels.int64_view().unwrap().as_slice(),
&[5, 8, 5, 4]
);
assert!(index.labels.materialized.get().is_none());
assert!(
replaced.labels.materialized.get().is_none(),
"affine Int64 putmask should gather raw values into typed output"
);
}
#[test]
fn index_asof_finds_largest_not_exceeding() {
let idx = Index::from_i64(vec![1, 3, 5, 7]);
assert_eq!(idx.asof(&IndexLabel::Int64(4)), Some(IndexLabel::Int64(3)));
assert_eq!(idx.asof(&IndexLabel::Int64(5)), Some(IndexLabel::Int64(5)));
assert_eq!(idx.asof(&IndexLabel::Int64(7)), Some(IndexLabel::Int64(7)));
assert_eq!(
idx.asof(&IndexLabel::Int64(100)),
Some(IndexLabel::Int64(7))
);
}
#[test]
fn index_asof_before_first_returns_none() {
let idx = Index::from_i64(vec![5, 10]);
assert_eq!(idx.asof(&IndexLabel::Int64(0)), None);
}
#[test]
fn int64_asof_avoids_label_materialization_1851g() {
let typed = Index::from_i64_values(vec![1, 3, 5, 7]);
assert!(typed.labels.materialized.get().is_none());
assert_eq!(
typed.asof(&IndexLabel::Int64(4)),
Some(IndexLabel::Int64(3))
);
assert_eq!(typed.asof(&IndexLabel::Int64(0)), None);
assert_eq!(
typed.asof(&IndexLabel::Int64(7)),
Some(IndexLabel::Int64(7))
);
assert!(
typed.labels.materialized.get().is_none(),
"asof should not materialize typed Int64 labels"
);
let affine = Index::new_known_unique_int64_affine_range(1, 2, 4).unwrap();
assert!(affine.labels.materialized.get().is_none());
assert!(affine.cached_int64_label_values().is_none());
assert_eq!(
affine.asof(&IndexLabel::Int64(6)),
Some(IndexLabel::Int64(5))
);
assert_eq!(
affine.asof(&IndexLabel::Int64(100)),
Some(IndexLabel::Int64(7))
);
assert!(
affine.labels.materialized.get().is_none(),
"asof should not materialize affine Int64 labels"
);
assert!(
affine.cached_int64_label_values().is_none(),
"asof should not materialize the affine raw i64 view"
);
let extreme = Index::new_known_unique_int64_affine_range(i64::MIN, i64::MAX, 2).unwrap();
assert_eq!(
extreme.asof(&IndexLabel::Int64(i64::MAX)),
Some(IndexLabel::Int64(-1))
);
assert!(extreme.cached_int64_label_values().is_none());
let singleton = Index::new_known_unique_int64_affine_range(7, i64::MIN, 1).unwrap();
assert_eq!(singleton.asof(&IndexLabel::Int64(6)), None);
assert_eq!(
singleton.asof(&IndexLabel::Int64(7)),
Some(IndexLabel::Int64(7))
);
assert!(singleton.cached_int64_label_values().is_none());
let empty = Index::new_known_unique_int64_affine_range(0, 0, 0).unwrap();
assert_eq!(empty.asof(&IndexLabel::Int64(0)), None);
assert!(empty.cached_int64_label_values().is_none());
}
#[test]
fn int64_asof_locs_avoids_label_materialization_4jr8s() {
let source = Index::from_i64_values(vec![1, 3, 5, 7]);
let probes = Index::from_i64_values(vec![0, 4, 7, 10]);
assert!(source.labels.materialized.get().is_none());
assert!(probes.labels.materialized.get().is_none());
assert_eq!(
source.asof_locs(&probes, None),
vec![None, Some(1), Some(3), Some(3)]
);
assert_eq!(
source.asof_locs(&probes, Some(&[true, false, true, true])),
vec![None, Some(0), Some(3), Some(3)]
);
assert!(
source.labels.materialized.get().is_none(),
"asof_locs should not materialize source Int64 labels"
);
assert!(
probes.labels.materialized.get().is_none(),
"asof_locs should not materialize probe Int64 labels"
);
}
#[test]
fn int64_asof_locs_no_mask_uses_right_bound_without_materializing_lx6k2() {
let source = Index::from_i64_values(vec![1, 3, 3, 8]);
let probes = Index::from_i64_values(vec![0, 3, 4, 9]);
assert_eq!(
source.asof_locs(&probes, None),
vec![None, Some(2), Some(2), Some(3)]
);
assert!(
source.labels.materialized.get().is_none(),
"no-mask asof_locs should keep duplicate Int64 source labels raw"
);
assert!(
probes.labels.materialized.get().is_none(),
"no-mask asof_locs should keep duplicate Int64 probe labels raw"
);
}
#[test]
fn index_searchsorted_left_right() {
let idx = Index::from_i64(vec![1, 2, 2, 5]);
assert_eq!(idx.searchsorted(&IndexLabel::Int64(2), "left").unwrap(), 1);
assert_eq!(idx.searchsorted(&IndexLabel::Int64(2), "right").unwrap(), 3);
assert_eq!(idx.searchsorted(&IndexLabel::Int64(0), "left").unwrap(), 0);
assert_eq!(idx.searchsorted(&IndexLabel::Int64(6), "left").unwrap(), 4);
}
#[test]
fn int64_searchsorted_avoids_label_materialization_ymhb6() {
let typed = Index::from_i64_values(vec![1, 2, 2, 5]);
assert!(typed.labels.materialized.get().is_none());
assert_eq!(
typed.searchsorted(&IndexLabel::Int64(2), "left").unwrap(),
1
);
assert_eq!(
typed.searchsorted(&IndexLabel::Int64(2), "right").unwrap(),
3
);
assert_eq!(
typed.searchsorted(&IndexLabel::Int64(0), "left").unwrap(),
0
);
assert_eq!(
typed.searchsorted(&IndexLabel::Int64(6), "left").unwrap(),
4
);
assert!(
typed.labels.materialized.get().is_none(),
"searchsorted should not materialize typed Int64 labels"
);
let affine = Index::new_known_unique_int64_affine_range(1, 2, 4).unwrap();
assert!(affine.labels.materialized.get().is_none());
assert_eq!(
affine.searchsorted(&IndexLabel::Int64(4), "left").unwrap(),
2
);
assert_eq!(
affine.searchsorted(&IndexLabel::Int64(5), "left").unwrap(),
2
);
assert_eq!(
affine.searchsorted(&IndexLabel::Int64(5), "right").unwrap(),
3
);
assert!(
affine.labels.materialized.get().is_none(),
"searchsorted should not materialize affine Int64 labels"
);
}
#[test]
fn index_searchsorted_rejects_invalid_side() {
let idx = Index::from_i64(vec![1]);
assert!(idx.searchsorted(&IndexLabel::Int64(0), "middle").is_err());
}
#[test]
fn index_memory_usage_counts_fixed_width() {
let idx = Index::from_i64(vec![1, 2, 3]);
let shallow = idx.memory_usage(false);
assert_eq!(shallow, 24); // 3 * 8
// deep is identical for fixed-width types.
assert_eq!(idx.memory_usage(true), 24);
}
#[test]
fn int64_memory_usage_avoids_label_materialization_bqfj0() {
let typed = Index::from_i64_values(vec![1, 2, 3, 4]);
assert!(typed.labels.materialized.get().is_none());
assert_eq!(typed.memory_usage(false), 32);
assert_eq!(typed.memory_usage(true), 32);
assert_eq!(typed.nbytes(), 32);
assert!(
typed.labels.materialized.get().is_none(),
"memory_usage should not materialize typed Int64 labels"
);
let affine = Index::new_known_unique_int64_affine_range(10, -2, 5).unwrap();
assert!(affine.labels.materialized.get().is_none());
assert_eq!(affine.memory_usage(false), 40);
assert_eq!(affine.memory_usage(true), 40);
assert_eq!(affine.nbytes(), 40);
assert!(
affine.labels.materialized.get().is_none(),
"memory_usage should not materialize affine Int64 labels"
);
let empty = Index::from_i64_values(Vec::new());
assert!(empty.labels.materialized.get().is_none());
assert_eq!(empty.memory_usage(false), 0);
assert_eq!(empty.memory_usage(true), 0);
assert_eq!(empty.nbytes(), 0);
assert!(empty.labels.materialized.get().is_none());
}
#[test]
fn index_memory_usage_saturates_fixed_width_bytes_uza04179() {
assert_eq!(super::fixed_width_label_memory_usage(4, 8), 32);
assert_eq!(
super::fixed_width_label_memory_usage(usize::MAX, 8),
usize::MAX
);
assert_eq!(
super::fixed_width_label_memory_usage(8, usize::MAX),
usize::MAX
);
}
#[test]
fn index_memory_usage_deep_counts_utf8_bytes() {
let idx = Index::new(vec![
IndexLabel::Utf8("hi".into()),
IndexLabel::Utf8("world".into()),
]);
let shallow = idx.memory_usage(false);
let deep = idx.memory_usage(true);
// deep - shallow == sum of string byte lengths
assert_eq!(deep - shallow, 7);
}
#[test]
fn index_nlevels_flat_index_is_one() {
let idx = Index::from_i64(vec![1, 2]);
assert_eq!(idx.nlevels(), 1);
}
#[test]
fn index_where_cond() {
let idx = Index::new(vec!["a".into(), "b".into(), "c".into()]);
let cond = vec![true, false, true];
let result = idx.where_cond(&cond, &"X".into());
assert_eq!(result.labels()[0], IndexLabel::Utf8("a".into()));
assert_eq!(result.labels()[1], IndexLabel::Utf8("X".into()));
assert_eq!(result.labels()[2], IndexLabel::Utf8("c".into()));
}
#[test]
fn int_index_where_nan_is_float_oq1df() {
let nan = IndexLabel::Null(fp_types::NullKind::NaN);
let idx = Index::from_i64(vec![1, 2, 3]);
let result = idx.where_cond(&[false, true, true], &nan);
assert_eq!(
result.labels(),
&[
nan.clone(),
IndexLabel::Float64(OrderedF64(2.0)),
IndexLabel::Float64(OrderedF64(3.0)),
]
);
let result = idx.where_cond(&[true, false, true], &IndexLabel::Float64(OrderedF64(0.5)));
assert_eq!(result.labels()[0], IndexLabel::Float64(OrderedF64(1.0)));
// Nothing replaced, or an int in place of a label: still ints.
let kept = idx.where_cond(&[true, true, true], &nan);
assert_eq!(kept.labels()[0], IndexLabel::Int64(1));
let ints = idx.where_cond(&[false, true, true], &IndexLabel::Int64(0));
assert_eq!(ints.labels()[0], IndexLabel::Int64(0));
assert_eq!(ints.labels()[1], IndexLabel::Int64(2));
}
#[test]
fn index_a31qh_conversion_aliases_materialize_labels() {
let idx = Index::new(vec!["a".into(), "b".into()]).set_name("key");
let labels = vec![IndexLabel::from("a"), IndexLabel::from("b")];
assert_eq!(idx.tolist(), labels);
assert_eq!(idx.to_numpy(), labels);
assert_eq!(idx.array(), labels);
assert_eq!(idx.values(), labels);
assert_eq!(idx.ravel(), labels);
assert_eq!(idx.view(), idx);
assert_eq!(idx.transpose(), idx);
assert_eq!(idx.T(), idx);
assert_eq!(
idx.to_frame(),
vec![vec![IndexLabel::from("a")], vec![IndexLabel::from("b")]]
);
assert_eq!(
idx.to_series(),
vec![
(IndexLabel::from("a"), IndexLabel::from("a")),
(IndexLabel::from("b"), IndexLabel::from("b")),
]
);
}
#[test]
fn int64_frame_series_views_avoid_source_materialization_codb() {
let index = Index::from_i64_values(vec![7, -1, 7]).set_name("row");
assert!(index.labels.materialized.get().is_none());
assert_eq!(
index.to_frame(),
vec![
vec![IndexLabel::Int64(7)],
vec![IndexLabel::Int64(-1)],
vec![IndexLabel::Int64(7)],
]
);
assert!(
index.labels.materialized.get().is_none(),
"to_frame should build owned rows from raw Int64 values"
);
assert_eq!(
index.to_series(),
vec![
(IndexLabel::Int64(7), IndexLabel::Int64(7)),
(IndexLabel::Int64(-1), IndexLabel::Int64(-1)),
(IndexLabel::Int64(7), IndexLabel::Int64(7)),
]
);
assert!(
index.labels.materialized.get().is_none(),
"to_series should build owned pairs from raw Int64 values"
);
let materialized = Index::new(vec![
IndexLabel::Int64(7),
IndexLabel::Int64(-1),
IndexLabel::Int64(7),
]);
assert_eq!(index.to_frame(), materialized.to_frame());
assert_eq!(index.to_series(), materialized.to_series());
let affine = Index::new_known_unique_int64_affine_range(4, 3, 3).unwrap();
assert!(affine.labels.materialized.get().is_none());
assert_eq!(
affine.to_frame(),
vec![
vec![IndexLabel::Int64(4)],
vec![IndexLabel::Int64(7)],
vec![IndexLabel::Int64(10)],
]
);
assert!(affine.labels.materialized.get().is_none());
}
#[test]
fn int64_list_aliases_avoid_source_materialization_codb() {
let index = Index::from_i64_values(vec![4, 0, -2]).set_name("row");
let expected = vec![
IndexLabel::Int64(4),
IndexLabel::Int64(0),
IndexLabel::Int64(-2),
];
assert!(index.labels.materialized.get().is_none());
assert_eq!(index.to_list(), expected);
assert_eq!(index.tolist(), expected);
assert_eq!(index.to_numpy(), expected);
assert_eq!(index.array(), expected);
assert_eq!(index.values(), expected);
assert_eq!(index.ravel(), expected);
assert!(
index.labels.materialized.get().is_none(),
"to_list aliases should materialize owned labels without caching source labels"
);
let materialized = Index::new(expected);
assert_eq!(index.to_list(), materialized.to_list());
assert_eq!(index.to_numpy(), materialized.to_numpy());
let affine = Index::new_known_unique_int64_affine_range(2, 3, 4).unwrap();
let expected_affine = vec![
IndexLabel::Int64(2),
IndexLabel::Int64(5),
IndexLabel::Int64(8),
IndexLabel::Int64(11),
];
assert!(affine.labels.materialized.get().is_none());
assert!(affine.cached_int64_label_values().is_none());
assert_eq!(affine.to_list(), expected_affine);
assert_eq!(affine.values(), expected_affine);
assert_eq!(affine.ravel(), expected_affine);
assert!(
affine.labels.materialized.get().is_none(),
"affine to_list aliases should not cache IndexLabel labels"
);
assert!(
affine.cached_int64_label_values().is_none(),
"affine to_list aliases should not build the intermediate i64 view"
);
}
#[test]
fn index_a31qh_dtype_metadata_and_type_checks() {
let ints = Index::from_i64(vec![1, 2, 3]);
assert_eq!(ints.dtype(), "int64");
assert_eq!(ints.dtypes(), vec!["int64"]);
assert_eq!(ints.inferred_type(), "integer");
assert!(ints.holds_integer());
assert!(ints.is_integer());
assert!(ints.is_numeric());
assert!(!ints.is_object());
assert_eq!(ints.ndim(), 1);
assert_eq!(ints.shape(), (3,));
assert_eq!(ints.size(), 3);
assert_eq!(ints.nbytes(), ints.memory_usage(false));
assert!(!ints.empty());
assert_eq!(
Index::from_i64(vec![42]).item().unwrap(),
IndexLabel::Int64(42)
);
assert!(ints.item().is_err());
let mixed = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Utf8("x".into()),
IndexLabel::Datetime64(i64::MIN),
]);
assert_eq!(mixed.dtype(), "object");
assert_eq!(mixed.inferred_type(), "mixed");
assert!(mixed.is_object());
assert!(mixed.hasnans());
assert_eq!(mixed.isnull(), mixed.isna());
assert_eq!(mixed.notnull(), mixed.notna());
assert!(!mixed.is_boolean());
assert!(!mixed.is_categorical());
assert!(!mixed.is_floating());
assert!(!mixed.is_interval());
assert_eq!(mixed.infer_objects(), mixed);
assert!(ints.is_(&ints));
assert!(!ints.is_(&Index::from_i64(vec![1, 2, 3])));
}
#[test]
fn a_missing_label_beside_bools_or_strings_is_mixed() {
use fp_types::NullKind;
// pd.Index([True, None]) / ['a', np.nan]: inferred 'mixed', object.
for labels in [
vec![IndexLabel::Bool(true), IndexLabel::Null(NullKind::Null)],
vec![
IndexLabel::Utf8("a".into()),
IndexLabel::Null(NullKind::NaN),
],
] {
let index = Index::new(labels);
assert_eq!(index.inferred_type(), "mixed");
assert_eq!(index.dtype(), "object");
}
// NEGATIVE: NaN is a float and NaT an instant; and every label present.
let floats = Index::new(vec![
IndexLabel::Float64(OrderedF64(1.5)),
IndexLabel::Null(NullKind::NaN),
]);
assert_eq!(floats.inferred_type(), "floating");
let instants = Index::new(vec![
IndexLabel::Datetime64(0),
IndexLabel::Null(NullKind::NaT),
]);
assert_eq!(instants.inferred_type(), "datetime64");
let bools = Index::new(vec![IndexLabel::Bool(true), IndexLabel::Bool(false)]);
assert_eq!(bools.dtype(), "bool");
let texts = Index::new(vec![IndexLabel::Utf8("a".into())]);
assert_eq!(texts.inferred_type(), "string");
}
#[test]
fn an_index_of_missing_labels_alone_is_typed_by_them_mzes1() {
use fp_types::NullKind;
// pd.Index([nan, nan]) / [nan, None]: float64 (it was object);
// [NaT, NaT]: datetime64[ns].
for labels in [
vec![
IndexLabel::Null(NullKind::NaN),
IndexLabel::Null(NullKind::NaN),
],
vec![
IndexLabel::Null(NullKind::NaN),
IndexLabel::Null(NullKind::Null),
],
] {
let index = Index::new(labels);
assert_eq!(index.inferred_type(), "floating");
assert_eq!(index.dtype(), "float64");
}
let nats = Index::new(vec![IndexLabel::Null(NullKind::NaT); 2]);
assert_eq!(nats.dtype(), "datetime64[ns]");
// NEGATIVE: None alone stays object ('mixed'), and no labels 'empty'.
let nones = Index::new(vec![IndexLabel::Null(NullKind::Null); 2]);
assert_eq!(nones.inferred_type(), "mixed");
assert_eq!(nones.dtype(), "object");
assert_eq!(Index::new(Vec::new()).inferred_type(), "empty");
}
#[test]
fn period_labels_make_a_period_index_45fzr() {
use fp_types::{Period, PeriodFreq};
// Ordinal 648 is 2024-01 monthly (54 years of 12 months).
let jan = Period::new(648, PeriodFreq::Monthly);
let feb = Period::new(649, PeriodFreq::Monthly);
let nat = Period::new(i64::MIN, PeriodFreq::Monthly);
let index = Index::new(vec![
IndexLabel::Period(feb),
IndexLabel::Period(jan),
IndexLabel::Period(nat),
]);
assert_eq!(index.labels()[0].to_string(), "2024-02");
assert_eq!(index.labels()[2].to_string(), "NaT");
assert!(index.labels()[2].is_missing());
assert!(!index.labels()[0].is_missing());
assert_eq!(index.inferred_type(), "period");
assert!(IndexLabel::Period(jan) < IndexLabel::Period(feb));
// A PeriodIndex and its labels round-trip.
let periods = PeriodIndex::from_index(&index).expect("periods of one freq");
assert_eq!(periods.freqstr().as_deref(), Some("M"));
assert_eq!(periods.to_index().labels(), index.labels());
// NEGATIVE: text that reads as periods is no PeriodIndex, nor are
// periods of two freqs (an object index there, as pandas').
assert!(PeriodIndex::from_index(&Index::from_utf8(vec!["2024-01".to_owned()])).is_none());
let mixed = Index::new(vec![
IndexLabel::Period(jan),
IndexLabel::Period(Period::new(0, PeriodFreq::Daily)),
]);
assert!(PeriodIndex::from_index(&mixed).is_none());
assert_eq!(mixed.inferred_type(), "mixed");
}
#[test]
fn int64_item_avoids_label_materialization_0633o() {
let typed = Index::from_i64_values(vec![42]);
assert!(typed.labels.materialized.get().is_none());
assert_eq!(typed.item().unwrap(), IndexLabel::Int64(42));
assert!(
typed.labels.materialized.get().is_none(),
"item should not materialize typed Int64 labels"
);
let affine = Index::new_known_unique_int64_affine_range(9, 3, 1).unwrap();
assert!(affine.labels.materialized.get().is_none());
assert_eq!(affine.item().unwrap(), IndexLabel::Int64(9));
assert!(
affine.labels.materialized.get().is_none(),
"item should not materialize affine Int64 labels"
);
}
#[test]
fn int64_dtype_predicates_avoid_label_materialization_gzi1i() {
let typed = Index::from_i64_values(vec![4, 0, -2]);
assert!(typed.labels.materialized.get().is_none());
assert_eq!(typed.inferred_type(), "integer");
assert_eq!(typed.dtype(), "int64");
assert_eq!(typed.dtypes(), vec!["int64"]);
assert!(typed.holds_integer());
assert!(typed.is_integer());
assert!(typed.is_numeric());
assert!(!typed.is_object());
assert!(
typed.labels.materialized.get().is_none(),
"dtype predicates should not materialize typed Int64 labels"
);
let affine = Index::new_known_unique_int64_affine_range(12, -4, 4).unwrap();
assert!(affine.labels.materialized.get().is_none());
assert_eq!(affine.inferred_type(), "integer");
assert_eq!(affine.dtype(), "int64");
assert!(affine.is_integer());
assert!(affine.is_numeric());
assert!(!affine.is_object());
assert!(
affine.labels.materialized.get().is_none(),
"dtype predicates should not materialize affine Int64 labels"
);
let empty = Index::from_i64_values(Vec::new());
assert!(empty.labels.materialized.get().is_none());
assert_eq!(empty.inferred_type(), "empty");
assert_eq!(empty.dtype(), "object");
assert!(!empty.is_integer());
assert!(!empty.is_numeric());
assert!(empty.is_object());
assert!(empty.labels.materialized.get().is_none());
}
#[test]
fn int64_monotonic_predicates_avoid_label_materialization_k9tlb() {
// Ascending affine range: O(1) via step sign, no materialization.
let asc = Index::new_known_unique_int64_affine_range(0, 2, 4).unwrap();
assert!(asc.labels.materialized.get().is_none());
assert!(asc.is_monotonic_increasing());
assert!(asc.is_monotonic());
assert!(!asc.is_monotonic_decreasing());
assert!(
asc.labels.materialized.get().is_none(),
"affine monotonic predicates must not materialize labels"
);
// Descending affine range.
let desc = Index::new_known_unique_int64_affine_range(12, -4, 4).unwrap();
assert!(desc.labels.materialized.get().is_none());
assert!(!desc.is_monotonic_increasing());
assert!(desc.is_monotonic_decreasing());
assert!(desc.labels.materialized.get().is_none());
// Typed non-affine Int64 that is neither ascending nor descending:
// scans the i64 view, still no label vector.
let unsorted = Index::from_i64_values(vec![4, 0, 7]);
assert!(unsorted.labels.materialized.get().is_none());
assert!(!unsorted.is_monotonic_increasing());
assert!(!unsorted.is_monotonic_decreasing());
assert!(
unsorted.labels.materialized.get().is_none(),
"typed Int64 monotonic predicates must not materialize labels"
);
let sorted = Index::from_i64_values(vec![-2, 0, 0, 4]);
assert!(sorted.is_monotonic_increasing());
assert!(!sorted.is_monotonic_decreasing());
assert!(sorted.labels.materialized.get().is_none());
let sorted_desc = Index::from_i64_values(vec![4, 0, 0, -2]);
assert!(!sorted_desc.is_monotonic_increasing());
assert!(sorted_desc.is_monotonic_decreasing());
// Single element / empty are trivially monotonic both ways.
let one = Index::from_i64_values(vec![7]);
assert!(one.is_monotonic_increasing() && one.is_monotonic_decreasing());
let empty = Index::from_i64_values(Vec::new());
assert!(empty.is_monotonic_increasing() && empty.is_monotonic_decreasing());
// Bit-identical to the object-label fallback path.
let obj = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(3),
IndexLabel::Int64(9),
]);
assert_eq!(
obj.is_monotonic_increasing(),
Index::from_i64_values(vec![1, 3, 3, 9]).is_monotonic_increasing()
);
assert_eq!(
obj.is_monotonic_decreasing(),
Index::from_i64_values(vec![1, 3, 3, 9]).is_monotonic_decreasing()
);
}
#[test]
fn datetime64_affine_monotonic_predicates_match_eager_oracle_jrlto() {
let cases = [
("ascending", 0, 2, 4),
("descending", 12, -4, 4),
("near_max", i64::MAX, -1, 3),
("singleton", 7, 0, 1),
("empty", 0, 0, 0),
];
for (name, start, step, len) in cases {
let affine = Index::from_datetime64_affine_range(start, step, len)
.expect("valid Datetime64 affine range");
let eager_values = (0..len)
.map(|offset| {
let offset = i64::try_from(offset).expect("test offset fits i64");
start
.checked_add(step.checked_mul(offset).expect("test span fits i64"))
.expect("test endpoint fits i64")
})
.collect();
let eager = Index::from_datetime64(eager_values);
assert!(
affine.labels.materialized.get().is_none(),
"{name}: affine labels must begin lazy",
);
assert_eq!(
affine.is_monotonic_increasing(),
eager.is_monotonic_increasing(),
"{name}: increasing predicate must match eager labels",
);
assert_eq!(
affine.is_monotonic_decreasing(),
eager.is_monotonic_decreasing(),
"{name}: decreasing predicate must match eager labels",
);
assert_eq!(
affine.is_monotonic(),
eager.is_monotonic(),
"{name}: monotonic alias must match eager labels",
);
assert!(
affine.labels.materialized.get().is_none(),
"{name}: affine monotonic predicates must not materialize labels",
);
assert!(
affine.labels.int64_typed.get().is_none(),
"{name}: affine monotonic predicates must not probe the Int64 view",
);
}
// NaT-bearing affine ranges must reject monotonicity without
// materializing their labels.
for (name, start, step) in [("nat_start", i64::MIN, 1), ("nat_end", i64::MIN + 2, -1)] {
let affine = Index::from_datetime64_affine_range(start, step, 3)
.expect("valid NaT-bearing Datetime64 affine range");
let eager_values = (0..3).map(|offset| start + step * offset).collect();
let eager = Index::from_datetime64(eager_values);
assert_eq!(
affine.is_monotonic_increasing(),
eager.is_monotonic_increasing(),
"{name}: increasing predicate must retain the eager fallback",
);
assert_eq!(
affine.is_monotonic_decreasing(),
eager.is_monotonic_decreasing(),
"{name}: decreasing predicate must retain the eager fallback",
);
assert!(
affine.labels.materialized.get().is_none(),
"{name}: NaT detection must keep affine labels lazy",
);
}
}
#[test]
fn datetime64_nat_is_not_monotonic_x6i5k() {
// pandas 2.2.3 reports both predicates false for a DatetimeIndex with
// NaT at every position, including the singleton case.
for (name, values) in [
("nat_start", vec![i64::MIN, 1, 2]),
("nat_middle", vec![1, i64::MIN, 2]),
("nat_end", vec![1, 2, i64::MIN]),
("reverse", vec![2, 1, i64::MIN]),
("singleton_nat", vec![i64::MIN]),
] {
let index = Index::from_datetime64(values);
assert!(
!index.is_monotonic_increasing(),
"{name}: NaT-bearing DatetimeIndex must not be increasing",
);
assert!(
!index.is_monotonic_decreasing(),
"{name}: NaT-bearing DatetimeIndex must not be decreasing",
);
assert!(
!index.is_monotonic(),
"{name}: monotonic alias must preserve increasing semantics",
);
}
}
#[test]
fn held_datetime_monotonic_flags_in_one_pass_pirog() {
// br-frankenpandas-pirog: held datetime labels answer both flags in
// one pass, as pandas' DatetimeIndex: equal neighbours keep an
// ascent, a descending pair breaks it, NaT anywhere breaks both.
// NEGATIVE: datetimes followed by a text label leave the pass at the
// text, and the generic label order answers, as before - it ranks
// text below a datetime, so an ascent into text is no ascent (pandas
// False too: a Timestamp and a str do not compare).
for (name, stamps, increasing, decreasing) in [
("equal neighbours", vec![1, 1, 2], true, false),
("all equal", vec![5, 5, 5], true, true),
("descending pair", vec![1, 3, 2], false, false),
("descending", vec![3, 2, 2], false, true),
("NaT first", vec![i64::MIN, 1, 2], false, false),
("NaT last of a descent", vec![2, 1, i64::MIN], false, false),
("empty", vec![], true, true),
] {
let index = Index::from_datetime64(stamps);
assert_eq!(
(
index.is_monotonic_increasing(),
index.is_monotonic_decreasing()
),
(increasing, decreasing),
"{name}"
);
}
let mixed = Index::new(vec![
IndexLabel::Datetime64(1),
IndexLabel::Datetime64(2),
IndexLabel::Utf8("a".to_owned()),
]);
assert!(!mixed.is_monotonic_increasing());
assert!(!mixed.is_monotonic_decreasing());
// The flags are remembered, shared by clones (a clone asked first
// answers the original); an index taken from a remembered one
// answers its own order.
let ascending = Index::from_datetime64(vec![1, 2, 3]);
assert!(ascending.clone().is_monotonic_increasing());
assert_eq!(ascending.monotonic_cache[0].get(), Some(&true));
assert!(ascending.is_monotonic_increasing());
let reversed = ascending.take(&[2, 1, 0]);
assert!(!reversed.is_monotonic_increasing());
assert!(reversed.is_monotonic_decreasing());
// An ascent read every label: the label kinds are kept from it (no
// second pass for a resampler's axis check). NEGATIVE: the mixed
// index's pass stopped at the text, so its kinds are its own.
let fresh = Index::from_datetime64(vec![4, 5, 6]);
assert!(fresh.is_monotonic_increasing());
let kept = crate::INDEX_LABEL_KINDS_CACHE
.get()
.and_then(|cache| cache.lock().ok()?.get(&fresh.label_identity).copied());
assert_eq!(kept, Some(crate::LabelKinds::DATETIME64));
assert_eq!(fresh.label_kinds(), crate::LabelKinds::DATETIME64);
assert!(mixed.label_kinds().intersects(crate::LabelKinds::UTF8));
}
#[test]
fn datetime64_affine_nunique_matches_eager_oracle_uls13() {
let cases = [
("empty", 0, 0, 0),
("singleton", 7, 0, 1),
("singleton_nat", i64::MIN, 0, 1),
("ascending", 0, 2, 4),
("nat_start", i64::MIN, 1, 4),
("nat_end", i64::MIN + 3, -1, 4),
("near_max", i64::MAX, -1, 3),
];
for (name, start, step, len) in cases {
let affine = Index::from_datetime64_affine_range(start, step, len)
.expect("valid Datetime64 affine range");
let eager_values = (0..len)
.map(|offset| {
let offset = i64::try_from(offset).expect("test offset fits i64");
start
.checked_add(step.checked_mul(offset).expect("test span fits i64"))
.expect("test endpoint fits i64")
})
.collect();
let eager = Index::from_datetime64(eager_values);
for dropna in [true, false] {
assert_eq!(
affine.nunique_with_dropna(dropna),
eager.nunique_with_dropna(dropna),
"{name}: dropna={dropna}",
);
}
assert!(
affine.labels.materialized.get().is_none(),
"{name}: affine nunique must not materialize labels",
);
assert!(
affine.labels.int64_typed.get().is_none(),
"{name}: affine nunique must not probe the Int64 view",
);
}
}
fn datetime64_nunique_former_body_uls13(index: &Index, dropna: bool) -> usize {
if let Some(affine) = index.labels.int64_affine_range() {
return affine.len;
}
if let Some(values) = index.labels.int64_view() {
return Index::nunique_i64(&values);
}
if let Some(ns) = index
.temporal_ns_present(true)
.or_else(|| index.temporal_ns_present(false))
{
return Index::nunique_i64(&ns);
}
index
.unique()
.labels
.iter()
.filter(|label| !dropna || !label.is_missing())
.count()
}
fn median_nanos_uls13(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
fn measure_nunique_nanos_uls13(f: impl FnOnce() -> usize) -> u128 {
let start = std::time::Instant::now();
std::hint::black_box(f());
start.elapsed().as_nanos()
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn datetime64_affine_nunique_ab_uls13() {
const LEN: usize = 1_000_000;
const SAMPLES: usize = 15;
let reference_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let reference_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let candidate_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let candidate_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
assert_eq!(
datetime64_nunique_former_body_uls13(&reference_a, true),
candidate_a.nunique(),
);
assert!(candidate_a.labels.materialized.get().is_none());
for _ in 0..3 {
std::hint::black_box(datetime64_nunique_former_body_uls13(&reference_a, true));
std::hint::black_box(datetime64_nunique_former_body_uls13(&reference_b, true));
std::hint::black_box(candidate_a.nunique());
std::hint::black_box(candidate_b.nunique());
}
let mut former_a = Vec::with_capacity(SAMPLES);
let mut former_b = Vec::with_capacity(SAMPLES);
let mut witness_a = Vec::with_capacity(SAMPLES);
let mut witness_b = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample % 2 == 0 {
former_a.push(measure_nunique_nanos_uls13(|| {
datetime64_nunique_former_body_uls13(&reference_a, true)
}));
witness_a.push(measure_nunique_nanos_uls13(|| candidate_a.nunique()));
witness_b.push(measure_nunique_nanos_uls13(|| candidate_b.nunique()));
former_b.push(measure_nunique_nanos_uls13(|| {
datetime64_nunique_former_body_uls13(&reference_b, true)
}));
} else {
former_b.push(measure_nunique_nanos_uls13(|| {
datetime64_nunique_former_body_uls13(&reference_b, true)
}));
witness_b.push(measure_nunique_nanos_uls13(|| candidate_b.nunique()));
witness_a.push(measure_nunique_nanos_uls13(|| candidate_a.nunique()));
former_a.push(measure_nunique_nanos_uls13(|| {
datetime64_nunique_former_body_uls13(&reference_a, true)
}));
}
}
let former_a_p50 = median_nanos_uls13(&mut former_a);
let former_b_p50 = median_nanos_uls13(&mut former_b);
let witness_a_p50 = median_nanos_uls13(&mut witness_a);
let witness_b_p50 = median_nanos_uls13(&mut witness_b);
let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
println!("affine Datetime64 nunique, len={LEN}, samples={SAMPLES}");
println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
println!(
"former/witness p50 ratio: {:.3}x",
former_mean / witness_mean
);
assert!(candidate_a.labels.materialized.get().is_none());
assert!(candidate_b.labels.materialized.get().is_none());
}
#[test]
fn datetime64_affine_min_matches_eager_oracle_hi31t() {
let cases = [
("empty", 0, 0, 0),
("singleton", 7, 0, 1),
("singleton_nat", i64::MIN, 0, 1),
("ascending", 0, 2, 4),
("descending", 12, -4, 4),
("nat_start", i64::MIN, 1, 4),
("nat_end", i64::MIN + 3, -1, 4),
("near_max", i64::MAX, -1, 3),
];
for (name, start, step, len) in cases {
let affine = Index::from_datetime64_affine_range(start, step, len)
.expect("valid Datetime64 affine range");
let eager_values = (0..len)
.map(|offset| {
let offset = i64::try_from(offset).expect("test offset fits i64");
start
.checked_add(step.checked_mul(offset).expect("test span fits i64"))
.expect("test endpoint fits i64")
})
.collect();
let eager = Index::from_datetime64(eager_values);
assert_eq!(affine.min(), eager.min(), "{name}");
assert!(
affine.labels.materialized.get().is_none(),
"{name}: affine min must not materialize labels",
);
assert!(
affine.labels.int64_typed.get().is_none(),
"{name}: affine min must not probe the Int64 view",
);
}
}
fn datetime64_min_former_body_hi31t(index: &Index) -> Option<IndexLabel> {
if let Some(affine) = index.labels.int64_affine_range() {
if affine.len == 0 {
return None;
}
let position = if affine.step >= 0 { 0 } else { affine.len - 1 };
return Some(IndexLabel::Int64(affine.value_at(position)));
}
if index.labels.has_lazy_int64_backing()
&& let Some(values) = index.labels.int64_view()
{
return values.iter().copied().min().map(IndexLabel::Int64);
}
index.labels.iter().min().cloned()
}
fn median_nanos_hi31t(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
fn measure_min_nanos_hi31t<T>(f: impl FnOnce() -> T) -> u128 {
let start = std::time::Instant::now();
std::hint::black_box(f());
start.elapsed().as_nanos()
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn datetime64_affine_min_ab_hi31t() {
const LEN: usize = 1_000_000;
const SAMPLES: usize = 15;
let reference_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let reference_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let candidate_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let candidate_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
assert_eq!(
datetime64_min_former_body_hi31t(&reference_a),
candidate_a.min(),
);
assert!(candidate_a.labels.materialized.get().is_none());
for _ in 0..3 {
std::hint::black_box(datetime64_min_former_body_hi31t(&reference_a));
std::hint::black_box(datetime64_min_former_body_hi31t(&reference_b));
std::hint::black_box(candidate_a.min());
std::hint::black_box(candidate_b.min());
}
let mut former_a = Vec::with_capacity(SAMPLES);
let mut former_b = Vec::with_capacity(SAMPLES);
let mut witness_a = Vec::with_capacity(SAMPLES);
let mut witness_b = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample % 2 == 0 {
former_a.push(measure_min_nanos_hi31t(|| {
datetime64_min_former_body_hi31t(&reference_a)
}));
witness_a.push(measure_min_nanos_hi31t(|| candidate_a.min()));
witness_b.push(measure_min_nanos_hi31t(|| candidate_b.min()));
former_b.push(measure_min_nanos_hi31t(|| {
datetime64_min_former_body_hi31t(&reference_b)
}));
} else {
former_b.push(measure_min_nanos_hi31t(|| {
datetime64_min_former_body_hi31t(&reference_b)
}));
witness_b.push(measure_min_nanos_hi31t(|| candidate_b.min()));
witness_a.push(measure_min_nanos_hi31t(|| candidate_a.min()));
former_a.push(measure_min_nanos_hi31t(|| {
datetime64_min_former_body_hi31t(&reference_a)
}));
}
}
let former_a_p50 = median_nanos_hi31t(&mut former_a);
let former_b_p50 = median_nanos_hi31t(&mut former_b);
let witness_a_p50 = median_nanos_hi31t(&mut witness_a);
let witness_b_p50 = median_nanos_hi31t(&mut witness_b);
let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
println!("affine Datetime64 min, len={LEN}, samples={SAMPLES}");
println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
println!(
"former/witness p50 ratio: {:.3}x",
former_mean / witness_mean
);
assert!(candidate_a.labels.materialized.get().is_none());
assert!(candidate_b.labels.materialized.get().is_none());
}
#[test]
fn datetime64_affine_max_matches_eager_oracle_nsexq() {
let cases = [
("empty", 0, 0, 0),
("singleton", 7, 0, 1),
("singleton_nat", i64::MIN, 0, 1),
("ascending", 0, 2, 4),
("descending", 12, -4, 4),
("nat_start", i64::MIN, 1, 4),
("nat_end", i64::MIN + 3, -1, 4),
("near_max", i64::MAX, -1, 3),
];
for (name, start, step, len) in cases {
let affine = Index::from_datetime64_affine_range(start, step, len)
.expect("valid Datetime64 affine range");
let eager_values = (0..len)
.map(|offset| {
let offset = i64::try_from(offset).expect("test offset fits i64");
start
.checked_add(step.checked_mul(offset).expect("test span fits i64"))
.expect("test endpoint fits i64")
})
.collect();
let eager = Index::from_datetime64(eager_values);
assert_eq!(affine.max(), eager.max(), "{name}");
assert!(
affine.labels.materialized.get().is_none(),
"{name}: affine max must not materialize labels",
);
assert!(
affine.labels.int64_typed.get().is_none(),
"{name}: affine max must not probe the Int64 view",
);
}
}
fn datetime64_max_former_body_nsexq(index: &Index) -> Option<IndexLabel> {
if let Some(affine) = index.labels.int64_affine_range() {
if affine.len == 0 {
return None;
}
let position = if affine.step >= 0 { affine.len - 1 } else { 0 };
return Some(IndexLabel::Int64(affine.value_at(position)));
}
if index.labels.has_lazy_int64_backing()
&& let Some(values) = index.labels.int64_view()
{
return values.iter().copied().max().map(IndexLabel::Int64);
}
index.labels.iter().max().cloned()
}
fn median_nanos_nsexq(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
fn measure_max_nanos_nsexq<T>(f: impl FnOnce() -> T) -> u128 {
let start = std::time::Instant::now();
std::hint::black_box(f());
start.elapsed().as_nanos()
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn datetime64_affine_max_ab_nsexq() {
const LEN: usize = 1_000_000;
const SAMPLES: usize = 15;
let reference_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let reference_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let candidate_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let candidate_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
assert_eq!(
datetime64_max_former_body_nsexq(&reference_a),
candidate_a.max(),
);
assert!(candidate_a.labels.materialized.get().is_none());
for _ in 0..3 {
std::hint::black_box(datetime64_max_former_body_nsexq(&reference_a));
std::hint::black_box(datetime64_max_former_body_nsexq(&reference_b));
std::hint::black_box(candidate_a.max());
std::hint::black_box(candidate_b.max());
}
let mut former_a = Vec::with_capacity(SAMPLES);
let mut former_b = Vec::with_capacity(SAMPLES);
let mut witness_a = Vec::with_capacity(SAMPLES);
let mut witness_b = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample % 2 == 0 {
former_a.push(measure_max_nanos_nsexq(|| {
datetime64_max_former_body_nsexq(&reference_a)
}));
witness_a.push(measure_max_nanos_nsexq(|| candidate_a.max()));
witness_b.push(measure_max_nanos_nsexq(|| candidate_b.max()));
former_b.push(measure_max_nanos_nsexq(|| {
datetime64_max_former_body_nsexq(&reference_b)
}));
} else {
former_b.push(measure_max_nanos_nsexq(|| {
datetime64_max_former_body_nsexq(&reference_b)
}));
witness_b.push(measure_max_nanos_nsexq(|| candidate_b.max()));
witness_a.push(measure_max_nanos_nsexq(|| candidate_a.max()));
former_a.push(measure_max_nanos_nsexq(|| {
datetime64_max_former_body_nsexq(&reference_a)
}));
}
}
let former_a_p50 = median_nanos_nsexq(&mut former_a);
let former_b_p50 = median_nanos_nsexq(&mut former_b);
let witness_a_p50 = median_nanos_nsexq(&mut witness_a);
let witness_b_p50 = median_nanos_nsexq(&mut witness_b);
let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
println!("affine Datetime64 max, len={LEN}, samples={SAMPLES}");
println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
println!(
"former/witness p50 ratio: {:.3}x",
former_mean / witness_mean
);
assert!(candidate_a.labels.materialized.get().is_none());
assert!(candidate_b.labels.materialized.get().is_none());
}
#[test]
fn datetime64_affine_argmin_matches_eager_oracle_wxjca() {
let cases = [
("empty", 0, 0, 0),
("singleton", 7, 0, 1),
("singleton_nat", i64::MIN, 0, 1),
("ascending", 0, 2, 4),
("descending", 12, -4, 4),
("nat_start", i64::MIN, 1, 4),
("nat_end", i64::MIN + 3, -1, 4),
("near_max", i64::MAX, -1, 3),
];
for (name, start, step, len) in cases {
let affine = Index::from_datetime64_affine_range(start, step, len)
.expect("valid Datetime64 affine range");
let eager_values = (0..len)
.map(|offset| {
let offset = i64::try_from(offset).expect("test offset fits i64");
start
.checked_add(step.checked_mul(offset).expect("test span fits i64"))
.expect("test endpoint fits i64")
})
.collect();
let eager = Index::from_datetime64(eager_values);
assert_eq!(affine.argmin(), eager.argmin(), "{name}");
assert!(
affine.labels.materialized.get().is_none(),
"{name}: affine argmin must not materialize labels",
);
assert!(
affine.labels.int64_typed.get().is_none(),
"{name}: affine argmin must not probe the Int64 view",
);
}
}
fn datetime64_argmin_former_body_wxjca(index: &Index) -> Option<usize> {
if let Some(affine) = index.labels.int64_affine_range() {
return (affine.len > 0).then(|| if affine.step >= 0 { 0 } else { affine.len - 1 });
}
if index.labels.has_lazy_int64_backing()
&& let Some(values) = index.labels.int64_view()
{
return values
.iter()
.enumerate()
.min_by(|(_, a), (_, b)| a.cmp(b))
.map(|(i, _)| i);
}
index
.labels
.iter()
.enumerate()
.min_by(|(_, a), (_, b)| a.cmp(b))
.map(|(i, _)| i)
}
fn median_nanos_wxjca(samples: &mut [u128]) -> u128 {
samples.sort_unstable();
samples[samples.len() / 2]
}
fn measure_argmin_nanos_wxjca<T>(f: impl FnOnce() -> T) -> u128 {
let start = std::time::Instant::now();
std::hint::black_box(f());
start.elapsed().as_nanos()
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn datetime64_affine_argmin_ab_wxjca() {
const LEN: usize = 1_000_000;
const SAMPLES: usize = 15;
let reference_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let reference_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let candidate_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let candidate_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
assert_eq!(
datetime64_argmin_former_body_wxjca(&reference_a),
candidate_a.argmin(),
);
assert!(candidate_a.labels.materialized.get().is_none());
for _ in 0..3 {
std::hint::black_box(datetime64_argmin_former_body_wxjca(&reference_a));
std::hint::black_box(datetime64_argmin_former_body_wxjca(&reference_b));
std::hint::black_box(candidate_a.argmin());
std::hint::black_box(candidate_b.argmin());
}
let mut former_a = Vec::with_capacity(SAMPLES);
let mut former_b = Vec::with_capacity(SAMPLES);
let mut witness_a = Vec::with_capacity(SAMPLES);
let mut witness_b = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample % 2 == 0 {
former_a.push(measure_argmin_nanos_wxjca(|| {
datetime64_argmin_former_body_wxjca(&reference_a)
}));
witness_a.push(measure_argmin_nanos_wxjca(|| candidate_a.argmin()));
witness_b.push(measure_argmin_nanos_wxjca(|| candidate_b.argmin()));
former_b.push(measure_argmin_nanos_wxjca(|| {
datetime64_argmin_former_body_wxjca(&reference_b)
}));
} else {
former_b.push(measure_argmin_nanos_wxjca(|| {
datetime64_argmin_former_body_wxjca(&reference_b)
}));
witness_b.push(measure_argmin_nanos_wxjca(|| candidate_b.argmin()));
witness_a.push(measure_argmin_nanos_wxjca(|| candidate_a.argmin()));
former_a.push(measure_argmin_nanos_wxjca(|| {
datetime64_argmin_former_body_wxjca(&reference_a)
}));
}
}
let former_a_p50 = median_nanos_wxjca(&mut former_a);
let former_b_p50 = median_nanos_wxjca(&mut former_b);
let witness_a_p50 = median_nanos_wxjca(&mut witness_a);
let witness_b_p50 = median_nanos_wxjca(&mut witness_b);
let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
println!("affine Datetime64 argmin, len={LEN}, samples={SAMPLES}");
println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
println!(
"former/witness p50 ratio: {:.3}x",
former_mean / witness_mean
);
assert!(candidate_a.labels.materialized.get().is_none());
assert!(candidate_b.labels.materialized.get().is_none());
}
#[test]
fn datetime64_affine_argmax_matches_eager_oracle_h453b() {
let cases = [
("empty", 0, 0, 0),
("singleton", 7, 0, 1),
("singleton_nat", i64::MIN, 0, 1),
("ascending", 0, 2, 4),
("descending", 12, -4, 4),
("nat_start", i64::MIN, 1, 4),
("nat_end", i64::MIN + 3, -1, 4),
("near_max", i64::MAX, -1, 3),
];
for (name, start, step, len) in cases {
let affine = Index::from_datetime64_affine_range(start, step, len)
.expect("valid Datetime64 affine range");
let eager_values = (0..len)
.map(|offset| {
let offset = i64::try_from(offset).expect("test offset fits i64");
start
.checked_add(step.checked_mul(offset).expect("test span fits i64"))
.expect("test endpoint fits i64")
})
.collect();
let eager = Index::from_datetime64(eager_values);
assert_eq!(affine.argmax(), eager.argmax(), "{name}");
assert!(
affine.labels.materialized.get().is_none(),
"{name}: affine argmax must not materialize labels",
);
assert!(
affine.labels.int64_typed.get().is_none(),
"{name}: affine argmax must not probe the Int64 view",
);
}
}
fn datetime64_argmax_former_body_h453b(index: &Index) -> Option<usize> {
if let Some(affine) = index.labels.int64_affine_range() {
return (affine.len > 0).then(|| if affine.step >= 0 { affine.len - 1 } else { 0 });
}
if index.labels.has_lazy_int64_backing()
&& let Some(values) = index.labels.int64_view()
{
return values
.iter()
.enumerate()
.max_by(|(_, a), (_, b)| a.cmp(b))
.map(|(i, _)| i);
}
index
.labels
.iter()
.enumerate()
.max_by(|(_, a), (_, b)| a.cmp(b))
.map(|(i, _)| i)
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn datetime64_affine_argmax_profile_h453b() {
const LEN: usize = 250_000;
const SAMPLES: usize = 10;
let former_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let former_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let witness_a = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
let witness_b = Index::from_datetime64_affine_range(0, 1, LEN).unwrap();
assert_eq!(
datetime64_argmax_former_body_h453b(&former_a),
witness_a.argmax(),
);
for _ in 0..3 {
std::hint::black_box(datetime64_argmax_former_body_h453b(&former_a));
std::hint::black_box(witness_a.argmax());
std::hint::black_box(witness_b.argmax());
std::hint::black_box(datetime64_argmax_former_body_h453b(&former_b));
}
let measure = |f: &dyn Fn() -> Option<usize>| {
let started = std::time::Instant::now();
std::hint::black_box(f());
started.elapsed().as_nanos()
};
let mut former_a_ns = Vec::with_capacity(SAMPLES);
let mut former_b_ns = Vec::with_capacity(SAMPLES);
let mut witness_a_ns = Vec::with_capacity(SAMPLES);
let mut witness_b_ns = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample % 2 == 0 {
former_a_ns.push(measure(&|| datetime64_argmax_former_body_h453b(&former_a)));
witness_a_ns.push(measure(&|| witness_a.argmax()));
witness_b_ns.push(measure(&|| witness_b.argmax()));
former_b_ns.push(measure(&|| datetime64_argmax_former_body_h453b(&former_b)));
} else {
former_b_ns.push(measure(&|| datetime64_argmax_former_body_h453b(&former_b)));
witness_b_ns.push(measure(&|| witness_b.argmax()));
witness_a_ns.push(measure(&|| witness_a.argmax()));
former_a_ns.push(measure(&|| datetime64_argmax_former_body_h453b(&former_a)));
}
}
for samples in [
&mut former_a_ns,
&mut former_b_ns,
&mut witness_a_ns,
&mut witness_b_ns,
] {
samples.sort_unstable();
}
let middle = SAMPLES / 2;
let former_a_p50 = former_a_ns[middle];
let former_b_p50 = former_b_ns[middle];
let witness_a_p50 = witness_a_ns[middle];
let witness_b_p50 = witness_b_ns[middle];
let former_mean = (former_a_p50 + former_b_p50) as f64 / 2.0;
let witness_mean = (witness_a_p50 + witness_b_p50) as f64 / 2.0;
println!("affine Datetime64 argmax, len={LEN}, samples={SAMPLES}");
println!("former body p50 A/B: {former_a_p50} / {former_b_p50} ns");
println!("affine witness p50 A/B: {witness_a_p50} / {witness_b_p50} ns");
println!(
"former/witness p50 ratio: {:.3}x",
former_mean / witness_mean
);
}
#[test]
fn int64_argminmax_avoid_label_materialization_ikbh9() {
// Ascending affine [0,2,4,6]: argmin=0, argmax=len-1. O(1), no materialization.
let asc = Index::new_known_unique_int64_affine_range(0, 2, 4).unwrap();
assert!(asc.labels.materialized.get().is_none());
assert_eq!(asc.argmin(), Some(0));
assert_eq!(asc.argmax(), Some(3));
assert!(
asc.labels.materialized.get().is_none(),
"affine argmin/argmax must not materialize labels"
);
// Descending affine [12,8,4,0]: argmin at the end, argmax at the front.
let desc = Index::new_known_unique_int64_affine_range(12, -4, 4).unwrap();
assert!(desc.labels.materialized.get().is_none());
assert_eq!(desc.argmin(), Some(3));
assert_eq!(desc.argmax(), Some(0));
assert!(desc.labels.materialized.get().is_none());
// Typed Int64 with ties. Rust's min_by returns the FIRST of equal
// minima, max_by the LAST of equal maxima — the i64-view fast path must
// match exactly. [3,1,1,2] -> min 1 first at idx 1; max 3 unique at idx 0.
let tied = Index::from_i64_values(vec![3, 1, 1, 2]);
assert!(tied.labels.materialized.get().is_none());
assert_eq!(tied.argmin(), Some(1));
assert_eq!(tied.argmax(), Some(0));
assert!(
tied.labels.materialized.get().is_none(),
"typed Int64 argmin/argmax must not materialize labels"
);
// Bit-identical to the object-label path (which also has ties).
let obj = Index::new(vec![
IndexLabel::Int64(3),
IndexLabel::Int64(1),
IndexLabel::Int64(1),
IndexLabel::Int64(2),
]);
assert_eq!(obj.argmin(), tied.argmin());
assert_eq!(obj.argmax(), tied.argmax());
// Tied maxima: [5,2,5,1] -> max 5 at idx 0,2 -> max_by last = 2; min 1 at idx 3.
let tied_max = Index::from_i64_values(vec![5, 2, 5, 1]);
assert_eq!(tied_max.argmax(), Some(2));
assert_eq!(tied_max.argmin(), Some(3));
// Single element and empty.
assert_eq!(Index::from_i64_values(vec![7]).argmin(), Some(0));
assert_eq!(Index::from_i64_values(vec![7]).argmax(), Some(0));
assert_eq!(Index::from_i64_values(Vec::new()).argmin(), None);
assert_eq!(Index::from_i64_values(Vec::new()).argmax(), None);
}
#[test]
fn int64_minmax_avoid_label_materialization_uza04151() {
// Ascending affine [0,2,4,6]: min/max are closed-form endpoints.
let asc = Index::new_known_unique_int64_affine_range(0, 2, 4).unwrap();
assert!(asc.labels.materialized.get().is_none());
assert_eq!(asc.min(), Some(IndexLabel::Int64(0)));
assert_eq!(asc.max(), Some(IndexLabel::Int64(6)));
assert!(
asc.labels.materialized.get().is_none(),
"affine min/max must not materialize labels"
);
// Descending affine [12,8,4,0]: min/max swap endpoints.
let desc = Index::new_known_unique_int64_affine_range(12, -4, 4).unwrap();
assert!(desc.labels.materialized.get().is_none());
assert_eq!(desc.min(), Some(IndexLabel::Int64(0)));
assert_eq!(desc.max(), Some(IndexLabel::Int64(12)));
assert!(desc.labels.materialized.get().is_none());
// Lazy typed Int64 scans the raw i64 view, preserving scalar results.
let typed = Index::from_i64_values(vec![5, 2, 5, 1]);
assert!(typed.labels.materialized.get().is_none());
assert_eq!(typed.min(), Some(IndexLabel::Int64(1)));
assert_eq!(typed.max(), Some(IndexLabel::Int64(5)));
assert!(
typed.labels.materialized.get().is_none(),
"typed Int64 min/max must not materialize labels"
);
let obj = Index::new(vec![
IndexLabel::Int64(5),
IndexLabel::Int64(2),
IndexLabel::Int64(5),
IndexLabel::Int64(1),
]);
assert_eq!(obj.min(), typed.min());
assert_eq!(obj.max(), typed.max());
assert_eq!(Index::from_i64_values(Vec::new()).min(), None);
assert_eq!(Index::from_i64_values(Vec::new()).max(), None);
}
#[test]
fn int64_nunique_avoid_label_materialization_a55d8() {
// Affine range: nunique == len for either dropna, no materialization.
let asc = Index::new_known_unique_int64_affine_range(0, 2, 5).unwrap();
assert!(asc.labels.materialized.get().is_none());
assert_eq!(asc.nunique(), 5);
assert_eq!(asc.nunique_with_dropna(false), 5);
assert!(
asc.labels.materialized.get().is_none(),
"affine nunique must not materialize labels"
);
// Descending affine and unit range behave the same.
let desc = Index::new_known_unique_int64_affine_range(20, -5, 4).unwrap();
assert_eq!(desc.nunique(), 4);
assert!(desc.labels.materialized.get().is_none());
// Equivalence vs the object-label path (with a duplicate).
let obj = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(1),
IndexLabel::Int64(2),
]);
assert_eq!(obj.nunique(), 2);
}
#[test]
fn sorted_int64_get_indexer_avoids_label_materialization_codb() {
let source = Index::from_i64_values(vec![1, 3, 5, 9]).set_name("n");
let sorted_target = Index::from_i64_values(vec![0, 3, 3, 6, 9]);
let unsorted_target = Index::from_i64_values(vec![9, 1, 4, 5]);
assert!(source.labels.materialized.get().is_none());
assert!(sorted_target.labels.materialized.get().is_none());
assert!(unsorted_target.labels.materialized.get().is_none());
let sorted_actual = source.get_indexer(&sorted_target);
let unsorted_actual = source.get_indexer(&unsorted_target);
assert_eq!(sorted_actual, vec![None, Some(1), Some(1), None, Some(3)]);
assert_eq!(unsorted_actual, vec![Some(3), Some(0), None, Some(2)]);
assert!(
source.labels.materialized.get().is_none(),
"sorted Int64 source should stay on raw backing"
);
assert!(
sorted_target.labels.materialized.get().is_none(),
"sorted Int64 target should stay on raw backing"
);
assert!(
unsorted_target.labels.materialized.get().is_none(),
"unsorted Int64 target should stay on raw backing"
);
let materialized_source = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(5),
IndexLabel::Int64(9),
]);
let materialized_sorted_target = Index::new(vec![
IndexLabel::Int64(0),
IndexLabel::Int64(3),
IndexLabel::Int64(3),
IndexLabel::Int64(6),
IndexLabel::Int64(9),
]);
let materialized_unsorted_target = Index::new(vec![
IndexLabel::Int64(9),
IndexLabel::Int64(1),
IndexLabel::Int64(4),
IndexLabel::Int64(5),
]);
assert_eq!(
sorted_actual,
materialized_source.get_indexer(&materialized_sorted_target)
);
assert_eq!(
unsorted_actual,
materialized_source.get_indexer(&materialized_unsorted_target)
);
}
#[test]
fn int64_position_avoids_label_materialization_codb() {
let sorted = Index::from_i64_values(vec![1, 3, 5, 9]);
let unsorted = Index::from_i64_values(vec![5, 1, 5, 3]);
assert!(sorted.labels.materialized.get().is_none());
assert!(unsorted.labels.materialized.get().is_none());
assert_eq!(sorted.position(&IndexLabel::Int64(5)), Some(2));
assert_eq!(sorted.get_loc(&IndexLabel::Int64(7)), None);
assert!(!sorted.contains(&IndexLabel::Utf8("5".to_owned())));
assert_eq!(unsorted.position(&IndexLabel::Int64(5)), Some(0));
assert_eq!(unsorted.position(&IndexLabel::Int64(3)), Some(3));
assert!(
sorted.labels.materialized.get().is_none(),
"sorted Int64 position should stay on raw backing"
);
assert!(
unsorted.labels.materialized.get().is_none(),
"unsorted Int64 position should stay on raw backing"
);
let materialized_sorted = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(5),
IndexLabel::Int64(9),
]);
let materialized_unsorted = Index::new(vec![
IndexLabel::Int64(5),
IndexLabel::Int64(1),
IndexLabel::Int64(5),
IndexLabel::Int64(3),
]);
assert_eq!(
sorted.position(&IndexLabel::Int64(5)),
materialized_sorted.position(&IndexLabel::Int64(5))
);
assert_eq!(
unsorted.position(&IndexLabel::Int64(5)),
materialized_unsorted.position(&IndexLabel::Int64(5))
);
}
#[test]
fn int64_index_mutation_fast_paths_match_materialized_2bgtq() {
// Differential harness (br-frankenpandas-2bgtq): insert (uza04.152),
// delete (uza04.150), groupby (xk18v) and take on lazy Int64 indexes must
// produce the same result as the materialized fallback. Deterministic
// seeded LCG — no rand crate, no mocks.
let mut state: u64 = 0x84242_u64.wrapping_mul(0x9e37_79b9);
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..2500u32 {
let len = (next() % 11) as usize;
let mut vals: Vec<i64> = (0..len).map(|_| (next() % 9) as i64 - 4).collect();
if next() % 3 == 0 {
vals.sort_unstable();
}
let lazy = Index::from_i64_values(vals.clone());
let mat = Index::new(
vals.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
);
let ctx = format!("iter={iter} vals={vals:?}");
// groupby (xk18v): label -> positions map must match exactly.
assert_eq!(lazy.groupby(), mat.groupby(), "groupby {ctx}");
// insert (uza04.152) at a random valid loc with an Int64 item and,
// occasionally, a non-Int64 item to exercise the dtype transition.
let loc = (next() as usize) % (len + 1);
let item = if next() % 4 == 0 {
IndexLabel::Utf8(format!("s{}", next() % 3))
} else {
IndexLabel::Int64((next() % 11) as i64 - 5)
};
let li = lazy.insert(loc, item.clone());
let mi = mat.insert(loc, item.clone());
assert_eq!(li.is_ok(), mi.is_ok(), "insert ok {ctx} loc={loc}");
if let (Ok(a), Ok(b)) = (&li, &mi) {
assert_eq!(
a.labels(),
b.labels(),
"insert labels {ctx} loc={loc} item={item:?}"
);
}
// delete (uza04.150) at a random valid loc.
if len > 0 {
let dloc = (next() as usize) % len;
let ld = lazy.delete(dloc);
let md = mat.delete(dloc);
assert_eq!(ld.is_ok(), md.is_ok(), "delete ok {ctx} dloc={dloc}");
if let (Ok(a), Ok(b)) = (&ld, &md) {
assert_eq!(a.labels(), b.labels(), "delete labels {ctx} dloc={dloc}");
}
// take with random in-range positions (possibly repeated / reordered).
let k = (next() % 6) as usize;
let positions: Vec<usize> = (0..k).map(|_| (next() as usize) % len).collect();
assert_eq!(
lazy.take(&positions).labels(),
mat.take(&positions).labels(),
"take {ctx} positions={positions:?}"
);
}
}
}
#[test]
fn int64_affine_lookup_fast_paths_match_materialized_q70pn() {
// Differential harness (br-frankenpandas-q70pn): affine Int64 lookup fast
// paths (searchsorted arithmetic lngwv, asof 1851g/4jr8s, affine get_loc/
// position) must agree with the materialized binary-search/linear fallback
// for every query. Deterministic seeded LCG — no rand crate, no mocks.
let mut state: u64 = 0x2545_f491_4f6c_dd1d;
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..2000u32 {
// Ascending affine range (step > 0) so searchsorted/asof are valid.
let len = (next() % 9) as usize + 1;
let start = (next() % 11) as i64 - 5;
let step = (next() % 4) as i64 + 1; // 1..=4
let Some(affine) = Index::new_known_unique_int64_affine_range(start, step, len) else {
continue;
};
let vals: Vec<i64> = (0..len as i64).map(|i| start + step * i).collect();
let mat = Index::new(
vals.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
);
// Query span: below min, exact elements, between elements, above max.
let lo = start - 2;
let hi = start + step * (len as i64 - 1) + 2;
for q in lo..=hi {
let label = IndexLabel::Int64(q);
let ctx = format!("iter={iter} start={start} step={step} len={len} q={q}");
assert_eq!(affine.get_loc(&label), mat.get_loc(&label), "get_loc {ctx}");
assert_eq!(
affine.position(&label),
mat.position(&label),
"position {ctx}"
);
assert_eq!(affine.asof(&label), mat.asof(&label), "asof {ctx}");
for side in ["left", "right"] {
assert_eq!(
affine.searchsorted(&label, side).unwrap(),
mat.searchsorted(&label, side).unwrap(),
"searchsorted side={side} {ctx}"
);
}
}
// get_indexer over a small mixed target (present + absent keys).
let targ_vals: Vec<i64> = (0..4).map(|_| (next() % 14) as i64 - 6).collect();
let target = Index::new(
targ_vals
.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
);
assert_eq!(
affine.get_indexer(&target),
mat.get_indexer(&target),
"get_indexer iter={iter} targ={targ_vals:?}"
);
}
}
#[test]
fn affine_get_indexer_probes_typed_targets_without_materializing_3gsa7() {
let source = Index::new_known_unique_int64_affine_range(10, 2, 5).unwrap();
let targets = Index::from_i64_values(vec![10, 11, 16, 99, 12]);
assert_eq!(
source.get_indexer(&targets),
vec![Some(0), None, Some(3), None, Some(1)]
);
assert!(
source.cached_int64_label_values().is_none(),
"affine source lookup must not materialize an i64 label vector"
);
assert!(
targets.labels.materialized.get().is_none(),
"typed target lookup must not box values into IndexLabel"
);
let all_miss = Index::new_known_unique_int64_affine_range(11, 2, 5).unwrap();
assert_eq!(source.get_indexer(&all_miss), vec![None; 5]);
assert!(all_miss.cached_int64_label_values().is_none());
let descending = Index::new_known_unique_int64_affine_range(18, -2, 5).unwrap();
assert_eq!(
descending.get_indexer(&targets),
vec![Some(4), None, Some(1), None, Some(3)]
);
assert!(descending.cached_int64_label_values().is_none());
// Planted negative: a non-Int64 target cannot match an affine Int64
// source and must not be treated as a numerically compatible label.
let non_int64 = Index::new(vec![IndexLabel::Utf8("10".to_owned())]);
assert_eq!(source.get_indexer(&non_int64), vec![None]);
}
#[test]
fn affine_index_searchsorted_avoids_materialization_lngwv() {
let affine = Index::new_known_unique_int64_affine_range(1, 2, 4).unwrap();
for (needle, left, right) in [(0, 0, 0), (1, 0, 1), (2, 1, 1), (7, 3, 4), (8, 4, 4)] {
let needle = IndexLabel::Int64(needle);
assert_eq!(affine.searchsorted(&needle, "left").unwrap(), left);
assert_eq!(affine.searchsorted(&needle, "right").unwrap(), right);
}
assert!(
affine.cached_int64_label_values().is_none(),
"affine searchsorted should not materialize the raw i64 view"
);
let extreme = Index::new_known_unique_int64_affine_range(i64::MIN, i64::MAX, 2).unwrap();
for (needle, left, right) in [
(i64::MIN, 0, 1),
(i64::MIN + 1, 1, 1),
(-1, 1, 2),
(i64::MAX, 2, 2),
] {
let needle = IndexLabel::Int64(needle);
assert_eq!(extreme.searchsorted(&needle, "left").unwrap(), left);
assert_eq!(extreme.searchsorted(&needle, "right").unwrap(), right);
}
assert!(extreme.cached_int64_label_values().is_none());
let singleton = Index::new_known_unique_int64_affine_range(7, i64::MIN, 1).unwrap();
for (needle, left, right) in [(6, 0, 0), (7, 0, 1), (8, 1, 1)] {
let needle = IndexLabel::Int64(needle);
assert_eq!(singleton.searchsorted(&needle, "left").unwrap(), left);
assert_eq!(singleton.searchsorted(&needle, "right").unwrap(), right);
}
assert!(singleton.cached_int64_label_values().is_none());
let empty = Index::new_known_unique_int64_affine_range(0, 0, 0).unwrap();
assert_eq!(
empty
.searchsorted(&IndexLabel::Int64(i64::MAX), "right")
.unwrap(),
0
);
assert!(empty.cached_int64_label_values().is_none());
}
#[test]
fn affine_take_arithmetic_positions_match_materialized_blackthrush() {
// Differential harness (BlackThrush): the affine-in/affine-out `take`
// fast paths (`Index::take_affine_positions` + `RangeIndex::take_
// arithmetic_positions`) must produce the identical labels, in the
// identical order, as a materialized gather — for arithmetic position
// sequences (the fast path) AND non-arithmetic ones (the fallback).
// Deterministic seeded LCG, no rand crate, no mocks.
let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
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..3000u32 {
let len = (next() % 40) as usize + 1;
let start = (next() % 21) as i64 - 10;
let step = (next() % 7) as i64 - 3; // -3..=3 (incl. 0)
let Some(affine) = Index::new_known_unique_int64_affine_range(start, step, len) else {
continue;
};
let vals: Vec<i64> = (0..len as i64)
.map(|i| start.checked_add(step.checked_mul(i).unwrap()).unwrap())
.collect();
let mat = Index::new(
vals.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
);
// RangeIndex equivalent (positive step only; RangeIndex requires it).
let range = if step > 0 {
RangeIndex::new(start, start + step * len as i64, step).ok()
} else {
None
};
// Build a position sequence: arithmetic (constant stride) most of the
// time, occasionally non-arithmetic, occasionally empty/single.
let mode = next() % 5;
let positions: Vec<usize> = match mode {
0 => Vec::new(),
1 => vec![(next() as usize) % len],
2 | 3 => {
// arithmetic in-bounds: pick pstart, pstep, count s.t. all < len.
let count = (next() % 8) as usize + 2;
let pstep = (next() % 3) as usize + 1;
let max_start = len.saturating_sub(1 + pstep * (count - 1));
if max_start == 0 && len <= pstep * (count - 1) {
continue;
}
let pstart = (next() as usize) % (max_start + 1);
(0..count).map(|k| pstart + pstep * k).collect()
}
_ => {
// arbitrary (likely non-arithmetic) in-bounds positions.
let count = (next() % 6) as usize + 1;
(0..count).map(|_| (next() as usize) % len).collect()
}
};
let ctx = format!("iter={iter} start={start} step={step} len={len} pos={positions:?}");
let oracle: Vec<IndexLabel> = positions
.iter()
.map(|&p| IndexLabel::Int64(vals[p]))
.collect();
assert_eq!(
affine.take(&positions).labels(),
oracle,
"affine take {ctx}"
);
assert_eq!(
mat.take(&positions).labels(),
oracle,
"materialized take {ctx}"
);
if let Some(range) = &range {
let got = range.take(&positions).expect("range take in-bounds");
assert_eq!(got.labels(), oracle, "range take {ctx}");
}
}
}
#[test]
fn arithmetic_take_stays_lazy_and_range_reports_oob_3gsa7() {
let affine = Index::new_known_unique_int64_affine_range(10, 3, 10).unwrap();
let taken = affine.take(&[1, 3, 5]);
assert_eq!(
taken.labels.int64_affine_range(),
Some(Int64AffineLabels {
start: 13,
step: 6,
len: 3,
})
);
assert!(
taken.cached_int64_label_values().is_none(),
"arithmetic Index::take must retain its affine witness without raw-label materialization"
);
let range = RangeIndex::new(10, 40, 3).unwrap();
let range_taken = range.take(&[1, 3, 5]).unwrap();
assert_eq!(
range_taken.labels.int64_affine_range(),
taken.labels.int64_affine_range()
);
assert!(
range_taken.cached_int64_label_values().is_none(),
"arithmetic RangeIndex::take must retain its affine witness without raw-label materialization"
);
let error = range.take(&[1, 3, 10]).unwrap_err();
assert!(matches!(
error,
super::IndexError::OutOfBounds {
position: 10,
length: 10,
}
));
}
#[test]
fn int64_index_sort_values_monotonic_bbx5s() {
// Property (br-frankenpandas-bbx5s): sort_values yields a monotonic-increasing
// index equal to the sorted label multiset. Seeded LCG, no mocks.
let mut st: u64 = 0x4e57_0b1c_2d3e_4f53;
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..800u32 {
let n = (next() % 12) as usize + 1;
let labels: Vec<i64> = (0..n).map(|_| (next() % 8) as i64).collect(); // dups
let idx = Index::new(
labels
.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
);
let sorted = idx.sort_values();
assert!(
sorted.is_monotonic_increasing(),
"monotonic iter={iter} labels={labels:?}"
);
let got: Vec<i64> = sorted
.labels()
.iter()
.map(|l| match l {
IndexLabel::Int64(k) => *k,
_ => i64::MIN,
})
.collect();
let mut exp = labels.clone();
exp.sort_unstable();
assert_eq!(got, exp, "sorted multiset iter={iter}");
}
}
#[test]
fn int64_get_indexer_non_unique_ohq9e() {
use std::collections::HashMap;
// Differential (br-frankenpandas-ohq9e): get_indexer_non_unique on a
// non-unique source. Per target label: all source positions concatenated
// (source order), else -1 + record missing target pos. Seeded LCG, no mocks.
let mut st: u64 = 0x4e57_0b1c_2d3e_4f52;
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..800u32 {
let sn = (next() % 10) as usize + 1;
let source: Vec<i64> = (0..sn).map(|_| (next() % 4) as i64).collect(); // dups
let tn = (next() % 6) as usize + 1;
let target: Vec<i64> = (0..tn).map(|_| (next() % 6) as i64).collect(); // some absent
let src_idx = Index::new(
source
.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
);
let tgt_idx = Index::new(
target
.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
);
let (indexer, missing) = src_idx.get_indexer_non_unique(&tgt_idx);
// Oracle.
let mut positions: HashMap<i64, Vec<usize>> = HashMap::new();
for (p, &l) in source.iter().enumerate() {
positions.entry(l).or_default().push(p);
}
let mut exp_idx: Vec<isize> = Vec::new();
let mut exp_missing: Vec<usize> = Vec::new();
for (tp, &l) in target.iter().enumerate() {
if let Some(ps) = positions.get(&l) {
exp_idx.extend(ps.iter().map(|&p| p as isize));
} else {
exp_idx.push(-1);
exp_missing.push(tp);
}
}
assert_eq!(
indexer, exp_idx,
"indexer iter={iter} src={source:?} tgt={target:?}"
);
assert_eq!(missing, exp_missing, "missing iter={iter}");
}
}
#[test]
fn int64_index_append_concat_qveej() {
// Differential (br-frankenpandas-qveej): append concatenates labels in order
// with no dedup (npbx4 was union/dedup). Seeded LCG, no mocks.
let mut s: u64 = 0xa99e_0d1c_2b3e_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 to_vec = |idx: &Index| -> Vec<i64> {
idx.labels()
.iter()
.map(|l| match l {
IndexLabel::Int64(k) => *k,
_ => i64::MIN,
})
.collect()
};
for iter in 0..1000u32 {
let na = (next() % 6) as usize;
let nb = (next() % 6) as usize;
let a: Vec<i64> = (0..na).map(|_| (next() % 6) as i64).collect();
let b: Vec<i64> = (0..nb).map(|_| (next() % 6) as i64).collect();
let ia = Index::new(a.iter().copied().map(IndexLabel::Int64).collect::<Vec<_>>());
let ib = Index::new(b.iter().copied().map(IndexLabel::Int64).collect::<Vec<_>>());
let app = ia.append(&ib);
let mut exp = a.clone();
exp.extend_from_slice(&b);
assert_eq!(to_vec(&app), exp, "append iter={iter} a={a:?} b={b:?}");
}
}
#[test]
fn int64_index_get_indexer_nonaffine_miaf7() {
use std::collections::HashMap;
// Differential (br-frankenpandas-miaf7): get_indexer on a non-monotonic
// unique Int64 index == position map, -1 for absent. Seeded LCG, no mocks.
let mut state: u64 = 0x9e3a_71b5_c2d4_06f1;
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..1500u32 {
let n = (next() % 10) as usize + 1;
// Shuffled distinct labels 0..n.
let mut labels: Vec<i64> = (0..n as i64).collect();
for i in (1..n).rev() {
let j = (next() as usize) % (i + 1);
labels.swap(i, j);
}
let ix = Index::new(
labels
.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
);
let pos: HashMap<i64, usize> =
labels.iter().enumerate().map(|(p, &v)| (v, p)).collect();
// Targets mix present (0..n) and absent (n..n+3, -1).
let q = (next() % 8) as usize + 1;
let targets: Vec<i64> = (0..q)
.map(|_| (next() % (n as u32 + 4)) as i64 - 1)
.collect();
let target_ix = Index::new(
targets
.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
);
let got = ix.get_indexer(&target_ix);
assert_eq!(got.len(), targets.len(), "len iter={iter}");
for i in 0..targets.len() {
let exp = pos.get(&targets[i]).copied();
assert_eq!(
got[i], exp,
"get_indexer iter={iter} target={} labels={labels:?}",
targets[i]
);
}
}
}
#[test]
fn int64_index_set_ops_match_set_oracle_npbx4() {
use std::collections::BTreeSet;
// Differential vs BTreeSet oracle (br-frankenpandas-npbx4): union /
// intersection / difference / symmetric_difference produce exactly the
// expected label set, with no duplicates. Order-independent (membership).
// Deterministic seeded LCG — no rand crate, no mocks.
let mut state: u64 = 0x5e70_b1c2_d3e4_f506;
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
};
let mk = |vals: &[i64]| {
Index::new(
vals.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
)
};
let to_set = |idx: &Index| -> BTreeSet<i64> {
idx.labels()
.iter()
.map(|l| match l {
IndexLabel::Int64(k) => *k,
_ => i64::MIN,
})
.collect()
};
for iter in 0..1500u32 {
// Distinct unique label subsets of 0..10.
let a: Vec<i64> = (0..10i64).filter(|_| next() % 2 == 0).collect();
let b: Vec<i64> = (0..10i64).filter(|_| next() % 2 == 0).collect();
let ia = mk(&a);
let ib = mk(&b);
let aset: BTreeSet<i64> = a.iter().copied().collect();
let bset: BTreeSet<i64> = b.iter().copied().collect();
let ctx = format!("iter={iter} a={a:?} b={b:?}");
let inter = ia.intersection(&ib);
let exp: BTreeSet<i64> = aset.intersection(&bset).copied().collect();
assert_eq!(to_set(&inter), exp, "intersection {ctx}");
assert_eq!(inter.len(), exp.len(), "intersection dedup {ctx}");
let uni = ia.union(&ib);
let exp: BTreeSet<i64> = aset.union(&bset).copied().collect();
assert_eq!(to_set(&uni), exp, "union {ctx}");
assert_eq!(uni.len(), exp.len(), "union dedup {ctx}");
let diff = ia.difference(&ib);
let exp: BTreeSet<i64> = aset.difference(&bset).copied().collect();
assert_eq!(to_set(&diff), exp, "difference {ctx}");
assert_eq!(diff.len(), exp.len(), "difference dedup {ctx}");
let sym = ia.symmetric_difference(&ib);
let exp: BTreeSet<i64> = aset.symmetric_difference(&bset).copied().collect();
assert_eq!(to_set(&sym), exp, "symdiff {ctx}");
assert_eq!(sym.len(), exp.len(), "symdiff dedup {ctx}");
}
}
#[test]
fn int64_index_fast_paths_match_materialized_fallback_yfyb9() {
// Differential harness (br-frankenpandas-yfyb9): every Int64 fast path on
// Index (min/max, argmin/argmax, is_monotonic_*, nunique, is_unique,
// has_duplicates, hasnans, dtype predicates) must agree between a LAZY
// representation (from_i64_values / affine constructor => fast path) and a
// MATERIALIZED one (Index::new of IndexLabel::Int64 => fallback path) of
// the SAME values. Deterministic seeded LCG — no rand crate, no mocks.
let mut state: u64 = 0xd1b5_4a32_d192_ed03;
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
};
let materialized = |vals: &[i64]| {
Index::new(
vals.iter()
.copied()
.map(IndexLabel::Int64)
.collect::<Vec<_>>(),
)
};
let assert_agree = |lazy: &Index, mat: &Index, ctx: &str| {
assert_eq!(lazy.len(), mat.len(), "len {ctx}");
assert_eq!(lazy.min(), mat.min(), "min {ctx}");
assert_eq!(lazy.max(), mat.max(), "max {ctx}");
assert_eq!(lazy.argmin(), mat.argmin(), "argmin {ctx}");
assert_eq!(lazy.argmax(), mat.argmax(), "argmax {ctx}");
assert_eq!(
lazy.is_monotonic_increasing(),
mat.is_monotonic_increasing(),
"mono_inc {ctx}"
);
assert_eq!(
lazy.is_monotonic_decreasing(),
mat.is_monotonic_decreasing(),
"mono_dec {ctx}"
);
assert_eq!(lazy.nunique(), mat.nunique(), "nunique {ctx}");
assert_eq!(lazy.is_unique(), mat.is_unique(), "is_unique {ctx}");
assert_eq!(
lazy.has_duplicates(),
mat.has_duplicates(),
"has_duplicates {ctx}"
);
assert_eq!(lazy.hasnans(), mat.hasnans(), "hasnans {ctx}");
assert_eq!(
lazy.inferred_type(),
mat.inferred_type(),
"inferred_type {ctx}"
);
assert_eq!(lazy.dtype(), mat.dtype(), "dtype {ctx}");
assert_eq!(lazy.is_integer(), mat.is_integer(), "is_integer {ctx}");
assert_eq!(lazy.is_numeric(), mat.is_numeric(), "is_numeric {ctx}");
};
// Typed Int64 (from_i64_values, fast path) vs materialized fallback.
for iter in 0..2500u32 {
let len = (next() % 13) as usize;
let force_sorted = next() % 3 == 0;
let mut vals: Vec<i64> = (0..len).map(|_| (next() % 9) as i64 - 4).collect();
if force_sorted {
vals.sort_unstable();
}
let lazy = Index::from_i64_values(vals.clone());
let mat = materialized(&vals);
assert_agree(&lazy, &mat, &format!("typed iter={iter} vals={vals:?}"));
}
// Affine Int64 ranges (fast path) vs materialized fallback.
for iter in 0..1500u32 {
let len = (next() % 10) as usize;
let start = (next() % 13) as i64 - 6;
// Non-zero step for len > 1 (affine constructor requires it).
let step = {
let s = (next() % 7) as i64 - 3;
if s == 0 { 1 } else { s }
};
let Some(lazy) = Index::new_known_unique_int64_affine_range(start, step, len) else {
continue;
};
let vals: Vec<i64> = (0..len as i64).map(|i| start + step * i).collect();
let mat = materialized(&vals);
assert_agree(
&lazy,
&mat,
&format!("affine iter={iter} start={start} step={step} len={len}"),
);
}
}
#[test]
fn index_a31qh_factorize_reindex_and_non_unique_indexer() {
let idx = Index::new(vec![
IndexLabel::Utf8("a".into()),
IndexLabel::Utf8("b".into()),
IndexLabel::Utf8("a".into()),
IndexLabel::Datetime64(i64::MIN),
])
.set_name("letters");
let (codes, uniques) = idx.factorize();
assert_eq!(codes, vec![0, 1, 0, -1]);
assert_eq!(
uniques.labels(),
&[IndexLabel::from("a"), IndexLabel::from("b")]
);
assert_eq!(uniques.name().map(|n| n.as_str()), Some("letters"));
let target = Index::new(vec![
IndexLabel::Utf8("a".into()),
IndexLabel::Utf8("z".into()),
IndexLabel::Utf8("b".into()),
]);
// ⚠️ RE-PINNED (br-frankenpandas-lerb2): this asserted [Some(0), None,
// Some(1)] — one entry per target, first match only — which is
// `get_indexer`'s answer, not `get_indexer_for`'s. `idx` HAS duplicates, and
// the very next assertion shows both positions of "a" at 0 and 2.
// pandas' rule is get_indexer when unique, else get_indexer_non_unique()[0],
// so the result may be LONGER than the target. MEASURED, live pandas 2.2.3,
// index [10,20,20,30] with target [20,99,10]: get_indexer_for -> [1,2,-1,0],
// four entries for a three-entry target.
assert_eq!(
idx.get_indexer_for(&target),
vec![Some(0), Some(2), None, Some(1)]
);
assert_eq!(
idx.get_indexer_non_unique(&target),
(vec![0, 2, -1, 1], vec![1])
);
let (reindexed, positions) = idx.reindex(&target);
assert_eq!(reindexed, target);
assert_eq!(positions, vec![Some(0), None, Some(1)]);
}
#[test]
fn int64_get_indexer_non_unique_avoids_label_materialization_codb() {
let source = Index::from_i64_values(vec![4, 2, 4, 7, 2]).set_name("source");
let target = Index::from_i64_values(vec![2, 5, 4, 2]);
assert!(source.labels.materialized.get().is_none());
assert!(target.labels.materialized.get().is_none());
let actual = source.get_indexer_non_unique(&target);
assert_eq!(actual, (vec![1, 4, -1, 0, 2, 1, 4], vec![1]));
assert!(
source.labels.materialized.get().is_none(),
"raw Int64 source positions should not materialize labels"
);
assert!(
target.labels.materialized.get().is_none(),
"raw Int64 targets should not materialize labels"
);
let materialized_source = Index::new(vec![
IndexLabel::Int64(4),
IndexLabel::Int64(2),
IndexLabel::Int64(4),
IndexLabel::Int64(7),
IndexLabel::Int64(2),
]);
let materialized_target = Index::new(vec![
IndexLabel::Int64(2),
IndexLabel::Int64(5),
IndexLabel::Int64(4),
IndexLabel::Int64(2),
]);
assert_eq!(
actual,
materialized_source.get_indexer_non_unique(&materialized_target)
);
}
#[test]
fn sorted_int64_get_indexer_non_unique_dense_runs_codb() {
let source = Index::from_i64_values(vec![1, 1, 2, 2, 2, 4, 4, 6]).set_name("source");
let target = Index::from_i64_values(vec![2, 3, 1, 6, 4, 0]);
assert!(source.labels.materialized.get().is_none());
assert!(target.labels.materialized.get().is_none());
let actual = source.get_indexer_non_unique(&target);
assert_eq!(actual, (vec![2, 3, 4, -1, 0, 1, 7, 5, 6, -1], vec![1, 5]));
assert!(
source.labels.materialized.get().is_none(),
"sorted dense Int64 source should stay on raw backing"
);
assert!(
target.labels.materialized.get().is_none(),
"sorted dense Int64 targets should stay on raw backing"
);
let materialized_source = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(2),
IndexLabel::Int64(2),
IndexLabel::Int64(4),
IndexLabel::Int64(4),
IndexLabel::Int64(6),
]);
let materialized_target = Index::new(vec![
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(1),
IndexLabel::Int64(6),
IndexLabel::Int64(4),
IndexLabel::Int64(0),
]);
assert_eq!(
actual,
materialized_source.get_indexer_non_unique(&materialized_target)
);
}
#[test]
fn index_a31qh_set_sort_slice_and_level_aliases() {
let idx = Index::from_i64(vec![3, 1, 2]).set_name("n");
let sorted = idx.sort();
assert_eq!(
sorted.labels(),
&[
IndexLabel::Int64(1),
IndexLabel::Int64(2),
IndexLabel::Int64(3),
]
);
let (sortlevel, order) = idx.sortlevel();
assert_eq!(sortlevel, sorted);
assert_eq!(order, vec![1, 2, 0]);
let other = Index::from_i64(vec![2, 4]);
assert_eq!(idx.union(&other), idx.union_with(&other));
assert_eq!(
idx.drop(&[IndexLabel::Int64(1)]),
idx.drop_labels(&[IndexLabel::Int64(1)])
);
assert_eq!(idx.copy(), idx);
assert_eq!(
idx.where_(&[true, false, true], &IndexLabel::Int64(0))
.labels()[1],
IndexLabel::Int64(0)
);
assert_eq!(idx.get_level_values(0).unwrap(), idx);
assert!(idx.get_level_values(1).is_err());
assert!(idx.droplevel(0).is_err());
let sorted_lookup = Index::from_i64(vec![1, 2, 2, 4]);
assert_eq!(
sorted_lookup
.get_slice_bound(&IndexLabel::Int64(2), "left")
.unwrap(),
1
);
assert_eq!(
sorted_lookup
.slice_locs(Some(&IndexLabel::Int64(2)), Some(&IndexLabel::Int64(4)))
.unwrap(),
(1, 4)
);
assert_eq!(
sorted_lookup
.slice_indexer(Some(&IndexLabel::Int64(2)), Some(&IndexLabel::Int64(2)))
.unwrap(),
(1, 3)
);
}
#[test]
fn index_a31qh_astype_str_groupby_join_asof_and_diff() {
let idx = Index::new(vec![
IndexLabel::Utf8("Alpha".into()),
IndexLabel::Utf8("beta".into()),
IndexLabel::Int64(7),
]);
assert_eq!(
idx.r#str().lower(),
vec![Some("alpha".to_owned()), Some("beta".to_owned()), None]
);
assert_eq!(
idx.r#str().upper(),
vec![Some("ALPHA".to_owned()), Some("BETA".to_owned()), None]
);
assert_eq!(
idx.r#str().contains("ta"),
vec![Some(false), Some(true), None]
);
assert_eq!(idx.r#str().len(), vec![Some(5), Some(4), None]);
assert_eq!(idx.r#str().is_empty(), vec![Some(false), Some(false), None]);
assert!(idx.astype("object").is_ok());
assert!(idx.astype("float64").is_err());
let grouped = Index::new(vec!["a".into(), "b".into(), "a".into()]).groupby();
assert_eq!(grouped[&IndexLabel::from("a")], vec![0, 2]);
assert_eq!(grouped[&IndexLabel::from("b")], vec![1]);
let left = Index::from_i64(vec![1, 2, 3]);
let right = Index::from_i64(vec![2, 4]);
assert_eq!(
left.join(&right, "inner").unwrap(),
left.intersection(&right)
);
assert_eq!(left.join(&right, "outer").unwrap(), left.union_with(&right));
assert_eq!(left.join(&right, "left").unwrap(), left);
assert_eq!(left.join(&right, "right").unwrap(), right);
assert!(left.join(&right, "sideways").is_err());
let sorted = Index::from_i64(vec![1, 3, 5, 7]);
let probes = Index::from_i64(vec![0, 3, 4, 8]);
assert_eq!(
sorted.asof_locs(&probes, None),
vec![None, Some(1), Some(1), Some(3)]
);
assert_eq!(
sorted.asof_locs(&probes, Some(&[true, false, true, true])),
vec![None, Some(0), Some(0), Some(3)]
);
assert_eq!(
sorted.diff(1),
vec![
None,
Some(IndexLabel::Int64(2)),
Some(IndexLabel::Int64(2)),
Some(IndexLabel::Int64(2)),
]
);
let datetimes = Index::from_datetime64(vec![10, 25]);
assert_eq!(
datetimes.diff(1),
vec![None, Some(IndexLabel::Timedelta64(15))]
);
}
#[test]
fn int64_diff_avoids_label_materialization_codb() {
let index = Index::from_i64_values(vec![10, 13, 20, i64::MIN]).set_name("n");
assert!(index.labels.materialized.get().is_none());
let actual = index.diff(2);
assert_eq!(actual, vec![None, None, Some(IndexLabel::Int64(10)), None,]);
assert_eq!(index.diff(99), vec![None, None, None, None]);
assert_eq!(
index.diff(0),
vec![
Some(IndexLabel::Int64(0)),
Some(IndexLabel::Int64(0)),
Some(IndexLabel::Int64(0)),
Some(IndexLabel::Int64(0)),
]
);
assert!(
index.labels.materialized.get().is_none(),
"raw Int64 diff should not materialize source labels"
);
let materialized = Index::new(vec![
IndexLabel::Int64(10),
IndexLabel::Int64(13),
IndexLabel::Int64(20),
IndexLabel::Int64(i64::MIN),
])
.set_name("n");
assert_eq!(actual, materialized.diff(2));
}
#[test]
fn int64_groupby_avoids_label_materialization_xk18v() {
let idx = Index::from_i64_values(vec![2, 1, 2, 3, 1]);
assert!(idx.labels.materialized.get().is_none());
let grouped = idx.groupby();
assert_eq!(grouped[&IndexLabel::Int64(1)], vec![1, 4]);
assert_eq!(grouped[&IndexLabel::Int64(2)], vec![0, 2]);
assert_eq!(grouped[&IndexLabel::Int64(3)], vec![3]);
assert!(
idx.labels.materialized.get().is_none(),
"groupby should not materialize source Int64 labels"
);
}
// ── Index name tests ────────────────────────────────────────────
#[test]
fn index_name_default_none() {
let idx = Index::new(vec![1_i64.into(), 2_i64.into()]);
assert_eq!(idx.name(), None);
}
#[test]
fn index_set_name() {
let idx = Index::new(vec![1_i64.into(), 2_i64.into()]);
let named = idx.set_name("year");
assert_eq!(named.name().map(|n| n.as_str()), Some("year"));
assert_eq!(named.labels(), idx.labels());
}
#[test]
fn index_names_keep_their_type_fvsao64() {
use super::LabelName;
let zero = LabelName::typed(IndexLabel::Int64(0));
let named = Index::new(vec![1_i64.into()]).set_name(zero.clone());
assert_eq!(
named.name().map(LabelName::label),
Some(IndexLabel::Int64(0))
);
// A name handed on keeps its label (relabel, rename by name, union
// of two indexes named alike).
assert_eq!(named.relabeled(vec![2_i64.into()]).name(), Some(&zero));
assert_eq!(
Index::new(vec![3_i64.into()])
.rename_index(named.name())
.name(),
Some(&zero)
);
assert_eq!(named.union(&named.clone()).name(), Some(&zero));
// NEGATIVE: the integer 0 and the string '0' are different names - a
// union of indexes named each is unnamed, as pandas' - and text
// names a string.
let text = Index::new(vec![4_i64.into()]).set_name("0");
assert_eq!(
text.name().map(LabelName::label),
Some(IndexLabel::Utf8("0".to_owned()))
);
assert_eq!(named.union(&text).name(), None);
assert_eq!(named.names(), vec![Some("0".to_owned())]);
}
#[test]
fn multiindex_level_names_keep_their_type_fvsao64() {
use super::LabelName;
let zero = LabelName::typed(IndexLabel::Int64(0));
let multi = super::MultiIndex::from_arrays(vec![
vec![1_i64.into(), 2_i64.into()],
vec!["x".into(), "y".into()],
])
.unwrap()
.set_names(vec![Some(zero.clone()), Some("b".into())]);
let label = |name: &Option<LabelName>| name.as_ref().map(LabelName::label);
assert_eq!(label(&multi.names()[0]), Some(IndexLabel::Int64(0)));
// A level taken out keeps its typed name; a renamed level takes the
// new one.
assert_eq!(multi.get_level_values(0).unwrap().name(), Some(&zero));
let seven = Some(LabelName::typed(IndexLabel::Int64(7)));
let renamed = multi.rename_level(seven, 1).unwrap();
assert_eq!(label(&renamed.names()[1]), Some(IndexLabel::Int64(7)));
// NEGATIVE: a string level name is the string ('0' is not 0).
let text = multi.clone().set_names(vec![Some("0".into()), None]);
assert_eq!(
label(&text.names()[0]),
Some(IndexLabel::Utf8("0".to_owned()))
);
assert_ne!(text.names()[0], multi.names()[0]);
}
#[test]
fn index_set_names_some_and_none() {
let idx = Index::new(vec!["a".into(), "b".into()]);
let named = idx.set_names(Some("letters"));
assert_eq!(named.name().map(|n| n.as_str()), Some("letters"));
let cleared = named.set_names(None::<&str>);
assert_eq!(cleared.name(), None);
}
#[test]
fn index_name_propagates_through_unique() {
let idx = Index::new(vec![1_i64.into(), 1_i64.into(), 2_i64.into()]).set_name("id");
let u = idx.unique();
assert_eq!(u.name().map(|n| n.as_str()), Some("id"));
assert_eq!(u.len(), 2);
}
#[test]
fn index_name_propagates_through_sort_values() {
let idx = Index::new(vec![3_i64.into(), 1_i64.into(), 2_i64.into()]).set_name("val");
let sorted = idx.sort_values();
assert_eq!(sorted.name().map(|n| n.as_str()), Some("val"));
}
#[test]
fn index_name_propagates_through_take_and_slice() {
let idx = Index::new(vec!["a".into(), "b".into(), "c".into()]).set_name("letter");
assert_eq!(idx.take(&[0, 2]).name().map(|n| n.as_str()), Some("letter"));
assert_eq!(idx.slice(1, 2).name().map(|n| n.as_str()), Some("letter"));
}
#[test]
fn index_name_propagates_through_map() {
let idx = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("x");
let mapped = idx.map(|l| match l {
IndexLabel::Int64(v) => IndexLabel::Int64(v * 10),
other => other.clone(),
});
assert_eq!(mapped.name().map(|n| n.as_str()), Some("x"));
}
#[test]
fn index_name_propagates_through_drop_labels() {
let idx = Index::new(vec![1_i64.into(), 2_i64.into(), 3_i64.into()]).set_name("num");
let dropped = idx.drop_labels(&[2_i64.into()]);
assert_eq!(dropped.name().map(|n| n.as_str()), Some("num"));
assert_eq!(dropped.len(), 2);
}
#[test]
fn index_name_propagates_through_astype() {
let idx = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("n");
assert_eq!(idx.astype_str().name().map(|n| n.as_str()), Some("n"));
let idx2 = Index::new(vec!["1".into(), "2".into()]).set_name("s");
assert_eq!(idx2.astype_int().name().map(|n| n.as_str()), Some("s"));
}
#[test]
fn index_name_shared_for_intersection() {
let a = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("x");
let b = Index::new(vec![2_i64.into(), 3_i64.into()]).set_name("x");
assert_eq!(a.intersection(&b).name().map(|n| n.as_str()), Some("x"));
let c = Index::new(vec![2_i64.into(), 3_i64.into()]).set_name("y");
assert_eq!(a.intersection(&c).name(), None);
}
#[test]
fn index_name_shared_for_union() {
let a = Index::new(vec![1_i64.into()]).set_name("k");
let b = Index::new(vec![2_i64.into()]).set_name("k");
assert_eq!(a.union_with(&b).name().map(|n| n.as_str()), Some("k"));
let c = Index::new(vec![2_i64.into()]);
assert_eq!(a.union_with(&c).name(), None);
}
#[test]
fn index_name_propagates_through_where_cond() {
let idx = Index::new(vec!["a".into(), "b".into()]).set_name("col");
let result = idx.where_cond(&[true, false], &"Z".into());
assert_eq!(result.name().map(|n| n.as_str()), Some("col"));
}
#[test]
fn int64_where_cond_avoids_label_materialization_codb() {
let index = Index::from_i64_values(vec![4, 5, 6, 7]).set_name("row");
assert!(index.labels.materialized.get().is_none());
let replaced = index.where_cond(&[true, false, true], &IndexLabel::Int64(-1));
assert_eq!(replaced.name().map(|n| n.as_str()), Some("row"));
assert_eq!(
replaced.labels.int64_view().unwrap().as_slice(),
&[4, -1, 6, -1]
);
assert!(index.labels.materialized.get().is_none());
assert!(
replaced.labels.materialized.get().is_none(),
"typed Int64 where should keep typed output backing"
);
let materialized = Index::new(vec![
IndexLabel::Int64(4),
IndexLabel::Int64(5),
IndexLabel::Int64(6),
IndexLabel::Int64(7),
]);
assert_eq!(
replaced.labels(),
materialized
.where_cond(&[true, false, true], &IndexLabel::Int64(-1))
.labels()
);
}
#[test]
fn affine_int64_where_cond_avoids_label_materialization_codb() {
let index = Index::new_known_unique_int64_affine_range(2, 3, 4)
.unwrap()
.set_name("axis");
assert!(index.labels.materialized.get().is_none());
let replaced = index.where_cond(&[false, true, true, false], &IndexLabel::Int64(0));
assert_eq!(replaced.name().map(|n| n.as_str()), Some("axis"));
assert_eq!(
replaced.labels.int64_view().unwrap().as_slice(),
&[0, 5, 8, 0]
);
assert!(index.labels.materialized.get().is_none());
assert!(
replaced.labels.materialized.get().is_none(),
"affine Int64 where should gather raw values into typed output"
);
}
#[test]
fn index_rename_index() {
let idx = Index::new(vec![1_i64.into()]);
let named = idx.rename_index(Some("foo"));
assert_eq!(named.name().map(|n| n.as_str()), Some("foo"));
let cleared = named.rename_index(None::<&str>);
assert_eq!(cleared.name(), None);
}
#[test]
fn index_equality_ignores_name() {
let a = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("a");
let b = Index::new(vec![1_i64.into(), 2_i64.into()]).set_name("b");
assert_eq!(a, b);
}
#[test]
fn index_names_property() {
let idx = Index::new(vec![1_i64.into()]);
assert_eq!(idx.names(), vec![None]);
let named = idx.set_name("x");
assert_eq!(named.names(), vec![Some("x".to_string())]);
}
#[test]
fn index_set_names_list() {
let idx = Index::new(vec![1_i64.into()]);
let named = idx.set_names_list(&[Some("foo")]);
assert_eq!(named.name().map(|n| n.as_str()), Some("foo"));
let cleared = named.set_names_list(&[None]);
assert_eq!(cleared.name(), None);
}
#[test]
fn index_to_flat_index() {
let idx = Index::new(vec!["a".into(), "b".into()]).set_name("x");
let flat = idx.to_flat_index();
assert_eq!(flat, idx);
assert_eq!(flat.name().map(|n| n.as_str()), Some("x"));
}
// ── MultiIndex tests ──
#[test]
fn multi_index_from_tuples() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["b".into(), 1_i64.into()],
])
.unwrap();
assert_eq!(mi.nlevels(), 2);
assert_eq!(mi.len(), 3);
assert!(!mi.is_empty());
}
#[test]
fn multi_index_from_tuples_ragged_errors() {
let err = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into()], // wrong number of levels
]);
assert!(err.is_err());
}
#[test]
fn multi_index_from_arrays() {
let mi = MultiIndex::from_arrays(vec![
vec!["a".into(), "a".into(), "b".into()],
vec![1_i64.into(), 2_i64.into(), 1_i64.into()],
])
.unwrap();
assert_eq!(mi.nlevels(), 2);
assert_eq!(mi.len(), 3);
}
#[test]
fn multi_index_from_arrays_length_mismatch_errors() {
let err = MultiIndex::from_arrays(vec![
vec!["a".into(), "b".into()],
vec![1_i64.into()], // wrong length
]);
assert!(err.is_err());
}
#[test]
fn multi_index_from_frame_preserves_column_names_a1dv9() {
let mi = MultiIndex::from_frame(vec![
(
Some("letter".into()),
vec!["a".into(), "b".into(), "b".into()],
),
(
Some("number".into()),
vec![1_i64.into(), 1_i64.into(), 2_i64.into()],
),
])
.unwrap();
assert_eq!(mi.names(), &[Some("letter".into()), Some("number".into())]);
assert_eq!(
mi.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
]
);
let empty = MultiIndex::from_frame(Vec::new()).unwrap();
assert!(empty.is_empty());
assert_eq!(empty.nlevels(), 0);
}
#[test]
fn multi_index_from_frame_rejects_length_mismatch_a1dv9() {
let err = MultiIndex::from_frame(vec![
(Some("letter".into()), vec!["a".into(), "b".into()]),
(Some("number".into()), vec![1_i64.into()]),
])
.unwrap_err();
assert!(matches!(
err,
super::IndexError::LengthMismatch {
expected: 2,
actual: 1,
..
}
));
}
#[test]
fn multi_index_from_product() {
let mi = MultiIndex::from_product(vec![
vec!["a".into(), "b".into()],
vec![1_i64.into(), 2_i64.into(), 3_i64.into()],
])
.unwrap();
assert_eq!(mi.nlevels(), 2);
assert_eq!(mi.len(), 6); // 2 * 3
}
#[test]
fn multi_index_product_cardinality_rejects_overflow_uza04184() {
assert_eq!(super::checked_cartesian_product_len([2, 3, 4]).unwrap(), 24);
assert_eq!(
super::checked_cartesian_product_len([usize::MAX, 0]).unwrap(),
0
);
let err = super::checked_cartesian_product_len([usize::MAX, 2]).unwrap_err();
assert!(matches!(
err,
super::IndexError::InvalidArgument(message)
if message == "MultiIndex product cardinality overflow"
));
}
#[test]
fn multi_index_from_product_values() {
let mi = MultiIndex::from_product(vec![
vec!["x".into(), "y".into()],
vec![1_i64.into(), 2_i64.into()],
])
.unwrap();
// Should produce: (x,1), (x,2), (y,1), (y,2)
assert_eq!(
mi.get_tuple(0).unwrap(),
vec![&IndexLabel::Utf8("x".into()), &IndexLabel::Int64(1)]
);
assert_eq!(
mi.get_tuple(1).unwrap(),
vec![&IndexLabel::Utf8("x".into()), &IndexLabel::Int64(2)]
);
assert_eq!(
mi.get_tuple(2).unwrap(),
vec![&IndexLabel::Utf8("y".into()), &IndexLabel::Int64(1)]
);
assert_eq!(
mi.get_tuple(3).unwrap(),
vec![&IndexLabel::Utf8("y".into()), &IndexLabel::Int64(2)]
);
}
#[test]
fn multi_index_get_level_values() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let level0 = mi.get_level_values(0).unwrap();
assert_eq!(
level0.labels(),
&[IndexLabel::Utf8("a".into()), IndexLabel::Utf8("b".into())]
);
assert_eq!(level0.name().map(|n| n.as_str()), Some("letter"));
let level1 = mi.get_level_values(1).unwrap();
assert_eq!(
level1.labels(),
&[IndexLabel::Int64(1), IndexLabel::Int64(2)]
);
assert_eq!(level1.name().map(|n| n.as_str()), Some("number"));
}
#[test]
fn multi_index_get_level_values_out_of_bounds() {
let mi = MultiIndex::from_tuples(vec![vec!["a".into()]]).unwrap();
assert!(mi.get_level_values(1).is_err());
}
#[test]
fn multi_index_metadata_shape_and_tuple_materialization() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["b".into(), 1_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let tuples = vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
];
assert_eq!(mi.name(), None);
assert_eq!(mi.names(), &[Some("letter".into()), Some("number".into())]);
assert_eq!(mi.size(), 3);
assert_eq!(mi.shape(), (3,));
assert_eq!(mi.ndim(), 1);
assert!(!mi.empty());
assert_eq!(mi.to_list(), tuples);
assert_eq!(mi.tolist(), mi.to_list());
assert_eq!(mi.to_numpy(), mi.to_list());
assert_eq!(mi.values(), mi.to_list());
assert_eq!(mi.array(), mi.to_list());
assert_eq!(mi.ravel(), mi.to_list());
assert_eq!(mi.format(), vec!["(a, 1)", "(a, 2)", "(b, 1)"]);
assert_eq!(mi.view(), mi);
assert_eq!(mi.transpose(), mi);
assert_eq!(mi.T(), mi);
assert_eq!(mi.to_frame(), tuples);
assert_eq!(
mi.to_series(),
tuples
.iter()
.cloned()
.map(|tuple| (tuple.clone(), tuple))
.collect::<Vec<_>>()
);
}
#[test]
fn multi_index_levels_codes_and_levshape_exclude_missing_labels() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec![IndexLabel::Datetime64(i64::MIN), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let levels = mi.levels();
assert_eq!(levels[0].labels(), &[IndexLabel::Utf8("a".into())]);
assert_eq!(levels[0].name().map(|n| n.as_str()), Some("letter"));
assert_eq!(
levels[1].labels(),
&[IndexLabel::Int64(1), IndexLabel::Int64(2)]
);
assert_eq!(levels[1].name().map(|n| n.as_str()), Some("number"));
assert_eq!(mi.codes(), vec![vec![0, -1, 0], vec![0, 1, 0]]);
assert_eq!(mi.levshape(), vec![1, 2]);
assert!(mi.memory_usage(false) <= mi.memory_usage(true));
assert_eq!(mi.nbytes(), mi.memory_usage(false));
}
/// levels / codes are pandas' sorted catalog - numbers by value before
/// strings - whatever order the labels first appear in, and set_codes /
/// set_levels read them the same way (98f6w: first-seen order).
#[test]
fn multi_index_levels_are_sorted_as_pandas_factorizes_98f6w() {
let mi = MultiIndex::from_tuples(vec![
vec!["s".into(), "b".into()],
vec!["n".into(), 2_i64.into()],
vec!["s".into(), 1_i64.into()],
vec![IndexLabel::Null(fp_types::NullKind::NaN), 1_i64.into()],
])
.unwrap();
let levels = mi.levels();
assert_eq!(
levels[0].labels(),
&["n".into(), "s".into()] as &[IndexLabel]
);
assert_eq!(
levels[1].labels(),
&[1_i64.into(), 2_i64.into(), "b".into()] as &[IndexLabel]
);
assert_eq!(mi.codes(), vec![vec![1, 0, 1, -1], vec![2, 1, 0, 0]]);
// The codes read against the levels give back every tuple.
let again = mi.set_codes(mi.codes()).unwrap();
for row in 0..mi.len() {
assert_eq!(again.get_tuple(row), mi.get_tuple(row));
}
// set_levels replaces the sorted catalog: 'n' -> 'N', 's' -> 'S'.
let relabelled = mi
.set_levels(vec![
vec!["N".into(), "S".into()],
vec![1_i64.into(), 2_i64.into(), "b".into()],
])
.unwrap();
assert_eq!(relabelled.get_tuple(0).unwrap()[0], &IndexLabel::from("S"));
assert_eq!(relabelled.get_tuple(1).unwrap()[0], &IndexLabel::from("N"));
// NEGATIVE: an already sorted level keeps its order and codes.
let sorted = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap();
assert_eq!(sorted.codes(), vec![vec![0, 1], vec![0, 1]]);
}
#[test]
fn multi_index_memory_usage_saturates_code_bytes_uza04178() {
assert_eq!(
super::multi_index_codes_memory_usage(2, 3),
6 * std::mem::size_of::<isize>()
);
assert_eq!(
super::multi_index_codes_memory_usage(usize::MAX, 2),
usize::MAX
);
assert_eq!(
super::multi_index_codes_memory_usage(2, usize::MAX),
usize::MAX
);
}
#[test]
fn multi_index_dtype_type_checks_and_item_match_object_index_shape() {
let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
assert_eq!(mi.dtype(), "object");
assert_eq!(mi.dtypes(), vec!["object", "int64"]);
assert_eq!(mi.inferred_type(), "mixed");
assert_eq!(mi.infer_objects(), mi);
assert!(!mi.holds_integer());
assert!(!mi.is_boolean());
assert!(!mi.is_categorical());
assert!(!mi.is_floating());
assert!(!mi.is_integer());
assert!(!mi.is_interval());
assert!(!mi.is_numeric());
assert!(mi.is_object());
assert!(mi.is_(&mi));
assert_eq!(
mi.item().unwrap(),
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)]
);
let multi = mi.repeat(2);
assert!(multi.item().is_err());
}
#[test]
fn multi_index_missing_masks_fillna_putmask_where_and_map() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec![IndexLabel::Datetime64(i64::MIN), 2_i64.into()],
vec!["b".into(), IndexLabel::Timedelta64(Timedelta::NAT)],
vec!["c".into(), 3_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let missing_mask_errors = [
mi.hasnans().unwrap_err(),
mi.isna().unwrap_err(),
mi.isnull().unwrap_err(),
mi.notna().unwrap_err(),
mi.notnull().unwrap_err(),
];
for err in missing_mask_errors {
assert!(matches!(
err,
super::IndexError::InvalidArgument(message)
if message == "isna is not defined for MultiIndex"
));
}
assert_eq!(mi.copy(), mi);
assert_eq!(mi.remove_unused_levels(), mi);
let scalar_filled = mi.fillna(&IndexLabel::Utf8("missing".into()));
assert_eq!(
scalar_filled.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("missing".into()), IndexLabel::Int64(2)],
vec![
IndexLabel::Utf8("b".into()),
IndexLabel::Utf8("missing".into())
],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
]
);
let tuple_filled = mi
.fillna_tuple(&[IndexLabel::Utf8("z".into()), IndexLabel::Int64(0)])
.unwrap();
assert_eq!(
tuple_filled.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(0)],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
]
);
assert!(
mi.fillna_tuple(&[IndexLabel::Utf8("short".into())])
.is_err()
);
let masked = mi
.putmask(
&[false, true, false, true],
vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(9)],
)
.unwrap();
assert_eq!(
masked.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(9)],
vec![
IndexLabel::Utf8("b".into()),
IndexLabel::Timedelta64(Timedelta::NAT)
],
vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(9)],
]
);
assert!(
mi.putmask(&[true], vec![IndexLabel::Utf8("x".into())])
.is_err()
);
let where_result = mi
.r#where(
&[true, false, true, false],
vec![IndexLabel::Utf8("fallback".into()), IndexLabel::Int64(5)],
)
.unwrap();
assert_eq!(
where_result.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("fallback".into()), IndexLabel::Int64(5)],
vec![
IndexLabel::Utf8("b".into()),
IndexLabel::Timedelta64(Timedelta::NAT)
],
vec![IndexLabel::Utf8("fallback".into()), IndexLabel::Int64(5)],
]
);
let rendered = mi.map(|tuple| {
tuple
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("|")
});
assert_eq!(rendered[0], "a|1");
assert_eq!(rendered[3], "c|3");
}
#[test]
fn multi_index_set_levels_and_set_codes_rebuild_from_pandas_catalogs() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let relabeled = mi
.set_levels(vec![
vec![IndexLabel::Utf8("x".into()), IndexLabel::Utf8("y".into())],
vec![IndexLabel::Int64(10), IndexLabel::Int64(20)],
])
.unwrap();
assert_eq!(
relabeled.to_list(),
vec![
vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(10)],
vec![IndexLabel::Utf8("y".into()), IndexLabel::Int64(20)],
vec![IndexLabel::Utf8("x".into()), IndexLabel::Int64(10)],
]
);
assert_eq!(relabeled.names(), mi.names());
assert!(
mi.set_levels(vec![vec![IndexLabel::Utf8("only".into())]])
.is_err()
);
assert!(
mi.set_levels(vec![
vec![IndexLabel::Utf8("x".into())],
vec![IndexLabel::Int64(10), IndexLabel::Int64(20)],
])
.is_err()
);
let recoded = mi.set_codes(vec![vec![1, 0, 1], vec![1, -1, 0]]).unwrap();
assert_eq!(
recoded.to_list(),
vec![
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
vec![
IndexLabel::Utf8("a".into()),
IndexLabel::Datetime64(i64::MIN)
],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
]
);
assert_eq!(recoded.names(), mi.names());
assert!(mi.set_codes(vec![vec![0, 1, 0]]).is_err());
assert!(mi.set_codes(vec![vec![0, 1], vec![0, 1, 0]]).is_err());
assert!(mi.set_codes(vec![vec![0, 1, 0], vec![0, 99, 0]]).is_err());
}
#[test]
fn multi_index_equals_identical_and_equal_levels_match_pandas_names() {
let left = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let renamed = left
.clone()
.set_names(vec![Some("letter".into()), Some("other".into())]);
let reordered = MultiIndex::from_tuples(vec![
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
assert!(left.equals(&renamed));
assert!(!left.identical(&renamed));
assert!(left.equal_levels(&renamed));
assert!(!left.equals(&reordered));
// TEST-CHANGE (98f6w): this asserted the reordered rows' levels
// differ; pandas 2.2.3 sorts each level, so they are equal
// (pd.MultiIndex.from_tuples([('a', 1), ('b', 2)]).equal_levels(
// pd.MultiIndex.from_tuples([('b', 2), ('a', 1)])) is True).
assert!(left.equal_levels(&reordered));
// NEGATIVE: a level holding another value differs.
let other_value = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["c".into(), 2_i64.into()],
])
.unwrap();
assert!(!left.equal_levels(&other_value));
}
#[test]
fn multi_index_to_flat_index() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap();
let flat = mi.to_flat_index("_");
assert_eq!(flat.labels()[0], IndexLabel::Utf8("a_1".into()));
assert_eq!(flat.labels()[1], IndexLabel::Utf8("b_2".into()));
}
#[test]
fn multi_index_droplevel() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into(), "x".into()],
vec!["b".into(), 2_i64.into(), "y".into()],
])
.unwrap()
.set_names(vec![
Some("l0".into()),
Some("l1".into()),
Some("l2".into()),
]);
// Drop middle level -> 2 levels remain -> MultiIndex
let result = mi.droplevel(1).unwrap();
assert!(
matches!(&result, super::MultiIndexOrIndex::Multi(_)),
"expected MultiIndex after dropping from 3 levels"
);
if let super::MultiIndexOrIndex::Multi(mi2) = result {
assert_eq!(mi2.nlevels(), 2);
assert_eq!(mi2.names(), &[Some("l0".into()), Some("l2".into())]);
}
}
#[test]
fn multi_index_droplevel_to_index() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
// Drop one level from 2 -> 1 level -> plain Index
let result = mi.droplevel(0).unwrap();
assert!(
matches!(&result, super::MultiIndexOrIndex::Index(_)),
"expected Index after dropping from 2 levels"
);
if let super::MultiIndexOrIndex::Index(idx) = result {
assert_eq!(idx.labels(), &[IndexLabel::Int64(1), IndexLabel::Int64(2)]);
assert_eq!(idx.name().map(|n| n.as_str()), Some("number"));
}
}
#[test]
fn multi_index_swaplevel() {
let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])
.unwrap()
.set_names(vec![Some("first".into()), Some("second".into())]);
let swapped = mi.swaplevel(0, 1).unwrap();
assert_eq!(
swapped.names(),
&[Some("second".into()), Some("first".into())]
);
assert_eq!(
swapped.get_tuple(0).unwrap(),
vec![&IndexLabel::Int64(1), &IndexLabel::Utf8("a".into())]
);
}
#[test]
fn multi_index_empty() {
let mi = MultiIndex::from_tuples(vec![]).unwrap();
assert_eq!(mi.nlevels(), 0);
assert_eq!(mi.len(), 0);
assert!(mi.is_empty());
}
#[test]
fn multi_index_get_tuple_out_of_bounds() {
let mi = MultiIndex::from_tuples(vec![vec!["a".into()]]).unwrap();
assert!(mi.get_tuple(1).is_none());
}
#[test]
fn multi_index_get_loc_tuple_exact_and_duplicates() {
let mi = MultiIndex::from_arrays(vec![
vec!["east".into(), "east".into(), "west".into(), "east".into()],
vec!["A".into(), "B".into(), "A".into(), "A".into()],
])
.unwrap();
let positions = mi
.get_loc_tuple(&[
IndexLabel::Utf8("east".into()),
IndexLabel::Utf8("A".into()),
])
.unwrap();
assert_eq!(positions, vec![0, 3]);
}
#[test]
fn multi_index_get_loc_level_prefix_returns_remaining_index() {
let mi = MultiIndex::from_arrays(vec![
vec!["east".into(), "east".into(), "west".into()],
vec!["A".into(), "B".into(), "A".into()],
])
.unwrap()
.set_names(vec![Some("region".into()), Some("product".into())]);
let (positions, remaining) = mi
.get_loc_level(&[IndexLabel::Utf8("east".into())])
.unwrap();
assert_eq!(positions, vec![0, 1]);
assert!(matches!(
&remaining,
Some(super::MultiIndexOrIndex::Index(index))
if index.labels()
== [IndexLabel::Utf8("A".into()), IndexLabel::Utf8("B".into())]
&& index.name().is_some_and(|name| name == "product")
));
}
#[test]
fn multi_index_groupby_join_groups_duplicate_tuples_d89fe3() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
])
.unwrap();
let groups = mi.groupby();
assert_eq!(
groups[&vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)]],
vec![0, 2]
);
assert_eq!(
groups[&vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)]],
vec![1]
);
}
#[test]
fn multi_index_groupby_join_modes_d89fe3() {
let left = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["c".into(), 3_i64.into()],
])
.unwrap();
let right = MultiIndex::from_tuples(vec![
vec!["b".into(), 2_i64.into()],
vec!["d".into(), 4_i64.into()],
])
.unwrap();
assert_eq!(left.join(&right, "left").unwrap(), left);
assert_eq!(left.join(&right, "right").unwrap(), right);
assert_eq!(
left.join(&right, "inner").unwrap().to_list(),
vec![vec!["b".into(), 2_i64.into()]]
);
assert_eq!(
left.join(&right, "outer").unwrap().to_list(),
vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["c".into(), 3_i64.into()],
vec!["d".into(), 4_i64.into()]
]
);
}
#[test]
fn multi_index_groupby_join_rejects_bad_mode_and_level_mismatch_d89fe3() {
let left = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
let right = MultiIndex::from_tuples(vec![vec!["a".into()]]).unwrap();
assert!(left.join(&right, "sideways").is_err());
assert!(left.join(&right, "inner").is_err());
assert!(left.join(&right, "outer").is_err());
}
#[test]
fn multi_index_slice_locs_uses_lexicographic_bounds() {
let mi = MultiIndex::from_arrays(vec![
vec!["east".into(), "east".into(), "west".into(), "west".into()],
vec![1_i64.into(), 2_i64.into(), 1_i64.into(), 2_i64.into()],
])
.unwrap();
let (start, stop) = mi
.slice_locs(
Some(&[IndexLabel::Utf8("east".into()), IndexLabel::Int64(2)]),
Some(&[IndexLabel::Utf8("west".into()), IndexLabel::Int64(1)]),
)
.unwrap();
assert_eq!((start, stop), (1, 3));
}
#[test]
fn multi_index_slice_bound_partial_prefixes_d89fe2() {
let mi = MultiIndex::from_arrays(vec![
vec!["east".into(), "east".into(), "west".into(), "west".into()],
vec![1_i64.into(), 2_i64.into(), 1_i64.into(), 2_i64.into()],
])
.unwrap();
let east = [IndexLabel::Utf8("east".into())];
assert_eq!(mi.get_slice_bound(&east, "left").unwrap(), 0);
assert_eq!(mi.get_slice_bound(&east, "right").unwrap(), 2);
let west = [IndexLabel::Utf8("west".into())];
assert_eq!(mi.slice_indexer(Some(&west), None).unwrap(), (2, 4));
assert_eq!(mi.slice_indexer(None, Some(&east)).unwrap(), (0, 2));
}
#[test]
fn multi_index_slice_bound_full_tuple_and_missing_insert_d89fe2() {
let mi = MultiIndex::from_arrays(vec![
vec!["east".into(), "east".into(), "west".into(), "west".into()],
vec![1_i64.into(), 2_i64.into(), 1_i64.into(), 2_i64.into()],
])
.unwrap();
let exact = [IndexLabel::Utf8("east".into()), IndexLabel::Int64(2)];
assert_eq!(mi.get_slice_bound(&exact, "left").unwrap(), 1);
assert_eq!(mi.get_slice_bound(&exact, "right").unwrap(), 2);
let missing_insert = [IndexLabel::Utf8("east".into()), IndexLabel::Int64(3)];
assert_eq!(mi.get_slice_bound(&missing_insert, "left").unwrap(), 2);
assert_eq!(mi.get_slice_bound(&missing_insert, "right").unwrap(), 2);
}
#[test]
fn multi_index_slice_bound_rejects_invalid_side_d89fe2() {
let mi = MultiIndex::from_tuples(vec![vec![IndexLabel::Utf8("east".into())]]).unwrap();
let key = [IndexLabel::Utf8("east".into())];
assert!(mi.get_slice_bound(&key, "middle").is_err());
}
#[test]
fn multi_index_truncate_uses_prefix_bounds_d89fe11() -> Result<(), super::IndexError> {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 3_i64.into()],
vec!["b".into(), 1_i64.into()],
vec!["c".into(), 1_i64.into()],
])?
.set_names(vec![Some("letter".into()), Some("number".into())]);
let bounded = mi.truncate(
Some(&[IndexLabel::Utf8("a".into())]),
Some(&[IndexLabel::Utf8("b".into())]),
)?;
assert_eq!(
bounded.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(3)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
]
);
assert_eq!(bounded.names(), mi.names());
let tail = mi.truncate(Some(&[IndexLabel::Utf8("b".into())]), None)?;
assert_eq!(
tail.to_list(),
vec![
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(1)],
]
);
let clipped = mi.truncate(None, Some(&[IndexLabel::Utf8("aa".into())]))?;
assert_eq!(
clipped.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(3)],
]
);
let empty = mi.truncate(Some(&[IndexLabel::Utf8("d".into())]), None)?;
assert!(empty.is_empty());
assert_eq!(empty.names(), mi.names());
Ok(())
}
#[test]
fn multi_index_get_locs_prefix_and_exact_selectors_d89fe10() -> Result<(), super::IndexError> {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["b".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
assert_eq!(mi.get_locs(&[IndexLabel::Utf8("a".into())])?, vec![0, 1]);
assert_eq!(
mi.get_locs(&[IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)])?,
vec![0]
);
assert_eq!(mi.get_locs(&[])?, Vec::<usize>::new());
Ok(())
}
#[test]
fn multi_index_get_locs_rejects_missing_and_overlong_keys_d89fe10()
-> Result<(), super::IndexError> {
let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
assert!(mi.get_locs(&[IndexLabel::Utf8("z".into())]).is_err());
assert!(
mi.get_locs(&[
IndexLabel::Utf8("a".into()),
IndexLabel::Int64(1),
IndexLabel::Utf8("extra".into()),
])
.is_err()
);
Ok(())
}
#[test]
fn multi_index_get_indexer_non_unique_expands_duplicate_matches() {
let source = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["b".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
])
.unwrap();
let target = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["z".into(), 9_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
])
.unwrap();
let (indexer, missing) = source.get_indexer_non_unique(&target);
assert_eq!(indexer, vec![0, 3, -1, 1, 0, 3]);
assert_eq!(missing, vec![1]);
}
#[test]
fn multi_index_setop_packed_matches_reference_misetop() {
// intersection/difference packed path must equal an independent
// tuple-set reference (mixed Utf8+Int64 levels, duplicate self rows,
// partial overlap, disjoint, and empty other).
let mk = |spec: &[(&str, i64)]| {
MultiIndex::from_tuples(
spec.iter()
.map(|(s, i)| vec![IndexLabel::Utf8((*s).to_string()), IndexLabel::Int64(*i)])
.collect::<Vec<_>>(),
)
.unwrap()
};
type TupleSpec = Vec<(&'static str, i64)>;
type SetopCase = (TupleSpec, TupleSpec);
let cases: Vec<SetopCase> = vec![
(
vec![("a", 1), ("b", 2), ("a", 1), ("c", 3), ("b", 2)],
vec![("b", 2), ("c", 3), ("z", 9)],
),
(vec![("a", 1), ("b", 2)], vec![("x", 7), ("y", 8)]),
(vec![("a", 1), ("a", 1), ("b", 2)], vec![("a", 1)]),
];
for (sa, sb) in cases {
let a = mk(&sa);
let b = mk(&sb);
let bset: std::collections::HashSet<Vec<IndexLabel>> =
b.to_list().into_iter().collect();
let mut seen = std::collections::HashSet::new();
let ref_inter: Vec<Vec<IndexLabel>> = a
.to_list()
.into_iter()
.filter(|t| bset.contains(t) && seen.insert(t.clone()))
.collect();
assert_eq!(
a.intersection(&b).unwrap().to_list(),
ref_inter,
"inter {sa:?}"
);
let mut seen_d = std::collections::HashSet::new();
let ref_diff: Vec<Vec<IndexLabel>> = a
.to_list()
.into_iter()
.filter(|t| !bset.contains(t) && seen_d.insert(t.clone()))
.collect();
assert_eq!(a.difference(&b).unwrap().to_list(), ref_diff, "diff {sa:?}");
}
}
#[test]
fn multi_index_two_utf8_setops_preserve_order_and_names_codb188() {
let left = MultiIndex::from_arrays(vec![
vec![
"a".into(),
"b".into(),
"a".into(),
"c".into(),
"d".into(),
"b".into(),
],
vec![
"x".into(),
"y".into(),
"x".into(),
"z".into(),
"w".into(),
"y".into(),
],
])
.unwrap()
.set_names(vec![Some("L0".into()), Some("L1".into())]);
let right = MultiIndex::from_arrays(vec![
vec!["b".into(), "c".into(), "e".into(), "b".into()],
vec!["y".into(), "z".into(), "q".into(), "y".into()],
])
.unwrap()
.set_names(vec![Some("L0".into()), Some("other".into())]);
assert_eq!(
left.intersection(&right).unwrap().to_list(),
vec![
vec![IndexLabel::Utf8("b".into()), IndexLabel::Utf8("y".into())],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Utf8("z".into())],
]
);
assert_eq!(
left.difference(&right).unwrap().to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Utf8("x".into())],
vec![IndexLabel::Utf8("d".into()), IndexLabel::Utf8("w".into())],
]
);
assert_eq!(
left.union(&right).unwrap().to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Utf8("x".into())],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Utf8("y".into())],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Utf8("z".into())],
vec![IndexLabel::Utf8("d".into()), IndexLabel::Utf8("w".into())],
vec![IndexLabel::Utf8("e".into()), IndexLabel::Utf8("q".into())],
]
);
assert_eq!(
left.symmetric_difference(&right).unwrap().to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Utf8("x".into())],
vec![IndexLabel::Utf8("d".into()), IndexLabel::Utf8("w".into())],
vec![IndexLabel::Utf8("e".into()), IndexLabel::Utf8("q".into())],
]
);
assert_eq!(
left.intersection(&right).unwrap().names(),
vec![Some("L0".into()), None]
);
}
#[test]
fn multi_index_two_level_dedup_counts_identity_codes_codb2tc1q() {
let mi = MultiIndex::from_arrays(vec![
vec![
"a".into(),
"b".into(),
"a".into(),
"c".into(),
"b".into(),
"d".into(),
],
vec![
"x".into(),
"y".into(),
"x".into(),
"z".into(),
"y".into(),
"w".into(),
],
])
.unwrap()
.set_names(vec![Some("L0".into()), Some("L1".into())]);
assert_eq!(mi.nunique(), 4);
assert_eq!(
mi.duplicated(DuplicateKeep::First),
vec![false, false, true, false, true, false]
);
assert_eq!(
mi.duplicated(DuplicateKeep::Last),
vec![true, true, false, false, false, false]
);
assert_eq!(
mi.duplicated(DuplicateKeep::None),
vec![true, true, true, false, true, false]
);
let unique = mi.unique();
assert_eq!(
unique.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Utf8("x".into())],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Utf8("y".into())],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Utf8("z".into())],
vec![IndexLabel::Utf8("d".into()), IndexLabel::Utf8("w".into())],
]
);
assert_eq!(unique.names(), mi.names());
}
#[test]
fn multi_index_setop_generic_fallback_preserves_order_codb() {
// Force the generic Vec<IndexLabel> tuple-key path: 65 levels with
// multiple distinct values make mixed-radix u64 packing overflow.
let mk = |row_keys: &[i64]| {
let mut levels = Vec::with_capacity(65);
for level in 0..65 {
let column = row_keys
.iter()
.map(|key| IndexLabel::Utf8(format!("level-{level}:key-{key}")))
.collect();
levels.push(column);
}
MultiIndex::from_arrays(levels).unwrap()
};
let left = mk(&[0, 1, 0, 2]);
let right = mk(&[1, 3, 2, 1]);
assert_eq!(
left.intersection(&right).unwrap().to_list(),
mk(&[1, 2]).to_list()
);
assert_eq!(
left.union(&right).unwrap().to_list(),
mk(&[0, 1, 2, 3]).to_list()
);
assert_eq!(
left.difference(&right).unwrap().to_list(),
mk(&[0]).to_list()
);
assert_eq!(
left.symmetric_difference(&right).unwrap().to_list(),
mk(&[0, 3]).to_list()
);
}
#[test]
fn multi_index_duplicated_packed_matches_vec_reference_midedup() {
// The identity-packed-key duplicated path must equal an independent
// Vec<IndexLabel>-key reference for all keep modes (mixed Utf8+Int64
// levels with duplicate tuples).
let n = 400usize;
let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
let mut l0 = Vec::with_capacity(n);
let mut l1 = Vec::with_capacity(n);
for _ in 0..n {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
l0.push(IndexLabel::Utf8(format!("g{}", (state >> 40) % 6)));
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
l1.push(IndexLabel::Int64(((state >> 40) % 5) as i64));
}
let mi = MultiIndex::from_arrays(vec![l0, l1]).unwrap();
let rows = mi.to_list();
for keep in [
DuplicateKeep::First,
DuplicateKeep::Last,
DuplicateKeep::None,
] {
let mut want = vec![false; n];
match keep {
DuplicateKeep::First => {
let mut seen = std::collections::HashSet::new();
for (r, w) in want.iter_mut().enumerate() {
if !seen.insert(rows[r].clone()) {
*w = true;
}
}
}
DuplicateKeep::Last => {
let mut seen = std::collections::HashSet::new();
for r in (0..n).rev() {
if !seen.insert(rows[r].clone()) {
want[r] = true;
}
}
}
DuplicateKeep::None => {
let mut counts: std::collections::HashMap<Vec<IndexLabel>, usize> =
Default::default();
for r in &rows {
*counts.entry(r.clone()).or_insert(0) += 1;
}
for (r, w) in want.iter_mut().enumerate() {
if counts[&rows[r]] > 1 {
*w = true;
}
}
}
}
assert_eq!(mi.duplicated(keep), want, "duplicated {keep:?}");
}
// drop_duplicates/unique derive from duplicated(First).
let mut seen = std::collections::HashSet::new();
let kept: Vec<Vec<IndexLabel>> = rows
.iter()
.filter(|r| seen.insert((*r).clone()))
.cloned()
.collect();
assert_eq!(mi.unique().to_list(), kept);
assert_eq!(mi.nunique(), kept.len());
}
#[test]
fn multi_index_argsort_packed_matches_tuple_sort_misort() {
// The sorted-packed-key argsort must equal the level-by-level tuple
// comparison sort (stable, original-position tiebreak) for mixed
// Utf8+Int64 levels with duplicate tuples and shuffled order.
let n = 600usize;
let mut state: u64 = 0x1234_5678_9abc_def1;
let mut l0 = Vec::with_capacity(n);
let mut l1 = Vec::with_capacity(n);
for _ in 0..n {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
let a = (state >> 33) % 7; // low cardinality -> duplicate tuples
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
let b = (state >> 33) % 5;
l0.push(IndexLabel::Utf8(format!("g{a}")));
l1.push(IndexLabel::Int64(b as i64));
}
let mi = MultiIndex::from_arrays(vec![l0, l1]).unwrap();
// Independent reference: stable sort by lexicographic tuple, ties by pos.
let rows = mi.to_list();
let mut want: Vec<usize> = (0..n).collect();
want.sort_by(|&a, &b| rows[a].cmp(&rows[b]).then(a.cmp(&b)));
assert_eq!(mi.argsort(), want, "argsort");
assert_eq!(
mi.sort_values().to_list(),
mi.take_existing_positions(&want).to_list()
);
// min/max derive from argsort and must match the reference ends.
assert_eq!(mi.min(), Some(rows[want[0]].clone()));
assert_eq!(mi.max(), Some(rows[want[n - 1]].clone()));
}
#[test]
fn multi_index_get_indexer_packed_matches_vec_reference_mipack() {
// The packed-u64-key path must equal an independent Vec<IndexLabel>-key
// reference (mixed Utf8+Int64 levels, duplicate source, target-only
// values exercising fresh per-level codes and the mixed-radix packing).
let mk = |spec: &[(&str, i64)]| {
MultiIndex::from_tuples(
spec.iter()
.map(|(s, i)| vec![IndexLabel::Utf8((*s).to_string()), IndexLabel::Int64(*i)])
.collect::<Vec<_>>(),
)
.unwrap()
};
let source = mk(&[("a", 1), ("a", 2), ("b", 1), ("a", 1), ("c", 5), ("b", 2)]);
let target = mk(&[
("b", 1),
("z", 9),
("a", 1),
("a", 2),
("c", 5),
("q", 0),
("b", 2),
]);
let src_rows = source.to_list();
let tgt_rows = target.to_list();
let mut pos: std::collections::HashMap<Vec<IndexLabel>, Vec<usize>> = Default::default();
for (r, key) in src_rows.iter().enumerate() {
pos.entry(key.clone()).or_default().push(r);
}
let mut ref_ix = Vec::new();
let mut ref_miss = Vec::new();
for (tr, key) in tgt_rows.iter().enumerate() {
if let Some(m) = pos.get(key) {
ref_ix.extend(m.iter().map(|&p| p as isize));
} else {
ref_ix.push(-1);
ref_miss.push(tr);
}
}
let (ix, miss) = source.get_indexer_non_unique(&target);
assert_eq!(ix, ref_ix, "non_unique indexer");
assert_eq!(miss, ref_miss, "non_unique missing");
let usrc = mk(&[("a", 1), ("a", 2), ("b", 1), ("c", 5), ("b", 2)]);
let urows = usrc.to_list();
let mut upos: std::collections::HashMap<Vec<IndexLabel>, isize> = Default::default();
for (r, key) in urows.iter().enumerate() {
upos.entry(key.clone()).or_insert(r as isize);
}
let ref_u: Vec<isize> = tgt_rows
.iter()
.map(|k| upos.get(k).copied().unwrap_or(-1))
.collect();
assert_eq!(usrc.get_indexer(&target).unwrap(), ref_u, "unique indexer");
}
#[test]
fn multi_index_get_indexer_unique_maps_hits_and_missing_d89fe1() -> Result<(), super::IndexError>
{
let source = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["c".into(), 3_i64.into()],
])?;
let target = MultiIndex::from_tuples(vec![
vec!["b".into(), 2_i64.into()],
vec!["z".into(), 9_i64.into()],
vec!["a".into(), 1_i64.into()],
])?;
assert_eq!(source.get_indexer(&target)?, vec![1, -1, 0]);
assert_eq!(source.get_indexer_for(&target)?, vec![1, -1, 0]);
Ok(())
}
#[test]
fn multi_index_typed_outer_align_preserves_columns_and_rejects_duplicate_tuple_3gsa7()
-> Result<(), super::IndexError> {
let left = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["b".into(), 1_i64.into()],
])?;
let right = MultiIndex::from_tuples(vec![
vec!["a".into(), 2_i64.into()],
vec!["c".into(), 3_i64.into()],
])?;
let plan = left.outer_align(&right)?;
assert_eq!(
plan.union_index.to_list(),
vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["b".into(), 1_i64.into()],
vec!["c".into(), 3_i64.into()],
]
);
assert_eq!(plan.left_positions, vec![Some(0), Some(1), Some(2), None]);
assert_eq!(plan.right_positions, vec![None, Some(0), None, Some(1)]);
assert_eq!(plan.union_index, left.union(&right)?);
// A repeated value in one level is valid when the complete tuples are
// unique; a duplicate tuple is not valid for this unique-only witness.
let duplicate_tuple = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
])?;
let error = duplicate_tuple.outer_align(&right).unwrap_err();
assert!(matches!(
error,
super::IndexError::InvalidArgument(message)
if message == "outer_align requires uniquely valued MultiIndexes"
));
Ok(())
}
#[test]
fn multi_index_get_indexer_rejects_duplicate_source_d89fe1() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let target = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let err = match source.get_indexer(&target) {
Ok(indexer) => {
return Err(super::IndexError::InvalidArgument(format!(
"duplicate source index unexpectedly returned {indexer:?}"
)));
}
Err(err) => err,
};
assert!(matches!(
err,
super::IndexError::InvalidArgument(message)
if message == "get_indexer requires a uniquely valued MultiIndex"
));
assert_eq!(source.get_indexer_for(&target)?, vec![0, 1, 2]);
Ok(())
}
#[test]
fn multi_index_get_indexer_level_mismatch_marks_missing_d89fe1() -> Result<(), super::IndexError>
{
let source = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let target = MultiIndex::from_tuples(vec![vec!["a".into()], vec!["b".into()]])?;
assert_eq!(source.get_indexer(&target)?, vec![-1, -1]);
assert_eq!(source.get_indexer_for(&target)?, vec![-1, -1]);
Ok(())
}
#[test]
fn multi_index_reindex_maps_target_hits_and_missing_d89fe4() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["c".into(), 3_i64.into()],
])?;
let target = MultiIndex::from_tuples(vec![
vec!["b".into(), 2_i64.into()],
vec!["z".into(), 9_i64.into()],
vec!["a".into(), 1_i64.into()],
])?
.set_names(vec![Some("letter".into()), Some("number".into())]);
let (reindexed, indexer) = source.reindex(&target)?;
assert_eq!(reindexed, target);
assert_eq!(indexer, vec![1, -1, 0]);
Ok(())
}
#[test]
fn multi_index_reindex_rejects_duplicate_source_d89fe4() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
])?;
let target = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
assert!(source.reindex(&target).is_err());
Ok(())
}
#[test]
fn multi_index_reindex_level_mismatch_marks_missing_d89fe4() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
let target = MultiIndex::from_tuples(vec![vec!["a".into()]])?;
let (reindexed, indexer) = source.reindex(&target)?;
assert_eq!(reindexed, target);
assert_eq!(indexer, vec![-1]);
Ok(())
}
#[test]
fn multi_index_rename_replaces_all_names_d89fe5() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?
.set_names(vec![Some("old0".into()), Some("old1".into())]);
let renamed = source.rename(vec![Some("new0".into()), Some("new1".into())])?;
assert_eq!(renamed.names(), &[Some("new0".into()), Some("new1".into())]);
assert_eq!(source.names(), &[Some("old0".into()), Some("old1".into())]);
assert_eq!(renamed.to_list(), source.to_list());
Ok(())
}
#[test]
fn multi_index_rename_level_replaces_one_name_d89fe5() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?
.set_names(vec![Some("old0".into()), Some("old1".into())]);
let renamed = source.rename_level(Some("new1".into()), 1)?;
assert_eq!(renamed.names(), &[Some("old0".into()), Some("new1".into())]);
assert_eq!(source.names(), &[Some("old0".into()), Some("old1".into())]);
Ok(())
}
#[test]
fn multi_index_rename_rejects_wrong_name_count_d89fe5() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
let err = source.rename(vec![Some("only".into())]).unwrap_err();
assert!(matches!(
err,
super::IndexError::LengthMismatch {
expected: 2,
actual: 1,
..
}
));
Ok(())
}
#[test]
fn multi_index_rename_level_rejects_out_of_bounds_d89fe5() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
let err = source.rename_level(Some("missing".into()), 2).unwrap_err();
assert!(matches!(
err,
super::IndexError::OutOfBounds {
position: 2,
length: 2
}
));
Ok(())
}
#[test]
fn multi_index_searchsorted_left_and_right_d89fe6() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 3_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let target = MultiIndex::from_tuples(vec![
vec!["a".into(), 0_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["a".into(), 3_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["c".into(), 0_i64.into()],
])?;
assert_eq!(
source.searchsorted(&target, "left")?,
vec![0, 0, 1, 1, 2, 4]
);
assert_eq!(
source.searchsorted(&target, "right")?,
vec![0, 1, 1, 2, 4, 4]
);
Ok(())
}
#[test]
fn multi_index_searchsorted_empty_target_d89fe6() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
let target = MultiIndex::from_tuples(Vec::new())?;
assert_eq!(source.searchsorted(&target, "left")?, Vec::<usize>::new());
Ok(())
}
#[test]
fn multi_index_searchsorted_rejects_invalid_side_d89fe6() -> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
let target = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]])?;
let err = source.searchsorted(&target, "middle").unwrap_err();
assert!(matches!(
err,
super::IndexError::InvalidArgument(message)
if message == "searchsorted: side must be 'left' or 'right', got \"middle\""
));
Ok(())
}
#[test]
fn multi_index_get_indexer_non_unique_level_mismatch_marks_all_missing() {
let source = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap();
let target = MultiIndex::from_tuples(vec![vec!["a".into()], vec!["b".into()]]).unwrap();
let (indexer, missing) = source.get_indexer_non_unique(&target);
assert_eq!(indexer, vec![-1, -1]);
assert_eq!(missing, vec![0, 1]);
}
#[test]
fn multi_index_isin_tuple_membership() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 3_i64.into()],
])
.unwrap();
let needles: Vec<Vec<IndexLabel>> = vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
];
assert_eq!(mi.isin(&needles), vec![true, true, false]);
}
#[test]
fn multi_index_isin_ignores_mismatched_tuple_length() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap();
// Wrong-arity tuple contributes no matches.
let needles: Vec<Vec<IndexLabel>> = vec![vec!["a".into()]];
assert_eq!(mi.isin(&needles), vec![false, false]);
}
#[test]
fn multi_index_isin_empty_values_yields_all_false() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap();
let needles: Vec<Vec<IndexLabel>> = Vec::new();
assert_eq!(mi.isin(&needles), vec![false, false]);
}
#[test]
fn multi_index_isin_level_filters_by_level() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 3_i64.into()],
])
.unwrap();
let level0 = mi.isin_level(&["a".into()], 0).unwrap();
assert_eq!(level0, vec![true, false, true]);
let level1 = mi.isin_level(&[2_i64.into(), 3_i64.into()], 1).unwrap();
assert_eq!(level1, vec![false, true, true]);
}
#[test]
fn multi_index_isin_level_out_of_bounds_errors() {
let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
let err = mi.isin_level(&["a".into()], 5).unwrap_err();
assert!(matches!(err, crate::IndexError::OutOfBounds { .. }));
}
#[test]
fn multi_index_isin_empty_index_yields_empty() {
let mi = MultiIndex::from_tuples(Vec::new()).unwrap();
let needles: Vec<Vec<IndexLabel>> = vec![vec!["a".into(), 1_i64.into()]];
assert_eq!(mi.isin(&needles), Vec::<bool>::new());
}
#[test]
fn multi_index_duplicated_keep_first_default() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["c".into(), 3_i64.into()],
])
.unwrap();
let dup = mi.duplicated(DuplicateKeep::First);
assert_eq!(dup, vec![false, false, true, false]);
}
#[test]
fn multi_index_duplicated_keep_last_marks_earlier_occurrences() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap();
let dup = mi.duplicated(DuplicateKeep::Last);
assert_eq!(dup, vec![true, false, false]);
}
#[test]
fn multi_index_duplicated_keep_none_marks_all_repeats() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["c".into(), 3_i64.into()],
])
.unwrap();
let dup = mi.duplicated(DuplicateKeep::None);
assert_eq!(dup, vec![true, false, true, false]);
}
#[test]
fn multi_index_is_unique_true_and_false() {
let unique = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap();
assert!(unique.is_unique());
assert!(!unique.has_duplicates());
let duped = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
])
.unwrap();
assert!(!duped.is_unique());
assert!(duped.has_duplicates());
}
fn multi_index_is_unique_former_haoam(index: &MultiIndex) -> bool {
!index
.duplicated(DuplicateKeep::First)
.iter()
.any(|&duplicated| duplicated)
}
#[test]
fn multi_index_is_unique_short_circuit_matches_former_haoam() {
let compact_unique = MultiIndex::from_arrays(vec![
vec![0_i64.into(), 1_i64.into(), 0_i64.into(), 1_i64.into()],
vec![0_i64.into(), 0_i64.into(), 1_i64.into(), 1_i64.into()],
])
.unwrap();
let compact_duplicate = MultiIndex::from_arrays(vec![
vec![0_i64.into(), 0_i64.into(), 1_i64.into()],
vec![1_i64.into(), 1_i64.into(), 0_i64.into()],
])
.unwrap();
let packed_unique = MultiIndex::from_arrays(vec![
vec![0_i64.into(), 1_i64.into(), 0_i64.into()],
vec![0_i64.into(), 0_i64.into(), 1_i64.into()],
vec![1_i64.into(), 1_i64.into(), 0_i64.into()],
])
.unwrap();
let packed_duplicate = MultiIndex::from_arrays(vec![
vec![0_i64.into(), 1_i64.into(), 0_i64.into()],
vec![0_i64.into(), 1_i64.into(), 0_i64.into()],
vec![1_i64.into(), 0_i64.into(), 1_i64.into()],
])
.unwrap();
let generic = |keys: &[i64]| {
let levels = (0..65)
.map(|level| {
keys.iter()
.map(|key| IndexLabel::Utf8(format!("level-{level}:key-{key}")))
.collect()
})
.collect();
MultiIndex::from_arrays(levels).unwrap()
};
let generic_unique = generic(&[0, 1, 2]);
let generic_duplicate = generic(&[0, 1, 0]);
let empty = MultiIndex::from_arrays(vec![Vec::new(), Vec::new()]).unwrap();
let singleton = MultiIndex::from_tuples(vec![vec![0_i64.into(), "x".into()]]).unwrap();
for index in [
&empty,
&singleton,
&compact_unique,
&compact_duplicate,
&packed_unique,
&packed_duplicate,
&generic_unique,
&generic_duplicate,
] {
let former = multi_index_is_unique_former_haoam(index);
assert_eq!(index.is_unique(), former);
assert_eq!(index.has_duplicates(), !former);
}
}
#[test]
#[ignore = "foreground release A/B for br-frankenpandas-haoam"]
fn multi_index_is_unique_short_circuit_ab_haoam() {
const ITEMS: usize = 131_072;
const SAMPLES: usize = 10;
const CALLS: usize = 4;
let make_index = |duplicate_first: bool| {
let mut level0 = Vec::with_capacity(ITEMS);
let mut level1 = Vec::with_capacity(ITEMS);
for row in 0..ITEMS {
let key = if duplicate_first && row < 2 {
0
} else if duplicate_first {
row - 1
} else {
row
};
level0.push(IndexLabel::Int64((key % 512) as i64));
level1.push(IndexLabel::Int64((key / 512) as i64));
}
MultiIndex::from_arrays(vec![level0, level1]).unwrap()
};
let early_duplicate = make_index(true);
let all_unique = make_index(false);
for index in [&early_duplicate, &all_unique] {
assert_eq!(index.is_unique(), multi_index_is_unique_former_haoam(index));
std::hint::black_box(multi_index_is_unique_former_haoam(index));
std::hint::black_box(index.is_unique());
}
let measure = |index: &MultiIndex, former: bool| {
let start = std::time::Instant::now();
for _ in 0..CALLS {
let unique = if former {
multi_index_is_unique_former_haoam(index)
} else {
index.is_unique()
};
std::hint::black_box(unique);
}
start.elapsed().as_nanos()
};
let mut early_former = Vec::with_capacity(SAMPLES);
let mut early_candidate = Vec::with_capacity(SAMPLES);
let mut unique_former = Vec::with_capacity(SAMPLES);
let mut unique_candidate = Vec::with_capacity(SAMPLES);
for sample in 0..SAMPLES {
if sample % 2 == 0 {
early_former.push(measure(&early_duplicate, true));
early_candidate.push(measure(&early_duplicate, false));
unique_candidate.push(measure(&all_unique, false));
unique_former.push(measure(&all_unique, true));
} else {
early_candidate.push(measure(&early_duplicate, false));
early_former.push(measure(&early_duplicate, true));
unique_former.push(measure(&all_unique, true));
unique_candidate.push(measure(&all_unique, false));
}
}
early_former.sort_unstable();
early_candidate.sort_unstable();
unique_former.sort_unstable();
unique_candidate.sort_unstable();
let middle = SAMPLES / 2;
println!(
"multi_index_is_unique_short_circuit_ab items={ITEMS} calls={CALLS} samples={SAMPLES} early_former_p50_ns={} early_candidate_p50_ns={} early_speedup={:.6}x unique_former_p50_ns={} unique_candidate_p50_ns={} unique_speedup={:.6}x\nearly_former_samples_ns={early_former:?}\nearly_candidate_samples_ns={early_candidate:?}\nunique_former_samples_ns={unique_former:?}\nunique_candidate_samples_ns={unique_candidate:?}",
early_former[middle],
early_candidate[middle],
early_former[middle] as f64 / early_candidate[middle] as f64,
unique_former[middle],
unique_candidate[middle],
unique_former[middle] as f64 / unique_candidate[middle] as f64,
);
}
#[test]
fn multi_index_duplicated_empty_yields_empty() {
let mi = MultiIndex::from_tuples(Vec::new()).unwrap();
assert_eq!(mi.duplicated(DuplicateKeep::First), Vec::<bool>::new());
assert!(mi.is_unique());
}
#[test]
fn multi_index_all_any_reject_bool_reduction_d89fe7() -> Result<(), super::IndexError> {
let non_empty = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let empty = MultiIndex::from_arrays(vec![Vec::new(), Vec::new()])?;
let cases = [
(
non_empty.all().unwrap_err(),
"cannot perform all with this index type: MultiIndex",
),
(
non_empty.any().unwrap_err(),
"cannot perform any with this index type: MultiIndex",
),
(
empty.all().unwrap_err(),
"cannot perform all with this index type: MultiIndex",
),
(
empty.any().unwrap_err(),
"cannot perform any with this index type: MultiIndex",
),
];
for (err, expected) in cases {
assert!(matches!(
err,
super::IndexError::InvalidArgument(message) if message == expected
));
}
Ok(())
}
#[test]
fn multi_index_shift_rejects_temporal_shift_d89fe9() -> Result<(), super::IndexError> {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let expected = "This method is only implemented for DatetimeIndex, PeriodIndex and TimedeltaIndex; Got type MultiIndex";
for err in [
mi.shift(1, None).unwrap_err(),
mi.shift(0, None).unwrap_err(),
mi.shift(1, Some("D")).unwrap_err(),
] {
assert!(matches!(
err,
super::IndexError::InvalidArgument(message) if message == expected
));
}
Ok(())
}
#[test]
fn multi_index_str_rejects_string_accessor_d89fe12() -> Result<(), super::IndexError> {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let err = mi.r#str().unwrap_err();
assert!(matches!(
err,
super::IndexError::InvalidArgument(message)
if message == "Can only use .str accessor with Index, not MultiIndex"
));
Ok(())
}
#[test]
fn multi_index_astype_object_clones_other_dtypes_reject_c2x17() -> Result<(), super::IndexError>
{
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
for dtype in ["object", "O"] {
let cloned = mi.astype(dtype)?;
assert!(cloned.equals(&mi));
assert_eq!(cloned.nlevels(), mi.nlevels());
assert_eq!(cloned.len(), mi.len());
}
let cat_err = mi.astype("category").unwrap_err();
assert!(matches!(
cat_err,
super::IndexError::InvalidArgument(message)
if message == "> 1 ndim Categorical are not supported at this time"
));
for dtype in ["int64", "float64", "datetime64[ns]"] {
let err = mi.astype(dtype).unwrap_err();
let expected = format!(
"Setting a MultiIndex dtype to anything other than object is not supported; got {dtype}"
);
assert!(matches!(
err,
super::IndexError::InvalidArgument(message) if message == expected
));
}
Ok(())
}
#[test]
fn multi_index_diff_rejects_tuple_subtraction_c2x17() -> Result<(), super::IndexError> {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["c".into(), 3_i64.into()],
])?;
let expected = "cannot perform __sub__ with this index type: MultiIndex";
for periods in [-1_i64, 0, 1, 2] {
let err = mi.diff(periods).unwrap_err();
assert!(matches!(
err,
super::IndexError::InvalidArgument(message) if message == expected
));
}
Ok(())
}
/// `MultiIndex.round` is a NO-OP in pandas, not a refusal.
///
/// ⚠️ THIS TEST USED TO ASSERT THE OPPOSITE, pinning the numpy `rint` error
/// text. The refusal and this assertion both rested on the reasoning that
/// pandas applies `np.around` to tuple labels. It does not. MEASURED, live
/// pandas 2.2.3:
///
/// ```text
/// mi = pd.MultiIndex.from_tuples([(1.567, "a"), (2.345, "b")])
/// mi.round(0) / round(2) / round(-1) -> [(1.567, 'a'), (2.345, 'b')]
/// mi.round(2).equals(mi) -> True
/// np.around(mi, 2) -> TypeError (a DIFFERENT call, and a
/// different message from the one that
/// was pinned here)
/// ```
///
/// Found by the error-only-stub classifier added to
/// scripts/validate_api_coverage_drift.py: it flagged ten MultiIndex methods
/// whose whole body is `Err(...)`, and probing all ten against pandas showed
/// NINE are correct refusals (pandas raises too, and for `all`/`any` with the
/// same wording) while `round` alone was wrong.
#[test]
fn multi_index_round_is_a_no_op_matching_pandas_c2x17() -> Result<(), super::IndexError> {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
for decimals in [-1_i32, 0, 1, 4] {
let rounded = mi.round(decimals)?;
assert_eq!(
rounded.values(),
mi.values(),
"round({decimals}) must leave a MultiIndex unchanged"
);
}
// Float levels are NOT rounded either — the no-op is total, which is the
// half a "rounding is unsupported here" reading would still get wrong.
let floats = MultiIndex::from_tuples(vec![
vec![
super::IndexLabel::Float64(super::OrderedF64(1.567)),
"a".into(),
],
vec![
super::IndexLabel::Float64(super::OrderedF64(2.345)),
"b".into(),
],
])?;
assert_eq!(floats.round(2)?.values(), floats.values());
Ok(())
}
#[test]
fn range_index_argmax_argmin_handles_step_direction_mrchb() {
let asc = super::RangeIndex::new(0, 5, 1).unwrap();
assert_eq!(asc.argmax().unwrap(), 4);
assert_eq!(asc.argmin().unwrap(), 0);
let desc = super::RangeIndex::new(10, 0, -2).unwrap();
assert_eq!(desc.argmax().unwrap(), 0);
assert_eq!(desc.argmin().unwrap(), desc.len() - 1);
let big_step = super::RangeIndex::new(1, 100, 7).unwrap();
assert_eq!(big_step.argmax().unwrap(), big_step.len() - 1);
assert_eq!(big_step.argmin().unwrap(), 0);
}
#[test]
fn range_index_argmax_argmin_reject_empty_mrchb() {
let empty = super::RangeIndex::new(5, 5, 1).unwrap();
assert!(empty.is_empty());
let max_err = empty.argmax().unwrap_err();
assert!(matches!(
max_err,
super::IndexError::InvalidArgument(ref message)
if message == "attempt to get argmax of an empty sequence"
));
let min_err = empty.argmin().unwrap_err();
assert!(matches!(
min_err,
super::IndexError::InvalidArgument(ref message)
if message == "attempt to get argmin of an empty sequence"
));
}
#[test]
fn range_index_argsort_orientation_matches_step_sign_mrchb() {
let asc = super::RangeIndex::new(0, 5, 1).unwrap();
assert_eq!(asc.argsort(), vec![0, 1, 2, 3, 4]);
let desc = super::RangeIndex::new(10, 0, -2).unwrap();
assert_eq!(desc.argsort(), vec![4, 3, 2, 1, 0]);
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert_eq!(empty.argsort(), Vec::<usize>::new());
}
#[test]
fn datetime_index_time_of_day_accessors_match_pandas_znejf() {
// 2024-01-01T12:34:56.789012345Z
// secs = 1704112496, subsec_nanos = 789_012_345
// total nanos = 1_704_112_496_000_000_000 + 789_012_345
// = 1_704_112_496_789_012_345
let total: i64 = 1_704_112_496 * 1_000_000_000 + 789_012_345;
let dt = super::DatetimeIndex::new(vec![total, i64::MIN, 0]);
assert_eq!(dt.hour(), vec![Some(12), None, Some(0)]);
assert_eq!(dt.minute(), vec![Some(34), None, Some(0)]);
assert_eq!(dt.second(), vec![Some(56), None, Some(0)]);
assert_eq!(dt.microsecond(), vec![Some(789_012), None, Some(0)]);
assert_eq!(dt.nanosecond(), vec![Some(345), None, Some(0)]);
}
#[test]
fn datetime_index_time_of_day_indexers_match_pandas_bwzmn() -> Result<(), super::IndexError> {
let hour = fp_types::Timedelta::NANOS_PER_HOUR;
let minute = fp_types::Timedelta::NANOS_PER_MIN;
let day = fp_types::Timedelta::NANOS_PER_DAY;
let dt = super::DatetimeIndex::new(vec![
9 * hour,
12 * hour + 30 * minute,
i64::MIN,
23 * hour + 30 * minute,
day + 30 * minute,
]);
assert_eq!(dt.indexer_at_time("12:30")?, vec![1]);
assert_eq!(dt.indexer_at_time("12:30:00.000000000")?, vec![1]);
assert_eq!(dt.indexer_at_time("00:30:00")?, vec![4]);
assert!(dt.indexer_at_time("not-a-time").is_err());
assert_eq!(
dt.indexer_between_time("08:00", "13:00", true, true)?,
vec![0, 1]
);
assert_eq!(
dt.indexer_between_time("09:00", "13:00", false, true)?,
vec![1]
);
assert_eq!(
dt.indexer_between_time("23:00", "01:00", true, true)?,
vec![3, 4]
);
assert_eq!(
dt.indexer_between_time("23:30", "00:30", false, false)?,
Vec::<usize>::new()
);
assert!(
dt.indexer_between_time("09:00", "not-a-time", true, true)
.is_err()
);
Ok(())
}
#[test]
fn datetime_index_week_weekofyear_match_pandas_e8xhb() {
const NS: i64 = 1_000_000_000;
// 2024-01-01 (Monday) is in ISO week 1 of 2024.
let jan_01 = 1_704_067_200_i64 * NS;
// 2024-12-30 (Monday) is in ISO week 1 of 2025 (yes: pandas/ chrono
// both report this as week 1).
let dec_30 = 1_735_516_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![jan_01, dec_30, i64::MIN]);
let weeks = dt.week();
assert_eq!(weeks[0], Some(1));
assert_eq!(weeks[1], Some(1));
assert_eq!(weeks[2], None);
// weekofyear is an alias.
assert_eq!(dt.weekofyear(), weeks);
assert_eq!(
dt.isocalendar(),
vec![Some((2024, 1, 1)), Some((2025, 1, 1)), None]
);
}
#[test]
fn datetime_index_day_of_x_and_quarter_match_pandas_k860x() {
// 2024-01-15T00:00:00Z (a Monday).
let mon: i64 = 1_705_276_800 * 1_000_000_000;
// 2024-01-21T00:00:00Z (a Sunday).
let sun: i64 = 1_705_795_200 * 1_000_000_000;
// 2024-04-30T00:00:00Z (Apr -> 30 days; Q2).
let apr30: i64 = 1_714_435_200 * 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![mon, sun, apr30, i64::MIN]);
// 2024 is a leap year. Jan 15 = ordinal 15. Jan 21 = ordinal 21.
// Apr 30 = 31+29+31+30 = 121.
assert_eq!(dt.dayofyear(), vec![Some(15), Some(21), Some(121), None]);
assert_eq!(dt.day_of_year(), dt.dayofyear());
// Mon=0, Sun=6. Apr 30 2024 was a Tuesday → 1.
assert_eq!(dt.dayofweek(), vec![Some(0), Some(6), Some(1), None]);
assert_eq!(dt.day_of_week(), dt.dayofweek());
assert_eq!(dt.weekday(), dt.dayofweek());
// Q1 / Q1 / Q2.
assert_eq!(dt.quarter(), vec![Some(1), Some(1), Some(2), None]);
// 2024 is a leap year.
assert_eq!(
dt.is_leap_year(),
vec![Some(true), Some(true), Some(true), None]
);
// Jan -> 31, Apr -> 30.
assert_eq!(dt.days_in_month(), vec![Some(31), Some(31), Some(30), None]);
assert_eq!(dt.daysinmonth(), dt.days_in_month());
}
#[test]
fn datetime_index_boundary_accessors_match_pandas_qy7yd() {
// 2024 is a leap year. Each entry is the 00:00:00Z second-of-epoch
// multiplied by 1_000_000_000.
const NS: i64 = 1_000_000_000;
let jan_01 = 1_704_067_200_i64 * NS; // year/quarter/month start
let jan_31 = 1_706_659_200_i64 * NS; // month end (Jan)
let feb_29 = 1_709_164_800_i64 * NS; // leap-month end
let mar_31 = 1_711_843_200_i64 * NS; // quarter/month end (Q1)
let apr_01 = 1_711_929_600_i64 * NS; // quarter/month start (Q2)
let dec_31 = 1_735_603_200_i64 * NS; // year/quarter/month end
let nat = i64::MIN;
let dt =
super::DatetimeIndex::new(vec![jan_01, jan_31, feb_29, mar_31, apr_01, dec_31, nat]);
// is_year_start: only Jan 1.
assert_eq!(
dt.is_year_start(),
vec![
Some(true),
Some(false),
Some(false),
Some(false),
Some(false),
Some(false),
None
]
);
// is_year_end: only Dec 31.
assert_eq!(
dt.is_year_end(),
vec![
Some(false),
Some(false),
Some(false),
Some(false),
Some(false),
Some(true),
None
]
);
// is_quarter_start: Jan 1, Apr 1.
assert_eq!(
dt.is_quarter_start(),
vec![
Some(true),
Some(false),
Some(false),
Some(false),
Some(true),
Some(false),
None
]
);
// is_quarter_end: Mar 31, Dec 31.
assert_eq!(
dt.is_quarter_end(),
vec![
Some(false),
Some(false),
Some(false),
Some(true),
Some(false),
Some(true),
None
]
);
// is_month_start: Jan 1, Apr 1.
assert_eq!(
dt.is_month_start(),
vec![
Some(true),
Some(false),
Some(false),
Some(false),
Some(true),
Some(false),
None
]
);
// is_month_end: Jan 31, Feb 29 (leap), Mar 31, Dec 31.
assert_eq!(
dt.is_month_end(),
vec![
Some(false),
Some(true),
Some(true),
Some(true),
Some(false),
Some(true),
None
]
);
}
#[test]
fn index_variants_insert_match_pandas_veabb() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, c]).set_name("ts");
// Middle insertion.
let middle = dt.insert(1, b)?;
assert_eq!(middle.values(), vec![Some(a), Some(b), Some(c)]);
assert_eq!(middle.name().map(|n| n.as_str()), Some("ts"));
// End insertion (loc == len()).
let end = dt.insert(dt.len(), b)?;
assert_eq!(end.values(), vec![Some(a), Some(c), Some(b)]);
// OOB.
assert!(matches!(
dt.insert(99, b).unwrap_err(),
super::IndexError::OutOfBounds {
position: 99,
length: 2
}
));
let td = super::TimedeltaIndex::new(vec![100_i64, 300]).set_name("d");
let td_inserted = td.insert(1, 200)?;
assert_eq!(td_inserted.values(), vec![Some(100), Some(200), Some(300)]);
assert_eq!(td_inserted.name().map(|n| n.as_str()), Some("d"));
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p3]).set_name("p");
let pi_inserted = pi.insert(1, p2)?;
assert_eq!(pi_inserted.values(), &[p1, p2, p3]);
let r = super::RangeIndex::new(0, 3, 1).unwrap();
let r_inserted = r.insert(1, 99)?;
let labels = int64_labels(&r_inserted);
assert_eq!(labels, vec![0, 99, 1, 2]);
Ok(())
}
#[test]
fn index_variants_format_match_pandas_n31q2() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS, i64::MIN]);
let dt_fmt = dt.format();
assert!(dt_fmt[0].starts_with("2024-01-01"));
assert_eq!(dt_fmt[1], "NaT");
let td = super::TimedeltaIndex::new(vec![1_000_000_i64, fp_types::Timedelta::NAT]);
let td_fmt = td.format();
assert_eq!(td_fmt[0], "1000000");
assert_eq!(td_fmt[1], "NaT");
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![Period::new(10, PeriodFreq::Monthly)]);
let pi_fmt = pi.format();
assert!(!pi_fmt[0].is_empty());
let cat = super::CategoricalIndex::from_values(vec!["a".to_owned(), "b".to_owned()], false);
assert_eq!(cat.format(), vec!["a".to_owned(), "b".to_owned()]);
}
#[test]
fn datetime_timedelta_fillna_isnull_match_pandas_az3t9() {
const NS: i64 = 1_000_000_000;
let unix = 1_704_067_200_i64 * NS;
let dt = super::DatetimeIndex::new(vec![unix, i64::MIN, 0]).set_name("ts");
let filled = dt.fillna(unix);
// NAT is replaced; existing values are preserved.
assert_eq!(filled.values(), vec![Some(unix), Some(unix), Some(0)]);
assert_eq!(filled.name().map(|n| n.as_str()), Some("ts"));
let iso = dt.isnull();
assert_eq!(iso, dt.isna());
let nio = dt.notnull();
assert_eq!(nio, dt.notna());
let nat = fp_types::Timedelta::NAT;
let td = super::TimedeltaIndex::new(vec![100_i64, nat, 0]).set_name("d");
let td_filled = td.fillna(99);
assert_eq!(td_filled.values(), vec![Some(100), Some(99), Some(0)]);
assert_eq!(td_filled.name().map(|n| n.as_str()), Some("d"));
assert_eq!(td.isnull(), td.isna());
assert_eq!(td.notnull(), td.notna());
}
#[test]
fn datetime_index_date_and_time_accessors_match_pandas_66pll() {
const NS: i64 = 1_000_000_000;
// 2024-01-15T12:34:56.789012345Z (computed in br-teeck).
let total: i64 = 1_705_322_096_i64 * NS + 789_012_345;
let dt = super::DatetimeIndex::new(vec![total, i64::MIN, 0]);
let dates = dt.date();
assert_eq!(
dates[0],
Some(chrono::NaiveDate::from_ymd_opt(2024, 1, 15).unwrap())
);
assert_eq!(dates[1], None);
assert_eq!(
dates[2],
Some(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
);
let times = dt.time();
assert_eq!(
times[0],
chrono::NaiveTime::from_hms_nano_opt(12, 34, 56, 789_012_345)
);
assert_eq!(times[1], None);
assert_eq!(times[2], chrono::NaiveTime::from_hms_nano_opt(0, 0, 0, 0));
assert_eq!(dt.timetz(), times);
}
#[test]
fn datetime_index_to_pydatetime_and_julian_match_pandas_dww6m() {
const NS: i64 = 1_000_000_000;
// 2024-01-01T00:00:00Z
let unix = 1_704_067_200_i64;
let total = unix * NS;
let dt = super::DatetimeIndex::new(vec![total, i64::MIN]);
let pydt = dt.to_pydatetime();
let first = pydt[0].expect("non-NAT label decodes");
assert_eq!(first.timestamp(), unix);
assert_eq!(pydt[1], None);
let julian = dt.to_julian_date();
// JD for 2024-01-01T00:00:00Z = 2_460_310.5.
let expected = (unix as f64) / 86_400.0 + 2_440_587.5;
let observed = julian[0].expect("non-NAT label decodes");
assert!((observed - expected).abs() < 1e-9);
assert_eq!(julian[1], None);
}
#[test]
fn timedelta_index_to_pytimedelta_match_pandas_dww6m() {
let one_day_nanos = fp_types::Timedelta::NANOS_PER_DAY;
let td = super::TimedeltaIndex::new(vec![one_day_nanos, fp_types::Timedelta::NAT]);
let durations = td.to_pytimedelta();
let one_day = durations[0].expect("non-NAT label decodes");
assert_eq!(one_day.num_seconds(), 86_400);
assert_eq!(durations[1], None);
}
#[test]
fn relabeled_keeps_the_name_and_the_zone_of_datetime_labels_fvsao_60() {
let instants = |ns: &[i64]| ns.iter().map(|&v| IndexLabel::Datetime64(v)).collect();
let aware = Index::new(instants(&[30, 10, 20]))
.set_names(Some("when"))
.with_tz(Some("US/Eastern"))
.unwrap();
// A subset / reordering of the labels keeps both (Index::new plus
// the name dropped the zone).
let taken = aware.relabeled(instants(&[20, 30]));
assert_eq!(taken.name().map(|n| n.as_str()), Some("when"));
assert_eq!(taken.tz(), Some("US/Eastern"));
// NEGATIVES: labels that are not all datetimes keep the name only;
// a naive index invents no zone.
let text = aware.relabeled(vec![IndexLabel::Utf8("a".to_owned())]);
assert_eq!(
(text.name().map(|n| n.as_str()), text.tz()),
(Some("when"), None)
);
let naive = Index::new(instants(&[1])).relabeled(instants(&[1]));
assert_eq!(naive.tz(), None);
}
#[test]
fn datetime_index_tz_localize_tz_convert_match_pandas_qm31w() {
use fp_types::TimeZoneError;
const NS: i64 = 1_000_000_000;
const HOUR: i64 = 3_600 * NS;
// Wall 2024-01-01 09:00 and 2024-07-01 09:00 (naive).
let jan = 1_704_067_200_i64 * NS + 9 * HOUR;
let jul = 1_719_792_000_i64 * NS + 9 * HOUR;
let dt = super::DatetimeIndex::new(vec![jan, jul, i64::MIN]).set_name("ts");
assert_eq!(dt.tz(), None);
// pandas: New York is EST (-5h) in January and EDT (-4h) in July;
// the labels become UTC instants, the fields keep the wall clock.
let ny = dt.tz_localize(Some("US/Eastern")).expect("localize");
assert_eq!(ny.tz().as_deref(), Some("US/Eastern"));
assert_eq!(ny.name().map(|n| n.as_str()), Some("ts"));
assert_eq!(
ny.values(),
vec![Some(jan + 5 * HOUR), Some(jul + 4 * HOUR), None]
);
assert_eq!(ny.hour(), vec![Some(9), Some(9), None]);
// pandas' equals: the same instants in another zone (or naive) differ.
let same_instants_naive = ny.tz_convert(None).expect("naive UTC");
assert!(!ny.equals(&same_instants_naive));
assert!(!ny.equals(&ny.tz_convert(Some("UTC")).expect("UTC")));
assert!(ny.equals(&ny.clone()));
// tz_convert keeps the instants and moves the wall clock.
let tokyo = ny.tz_convert(Some("Asia/Tokyo")).expect("convert");
assert_eq!(tokyo.values(), ny.values());
assert_eq!(tokyo.hour(), vec![Some(23), Some(22), None]);
assert_eq!(tokyo.day(), vec![Some(1), Some(1), None]);
// tz_convert(None) is UTC, naive; tz_localize(None) keeps the wall.
let utc_naive = ny.tz_convert(None).expect("to naive UTC");
assert_eq!(utc_naive.tz(), None);
assert_eq!(utc_naive.values(), ny.values());
assert!(ny.tz_localize(None).expect("drop zone").equals(&dt));
// A take keeps the zone; normalize is the wall-clock midnight.
assert_eq!(
ny.take(&[1]).expect("take").tz().as_deref(),
Some("US/Eastern")
);
let midnights = ny.normalize().expect("normalize");
assert_eq!(midnights.tz().as_deref(), Some("US/Eastern"));
assert_eq!(midnights.hour(), vec![Some(0), Some(0), None]);
assert_eq!(
midnights.values(),
vec![
Some(jan - 9 * HOUR + 5 * HOUR),
Some(jul - 9 * HOUR + 4 * HOUR),
None
]
);
// NEGATIVES (pandas' errors): localizing an aware index, converting a
// naive one, a wall time a DST change skips, an unknown zone.
assert!(matches!(
ny.tz_localize(Some("UTC")),
Err(super::IndexError::TimeZoneMismatch(ref m)) if m.contains("Already tz-aware")
));
assert!(matches!(
dt.tz_convert(Some("UTC")),
Err(super::IndexError::TimeZoneMismatch(ref m)) if m.contains("tz-naive")
));
let skipped = 1_710_028_800_i64 * NS + 2 * HOUR + 30 * 60 * NS; // 2024-03-10 02:30
assert_eq!(
super::DatetimeIndex::new(vec![skipped]).tz_localize(Some("US/Eastern")),
Err(super::IndexError::TimeZone(TimeZoneError::NonExistent(
"2024-03-10 02:30:00".to_owned()
)))
);
assert!(matches!(
dt.tz_localize(Some("Mars/Base")),
Err(super::IndexError::TimeZone(TimeZoneError::Unknown(_)))
));
}
#[test]
fn datetime_timedelta_as_unit_match_pandas_70mbe() {
let dt = super::DatetimeIndex::new(vec![]);
assert!(dt.as_unit("ns").is_ok());
let bad = dt.as_unit("us").unwrap_err();
assert!(matches!(
bad,
super::IndexError::InvalidArgument(ref msg) if msg.contains("as_unit")
));
let td = super::TimedeltaIndex::new(vec![]);
assert!(td.as_unit("ns").is_ok());
assert!(td.as_unit("ms").is_err());
}
#[test]
fn datetime_timedelta_unit_resolution_match_pandas_c50rv() {
let dt = super::DatetimeIndex::new(vec![]);
assert_eq!(dt.unit(), "ns");
assert_eq!(dt.resolution(), "nanosecond");
let td = super::TimedeltaIndex::new(vec![]);
assert_eq!(td.unit(), "ns");
assert_eq!(td.resolution(), "nanosecond");
}
#[test]
fn datetime_timedelta_tz_freq_accessors_return_none_ze7et() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS]);
assert_eq!(dt.tz(), None);
assert_eq!(dt.tzinfo(), None);
assert_eq!(dt.freq(), None);
assert_eq!(dt.freqstr(), None);
assert_eq!(dt.inferred_freq(), None);
let td = super::TimedeltaIndex::new(vec![100_i64]);
assert_eq!(td.freq(), None);
assert_eq!(td.freqstr(), None);
assert_eq!(td.inferred_freq(), None);
}
#[test]
fn period_index_freqstr_inferred_freq_match_pandas_ze7et() {
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![
Period::new(10, PeriodFreq::Monthly),
Period::new(11, PeriodFreq::Monthly),
]);
let s = pi.freqstr().expect("homogeneous index has a freqstr");
assert!(!s.is_empty());
let inferred = pi.inferred_freq().expect("homogeneous freq is inferable");
assert_eq!(inferred, s);
// Mixed-frequency index: inferred_freq returns None.
let mixed = super::PeriodIndex::new(vec![
Period::new(10, PeriodFreq::Monthly),
Period::new(10, PeriodFreq::ANNUAL),
]);
assert_eq!(mixed.inferred_freq(), None);
// Empty index: freqstr is None.
let empty = super::PeriodIndex::new(Vec::new());
assert_eq!(empty.freqstr(), None);
assert_eq!(empty.inferred_freq(), None);
}
#[test]
fn range_index_where_putmask_match_pandas_jw1kw() -> Result<(), super::IndexError> {
let r = super::RangeIndex::new(0, 5, 1).unwrap().set_name("r");
let masked = r.r#where(&[true, false, true, false, true], 99)?;
assert_eq!(int64_labels(&masked), vec![0, 99, 2, 99, 4]);
assert_eq!(masked.name().map(|n| n.as_str()), Some("r"));
let put = r.putmask(&[false, true, false, true, false], 99)?;
assert_eq!(int64_labels(&put), vec![0, 99, 2, 99, 4]);
// Length mismatch.
assert!(matches!(
r.r#where(&[true, false], 0).unwrap_err(),
super::IndexError::LengthMismatch { .. }
));
assert!(matches!(
r.putmask(&[true; 7], 0).unwrap_err(),
super::IndexError::LengthMismatch { .. }
));
Ok(())
}
#[test]
fn range_index_set_ops_match_pandas_tz40f() {
let left = super::RangeIndex::new(0, 5, 1).unwrap().set_name("r");
let right = super::RangeIndex::new(3, 8, 1).unwrap().set_name("r");
let inter = left.intersection(&right);
assert_eq!(int64_labels(&inter), vec![3, 4]);
assert_eq!(inter.name().map(|n| n.as_str()), Some("r"));
let union = left.union(&right);
assert_eq!(int64_labels(&union), vec![0, 1, 2, 3, 4, 5, 6, 7]);
let diff = left.difference(&right);
assert_eq!(int64_labels(&diff), vec![0, 1, 2]);
let sym = left.symmetric_difference(&right);
assert_eq!(int64_labels(&sym), vec![0, 1, 2, 5, 6, 7]);
// Mismatched names drop the name.
let other_name = super::RangeIndex::new(3, 6, 1).unwrap().set_name("other");
assert_eq!(left.union(&other_name).name(), None);
}
#[test]
fn period_range_slice_indexer_match_pandas_18kvv() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![
Period::new(10, PeriodFreq::Monthly),
Period::new(11, PeriodFreq::Monthly),
Period::new(12, PeriodFreq::Monthly),
]);
assert_eq!(
pi.slice_indexer(
Period::new(11, PeriodFreq::Monthly),
Period::new(12, PeriodFreq::Monthly)
)?,
1..3
);
let r = super::RangeIndex::new(0, 10, 2).unwrap();
assert_eq!(r.slice_indexer(2, 6)?, 1..4);
Ok(())
}
#[test]
fn period_range_slice_locs_match_pandas_fdga0() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let p4 = Period::new(13, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p2, p3, p4]);
assert_eq!(pi.slice_locs(p2, p3)?, (1, 3));
assert_eq!(pi.slice_locs(p1, p4)?, (0, 4));
// Non-monotonic rejects.
let unsorted = super::PeriodIndex::new(vec![p3, p1, p2]);
assert!(unsorted.slice_locs(p1, p3).is_err());
let r = super::RangeIndex::new(0, 10, 2).unwrap();
// Values 0,2,4,6,8.
assert_eq!(r.slice_locs(2, 6)?, (1, 4));
assert_eq!(r.slice_locs(0, 8)?, (0, 5));
// Descending rejects.
let desc = super::RangeIndex::new(10, 0, -2).unwrap();
assert!(desc.slice_locs(2, 6).is_err());
Ok(())
}
#[test]
fn typed_index_variants_rename_alias_match_pandas_i8t6n() {
let dt = super::DatetimeIndex::new(vec![]);
assert_eq!(dt.rename("ts").name().map(|n| n.as_str()), Some("ts"));
let td = super::TimedeltaIndex::new(vec![]);
assert_eq!(td.rename("d").name().map(|n| n.as_str()), Some("d"));
use fp_types::PeriodFreq;
let pi = super::PeriodIndex::new(vec![]);
assert_eq!(pi.rename("p").name().map(|n| n.as_str()), Some("p"));
let _ = PeriodFreq::Monthly; // suppress unused-import warning when no other test in scope
let r = super::RangeIndex::new(0, 0, 1).unwrap();
assert_eq!(r.rename("r").name().map(|n| n.as_str()), Some("r"));
let cat = super::CategoricalIndex::from_values(vec!["a".to_owned()], false);
assert_eq!(cat.rename("c").name().map(|n| n.as_str()), Some("c"));
}
#[test]
fn typed_index_variants_reindex_match_pandas_qm3nq() {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, b]);
let target = super::DatetimeIndex::new(vec![b, a, 0]);
let (out, indexer) = dt.reindex(&target);
assert_eq!(out.values(), target.values());
assert_eq!(indexer, vec![1, 0, -1]);
let td = super::TimedeltaIndex::new(vec![100_i64, 200]);
let td_target = super::TimedeltaIndex::new(vec![200_i64, 999]);
let (_, td_indexer) = td.reindex(&td_target);
assert_eq!(td_indexer, vec![1, -1]);
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p2]);
let pi_target = super::PeriodIndex::new(vec![p2, Period::new(99, PeriodFreq::Monthly)]);
let (_, pi_indexer) = pi.reindex(&pi_target);
assert_eq!(pi_indexer, vec![1, -1]);
let r = super::RangeIndex::new(0, 5, 1).unwrap();
let r_target = super::RangeIndex::new(2, 6, 1).unwrap();
let (_, r_indexer) = r.reindex(&r_target);
assert_eq!(r_indexer, vec![2, 3, 4, -1]);
let descending_target = super::RangeIndex::new(6, -3, -3)
.unwrap()
.set_name("target");
let (reindexed, descending_indexer) = r.reindex(&descending_target);
assert!(reindexed.identical(&descending_target));
assert_eq!(descending_indexer, vec![-1, 3, 0]);
}
#[test]
fn period_range_categorical_get_indexer_non_unique_match_pandas_z9sna()
-> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
// PeriodIndex with duplicate p1.
let pi = super::PeriodIndex::new(vec![p1, p2, p1]);
let (positions, missing) =
pi.get_indexer_non_unique(&[p1, Period::new(99, PeriodFreq::Monthly)]);
assert_eq!(positions, vec![0, 2, -1]);
assert_eq!(missing, vec![1]);
// RangeIndex (always unique).
let r = super::RangeIndex::new(0, 5, 1).unwrap();
let (positions, missing) = r.get_indexer_non_unique(&[2, 99]);
assert_eq!(positions, vec![2, -1]);
assert_eq!(missing, vec![1]);
// CategoricalIndex with duplicate "a".
let cat = super::CategoricalIndex::from_values(
vec!["a".to_owned(), "b".to_owned(), "a".to_owned()],
false,
);
let (positions, missing) =
cat.get_indexer_non_unique(&[IndexLabel::from("a"), IndexLabel::from("z")]);
assert_eq!(positions, vec![0, 2, -1]);
assert_eq!(missing, vec![1]);
// Categorical get_indexer also works.
let mapped = cat.get_indexer(&[IndexLabel::from("b"), IndexLabel::from("z")]);
assert_eq!(mapped, vec![1, -1]);
// get_indexer_for is an alias.
assert_eq!(
cat.get_indexer_for(&[IndexLabel::from("a")]),
cat.get_indexer(&[IndexLabel::from("a")])
);
Ok(())
}
#[test]
fn typed_index_variants_get_indexer_for_aliases_match_pandas_lf1jy()
-> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS]);
assert_eq!(
dt.get_indexer_for(&[1_704_067_200_i64 * NS, 0]),
dt.get_indexer(&[1_704_067_200_i64 * NS, 0])
);
let td = super::TimedeltaIndex::new(vec![100_i64, 200]);
assert_eq!(td.get_indexer_for(&[200, 999]), td.get_indexer(&[200, 999]));
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![Period::new(10, PeriodFreq::Monthly)]);
let target = vec![Period::new(10, PeriodFreq::Monthly)];
assert_eq!(pi.get_indexer_for(&target), pi.get_indexer(&target));
let r = super::RangeIndex::new(0, 5, 1).unwrap();
assert_eq!(r.get_indexer_for(&[2, 99]), r.get_indexer(&[2, 99]));
Ok(())
}
#[test]
fn period_range_get_loc_get_indexer_match_pandas_e7psu() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p2, p3]);
assert_eq!(pi.get_loc(p2)?, 1);
assert!(pi.get_loc(Period::new(99, PeriodFreq::Monthly)).is_err());
assert_eq!(
pi.get_indexer(&[p3, p1, Period::new(99, PeriodFreq::Monthly)]),
vec![2, 0, -1]
);
// RangeIndex with step=2: 0, 2, 4, 6, 8.
let r = super::RangeIndex::new(0, 10, 2).unwrap();
assert_eq!(r.get_loc(0)?, 0);
assert_eq!(r.get_loc(8)?, 4);
assert!(r.get_loc(7).is_err()); // not in step
assert!(r.get_loc(99).is_err()); // out of range
assert_eq!(r.get_indexer(&[4, 7, 0, 99]), vec![2, -1, 0, -1]);
// Negative step: 10, 8, 6, 4, 2.
let desc = super::RangeIndex::new(10, 0, -2).unwrap();
assert_eq!(desc.get_loc(10)?, 0);
assert_eq!(desc.get_loc(2)?, 4);
assert!(desc.get_loc(7).is_err());
Ok(())
}
#[test]
fn range_index_vectorized_indexers_match_get_loc_29u49() {
let source = super::RangeIndex::new(10, 0, -2).unwrap();
let targets = [10, 7, 2, 0, 6];
assert_eq!(source.get_indexer(&targets), vec![0, -1, 4, -1, 2]);
let (positions, missing) = source.get_indexer_non_unique(&targets);
assert_eq!(positions, vec![0, -1, 4, -1, 2]);
assert_eq!(missing, vec![1, 3]);
let target_index = super::RangeIndex::new(12, -2, -4).unwrap();
let (reindexed, indexer) = source.reindex(&target_index);
assert!(reindexed.identical(&target_index));
assert_eq!(indexer, vec![-1, 1, 3, -1]);
let missing_error = source.get_loc(7).unwrap_err();
assert!(matches!(
missing_error,
super::IndexError::InvalidArgument(ref msg)
if msg == "get_loc: 7 not in RangeIndex"
));
}
#[test]
fn range_index_reindex_uses_arithmetic_lattice_fast_path_codb159() {
let source = super::RangeIndex::new(0, 10, 2).unwrap();
let all_miss_target = super::RangeIndex::new(1, 11, 2).unwrap();
let (reindexed, indexer) = source.reindex(&all_miss_target);
assert!(reindexed.identical(&all_miss_target));
assert_eq!(indexer, vec![-1, -1, -1, -1, -1]);
let aligned_target = super::RangeIndex::new(4, 12, 2).unwrap();
let (reindexed, indexer) = source.reindex(&aligned_target);
assert!(reindexed.identical(&aligned_target));
assert_eq!(indexer, vec![2, 3, 4, -1]);
let descending_source = super::RangeIndex::new(10, 0, -2).unwrap();
let descending_target = super::RangeIndex::new(8, -4, -4).unwrap();
let (reindexed, indexer) = descending_source.reindex(&descending_target);
assert!(reindexed.identical(&descending_target));
assert_eq!(indexer, vec![1, 3, -1]);
let partial_lattice_target = super::RangeIndex::new(0, 10, 2).unwrap();
let wide_step_source = super::RangeIndex::new(0, 12, 4).unwrap();
let (reindexed, indexer) = wide_step_source.reindex(&partial_lattice_target);
assert!(reindexed.identical(&partial_lattice_target));
assert_eq!(indexer, vec![0, -1, 1, -1, 2]);
}
#[test]
fn range_index_bulk_indexers_reuse_source_len_without_extreme_overflow_codb159() {
let source = super::RangeIndex::new(i64::MIN, i64::MIN + 10, 2).unwrap();
assert_eq!(
source.get_indexer(&[i64::MIN, i64::MIN + 8, i64::MAX]),
vec![0, 4, -1]
);
let (positions, missing) =
source.get_indexer_non_unique(&[i64::MIN, i64::MIN + 1, i64::MIN + 8, i64::MAX]);
assert_eq!(positions, vec![0, -1, 4, -1]);
assert_eq!(missing, vec![1, 3]);
}
#[test]
fn range_index_get_loc_uses_wide_arithmetic_uza04172() -> Result<(), super::IndexError> {
let asc = super::RangeIndex::new(i64::MIN, i64::MIN + 10, 2).unwrap();
assert_eq!(asc.get_loc(i64::MIN)?, 0);
assert_eq!(asc.get_loc(i64::MIN + 8)?, 4);
let asc_missing = asc.get_loc(i64::MAX).unwrap_err();
assert!(matches!(
asc_missing,
super::IndexError::InvalidArgument(ref msg)
if msg == &format!("get_loc: {} not in RangeIndex", i64::MAX)
));
let desc = super::RangeIndex::new(i64::MAX, i64::MAX - 10, -2).unwrap();
assert_eq!(desc.get_loc(i64::MAX)?, 0);
assert_eq!(desc.get_loc(i64::MAX - 8)?, 4);
let desc_missing = desc.get_loc(i64::MIN).unwrap_err();
assert!(matches!(
desc_missing,
super::IndexError::InvalidArgument(ref msg)
if msg == &format!("get_loc: {} not in RangeIndex", i64::MIN)
));
Ok(())
}
#[test]
fn period_index_where_putmask_match_pandas_so9oh() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p2, p3]).set_name("p");
// where: keep position 0 and 2.
let masked = pi.r#where(&[true, false, true], p1)?;
assert_eq!(masked.values(), &[p1, p1, p3]);
assert_eq!(masked.name().map(|n| n.as_str()), Some("p"));
// putmask: replace masked positions.
let put = pi.putmask(&[false, true, false], p1)?;
assert_eq!(put.values(), &[p1, p1, p3]);
// Length mismatch.
let bad_len = pi.r#where(&[true, false], p1).unwrap_err();
assert!(matches!(bad_len, super::IndexError::LengthMismatch { .. }));
// Mismatched freq replacement rejects.
let mismatch = Period::new(10, PeriodFreq::ANNUAL);
assert!(pi.r#where(&[true, false, true], mismatch).is_err());
assert!(pi.putmask(&[false, true, false], mismatch).is_err());
Ok(())
}
#[test]
fn categorical_index_where_putmask_match_pandas_so9oh() -> Result<(), super::IndexError> {
let cat = super::CategoricalIndex::with_categories(
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
vec![
"a".to_owned(),
"b".to_owned(),
"c".to_owned(),
"d".to_owned(),
],
false,
)?;
let masked = cat.r#where(&[true, false, true], &IndexLabel::from("d"))?;
assert_eq!(
masked.labels(),
vec![
IndexLabel::from("a"),
IndexLabel::from("d"),
IndexLabel::from("c")
]
.as_slice()
);
let put = cat.putmask(&[false, true, true], &IndexLabel::from("d"))?;
assert_eq!(
put.labels(),
vec![
IndexLabel::from("a"),
IndexLabel::from("d"),
IndexLabel::from("d")
]
.as_slice()
);
// Replacement that's not a category rejects.
assert!(
cat.r#where(&[true, false, true], &IndexLabel::from("zzz"))
.is_err()
);
// Length mismatch.
assert!(cat.putmask(&[true; 5], &IndexLabel::from("a")).is_err());
Ok(())
}
#[test]
fn period_index_set_ops_match_pandas_8042v() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let p4 = Period::new(13, PeriodFreq::Monthly);
let left = super::PeriodIndex::new(vec![p1, p2, p3]).set_name("p");
let right = super::PeriodIndex::new(vec![p2, p3, p4]).set_name("p");
assert_eq!(left.intersection(&right)?.values(), &[p2, p3]);
assert_eq!(left.union(&right)?.values(), &[p1, p2, p3, p4]);
assert_eq!(left.difference(&right)?.values(), &[p1]);
assert_eq!(left.symmetric_difference(&right)?.values(), &[p1, p4]);
// Mismatched freq rejects.
let mismatch = super::PeriodIndex::new(vec![Period::new(10, PeriodFreq::ANNUAL)]);
assert!(left.intersection(&mismatch).is_err());
assert!(left.union(&mismatch).is_err());
assert!(left.difference(&mismatch).is_err());
assert!(left.symmetric_difference(&mismatch).is_err());
// Mismatched names drop the name.
let other_name = super::PeriodIndex::new(vec![p2]).set_name("other");
assert_eq!(left.union(&other_name)?.name(), None);
Ok(())
}
#[test]
fn period_categorical_sort_values_match_pandas_482qd() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p3, p1, p2]).set_name("p");
let sorted = pi.sort_values()?;
let sorted_alias = pi.sort()?;
assert_eq!(sorted.values(), &[p1, p2, p3]);
assert_eq!(sorted_alias.values(), sorted.values());
assert_eq!(sorted.name().map(|n| n.as_str()), Some("p"));
assert_eq!(sorted_alias.name().map(|n| n.as_str()), Some("p"));
let mixed = super::PeriodIndex::new(vec![
Period::new(10, PeriodFreq::Monthly),
Period::new(10, PeriodFreq::ANNUAL),
]);
assert!(mixed.sort_values().is_err());
assert!(mixed.sort().is_err());
// CategoricalIndex with ordered=true uses category position.
let cat = super::CategoricalIndex::with_categories(
vec![
"b".to_owned(),
"a".to_owned(),
"c".to_owned(),
"a".to_owned(),
],
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
true,
)?;
let cat_sorted = cat.sort_values();
let cat_sorted_alias = cat.sort();
assert_eq!(
cat_sorted.labels(),
vec![
IndexLabel::from("a"),
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("c")
]
.as_slice()
);
assert_eq!(cat_sorted_alias.labels(), cat_sorted.labels());
Ok(())
}
#[test]
fn categorical_sort_values_by_category_code_not_lexicographic() {
// Non-lexicographic category order: codes b=0, a=1, c=2. pandas
// sort_values orders by code -> b, a, a, c (NOT lexicographic a,a,b,c).
// The old `to_index().argsort()` text sort returned a,a,b,c, which
// diverges from pandas; the existing 482qd test used lexicographic
// categories so it could not catch this.
let cat = super::CategoricalIndex::with_categories(
vec![
"a".to_owned(),
"c".to_owned(),
"b".to_owned(),
"a".to_owned(),
],
vec!["b".to_owned(), "a".to_owned(), "c".to_owned()],
true,
)
.unwrap();
// labels [a,c,b,a] -> codes [1,2,0,1]; stable argsort by code:
// code0 -> pos2 (b); code1 -> pos0 (a), pos3 (a); code2 -> pos1 (c).
assert_eq!(cat.argsort(), vec![2, 0, 3, 1]);
assert_eq!(
cat.sort_values().labels(),
[
IndexLabel::from("b"),
IndexLabel::from("a"),
IndexLabel::from("a"),
IndexLabel::from("c")
]
.as_slice()
);
// Unordered categoricals also sort by category code in pandas.
let cat_u = super::CategoricalIndex::with_categories(
vec!["a".to_owned(), "b".to_owned()],
vec!["b".to_owned(), "a".to_owned()],
false,
)
.unwrap();
// codes a=1, b=0 -> sorted by code: b, a.
assert_eq!(
cat_u.sort_values().labels(),
[IndexLabel::from("b"), IndexLabel::from("a")].as_slice()
);
}
#[test]
fn period_index_from_ordinals_match_pandas_baenb() {
use fp_types::PeriodFreq;
let pi = super::PeriodIndex::from_ordinals(&[10, 11, 12], PeriodFreq::Monthly);
assert_eq!(pi.values().len(), 3);
assert_eq!(pi.values()[0].ordinal, 10);
assert_eq!(pi.values()[2].ordinal, 12);
assert_eq!(pi.asi8(), vec![10, 11, 12]);
for period in pi.values() {
assert_eq!(period.freq, PeriodFreq::Monthly);
}
let empty = super::PeriodIndex::from_ordinals(&[], PeriodFreq::ANNUAL);
assert!(empty.is_empty());
assert!(empty.asi8().is_empty());
}
#[test]
fn period_fields_read_the_end_date_and_nat_is_missing() -> Result<(), super::IndexError> {
use fp_types::PeriodFreq;
// pd.PeriodIndex(['2024-01', NaT, '2023-02'], freq='M'): a month's
// day is its last; a NaT period's fields are missing (the binding's
// -1), its boundaries NaT, its asfreq NaT.
let months = super::PeriodIndex::from_ordinals(&[648, i64::MIN, 637], PeriodFreq::Monthly);
assert_eq!(months.day()?, vec![Some(31), None, Some(28)]);
assert_eq!(months.dayofyear()?, vec![Some(31), None, Some(59)]);
assert_eq!(months.week()?, vec![Some(5), None, Some(9)]);
assert_eq!(months.qyear()?, vec![2024, -1, 2023]);
assert_eq!(
months.start_time()?.as_index().labels()[1],
super::IndexLabel::Datetime64(i64::MIN)
);
let days = months.asfreq("D")?;
assert_eq!(days.values()[1].ordinal, i64::MIN);
assert_eq!(days.values()[1].freq, PeriodFreq::Daily);
// A quarter's month is its third; an hour's hour is itself.
let quarters = super::PeriodIndex::from_ordinals(&[216], PeriodFreq::QUARTERLY);
assert_eq!(quarters.month()?, vec![Some(3)]);
let hours = super::PeriodIndex::from_ordinals(&[473_374], PeriodFreq::Hourly);
assert_eq!(hours.hour()?, vec![Some(22)]);
// NEGATIVE: a month's year and month are those of its start too.
assert_eq!(months.year()?, vec![Some(2024), None, Some(2023)]);
assert_eq!(months.month()?, vec![Some(1), None, Some(2)]);
Ok(())
}
/// Anchored frequencies on pandas' fiscal axes, live pandas 2.2.3:
/// 2024-03-01 is Y-JUN '2024' (ordinal 54, from 2023-07-01), Q-JAN
/// '2025Q1' (220, from 2024-02-01; quarter 1, qyear 2025, year 2024),
/// Q-NOV '2024Q2' (217), W-MON ordinal 2827 from 2024-02-27, W-SAT 2826
/// from 2024-02-25; 1969-12-31 at Q-JAN is 1970Q4 (3)
/// (br-frankenpandas-39h5n).
#[test]
fn anchored_periods_follow_the_fiscal_calendar_39h5n() -> Result<(), super::IndexError> {
use fp_types::PeriodFreq;
const DAY: i64 = 86_400_000_000_000;
let march_first = 19_783 * DAY;
let cases = [
(PeriodFreq::Annual(6), 54, 19_539),
(PeriodFreq::Quarterly(1), 220, 19_754),
(PeriodFreq::Quarterly(11), 217, 19_783),
(PeriodFreq::Weekly(0), 2827, 19_780),
(PeriodFreq::Weekly(5), 2826, 19_778),
(PeriodFreq::QUARTERLY, 216, 19_723),
];
for (freq, ordinal, start_day) in cases {
let period = super::datetime_nanos_to_period(march_first, freq)?;
assert_eq!(period.ordinal, ordinal, "{freq:?}");
assert_eq!(
super::period_start_nanos(period)?,
start_day * DAY,
"{freq:?}"
);
}
let pre_epoch = super::datetime_nanos_to_period(-DAY, PeriodFreq::Quarterly(1))?;
assert_eq!(pre_epoch.ordinal, 3);
let quarters =
super::PeriodIndex::from_ordinals(&[220, i64::MIN], PeriodFreq::Quarterly(1));
assert_eq!(quarters.quarter()?, vec![Some(1), None]);
assert_eq!(quarters.qyear()?, vec![2025, -1]);
assert_eq!(quarters.year()?, vec![Some(2024), None]);
assert_eq!(quarters.month()?, vec![Some(4), None]);
// NEGATIVE: a fiscal year's quarter is its end date's calendar one.
let years = super::PeriodIndex::from_ordinals(&[54], PeriodFreq::Annual(6));
assert_eq!(years.quarter()?, vec![Some(2)]);
Ok(())
}
#[test]
fn period_index_astype_datetime_and_int_match_pandas() -> Result<(), super::IndexError> {
use fp_types::PeriodFreq;
let pi = super::PeriodIndex::from_ordinals(&[600, 601], PeriodFreq::Monthly).set_name("p");
let as_int = pi.astype("int64")?;
assert_eq!(
as_int.labels(),
&[IndexLabel::Int64(600), IndexLabel::Int64(601)]
);
assert_eq!(as_int.name().map(|n| n.as_str()), Some("p"));
let as_datetime = pi.astype("datetime64[ns]")?;
assert_eq!(
as_datetime.labels(),
&[
IndexLabel::Datetime64(1_577_836_800_000_000_000),
IndexLabel::Datetime64(1_580_515_200_000_000_000),
]
);
assert_eq!(as_datetime.name().map(|n| n.as_str()), Some("p"));
Ok(())
}
#[test]
fn period_index_missing_value_accessors_are_all_present() {
use fp_types::PeriodFreq;
let pi = super::PeriodIndex::from_ordinals(&[10, 11, 12], PeriodFreq::Monthly)
.set_name("periods");
assert!(!pi.hasnans());
assert_eq!(pi.isna(), vec![false, false, false]);
assert_eq!(pi.isnull(), pi.isna());
assert_eq!(pi.notna(), vec![true, true, true]);
assert_eq!(pi.notnull(), pi.notna());
let dropped = pi.dropna();
assert_eq!(dropped.values(), pi.values());
assert_eq!(dropped.name().map(|n| n.as_str()), Some("periods"));
}
#[test]
fn period_index_mean_median_match_pandas_3rsrc() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(20, PeriodFreq::Monthly);
let p3 = Period::new(30, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p2, p3]);
assert_eq!(pi.mean()?.unwrap().ordinal, 20);
assert_eq!(pi.median()?.unwrap().ordinal, 20);
let empty = super::PeriodIndex::new(Vec::new());
assert_eq!(empty.mean()?, None);
assert_eq!(empty.median()?, None);
let mixed = super::PeriodIndex::new(vec![p1, Period::new(10, PeriodFreq::ANNUAL)]);
assert!(mixed.mean().is_err());
assert!(mixed.median().is_err());
Ok(())
}
#[test]
fn period_index_argmax_argmin_argsort_match_pandas_qg8u5() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p2, p3, p1]);
assert_eq!(pi.argmax()?, 1);
assert_eq!(pi.argmin()?, 2);
assert_eq!(pi.argsort()?, vec![2, 0, 1]);
let empty = super::PeriodIndex::new(Vec::new());
assert!(empty.argmax().is_err());
assert!(empty.argmin().is_err());
assert!(empty.argsort()?.is_empty());
let mixed = super::PeriodIndex::new(vec![p1, Period::new(10, PeriodFreq::ANNUAL)]);
assert!(mixed.argmax().is_err());
assert!(mixed.argsort().is_err());
Ok(())
}
#[test]
fn period_index_shift_match_pandas_pnaui() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p2]).set_name("p");
let shifted = pi.shift(2)?;
assert_eq!(shifted.values()[0].ordinal, 12);
assert_eq!(shifted.values()[1].ordinal, 13);
assert_eq!(shifted.name().map(|n| n.as_str()), Some("p"));
// Negative shift.
let back = pi.shift(-1)?;
assert_eq!(back.values()[0].ordinal, 9);
// Mixed-freq rejects.
let mixed = super::PeriodIndex::new(vec![p1, Period::new(10, PeriodFreq::ANNUAL)]);
assert!(mixed.shift(1).is_err());
Ok(())
}
#[test]
fn period_index_is_full_match_pandas_7i32m() {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let p5 = Period::new(14, PeriodFreq::Monthly);
// Contiguous.
let full = super::PeriodIndex::new(vec![p1, p2, p3]);
assert!(full.is_full());
// Out-of-order but contiguous (sort first).
let unsorted = super::PeriodIndex::new(vec![p3, p1, p2]);
assert!(unsorted.is_full());
// Gap.
let gap = super::PeriodIndex::new(vec![p1, p2, p5]);
assert!(!gap.is_full());
// Empty / single-element.
assert!(super::PeriodIndex::new(Vec::new()).is_full());
assert!(super::PeriodIndex::new(vec![p1]).is_full());
// Mixed-frequency.
let mixed = super::PeriodIndex::new(vec![p1, Period::new(10, PeriodFreq::ANNUAL)]);
assert!(!mixed.is_full());
}
#[test]
fn period_index_min_max_match_pandas_fwlv4() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p3, p1, p2]);
assert_eq!(pi.min()?, Some(p1));
assert_eq!(pi.max()?, Some(p3));
let empty = super::PeriodIndex::new(Vec::new());
assert_eq!(empty.min()?, None);
assert_eq!(empty.max()?, None);
// Mixed freq rejects.
let mixed = super::PeriodIndex::new(vec![
Period::new(10, PeriodFreq::Monthly),
Period::new(10, PeriodFreq::ANNUAL),
]);
assert!(mixed.min().is_err());
assert!(mixed.max().is_err());
Ok(())
}
#[test]
fn range_index_sort_values_closed_form_mhcge() {
let asc = super::RangeIndex::new(0, 5, 1).unwrap();
assert!(asc.sort_values().equals(&asc));
assert!(asc.sort().equals(&asc));
let desc = super::RangeIndex::new(10, 0, -2).unwrap();
// Original values 10, 8, 6, 4, 2 → sorted ascending 2, 4, 6, 8, 10.
let sorted = desc.sort_values();
let sorted_alias = desc.sort();
assert_eq!(sorted.values().to_vec(), vec![2, 4, 6, 8, 10]);
assert_eq!(sorted_alias.values().to_vec(), sorted.values().to_vec());
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert!(empty.sort_values().is_empty());
assert!(empty.sort().is_empty());
let zero_step = super::RangeIndex::new(0, 5, 1).unwrap();
assert!(zero_step.sort_values().equals(&zero_step));
assert!(zero_step.sort().equals(&zero_step));
}
#[test]
fn range_index_sort_values_keeps_singleton_min_step_uza04177() {
let singleton = super::RangeIndex::new(0, i64::MIN, i64::MIN)
.unwrap()
.set_name("row");
assert_eq!(singleton.len(), 1);
assert_eq!(singleton.sort_values(), singleton);
}
#[test]
fn range_index_descending_ops_match_pandas_dustysummit() {
use super::RangeIndex;
// Regression coverage for descending-range handling — the exact smell
// that was buggy in the set operations. All expected values verified
// against pandas 2.2.3 (R(10,0,-2) = [10,8,6,4,2]).
let vals = |idx: &super::Index| -> Vec<i64> {
idx.labels()
.iter()
.filter_map(|l| match l {
super::IndexLabel::Int64(v) => Some(*v),
_ => None,
})
.collect()
};
let desc = RangeIndex::new(10, 0, -2).unwrap();
let asc = RangeIndex::new(0, 10, 2).unwrap();
// argsort: the permutation that sorts values ascending.
assert_eq!(desc.argsort(), vec![4, 3, 2, 1, 0]);
assert_eq!(asc.argsort(), vec![0, 1, 2, 3, 4]);
// sort_values: ascending (descending rebuilds an ascending range).
assert_eq!(
vals(&desc.sort_values().to_flat_index()),
vec![2, 4, 6, 8, 10]
);
assert_eq!(
vals(&asc.sort_values().to_flat_index()),
vec![0, 2, 4, 6, 8]
);
// factorize: identity codes; uniques preserve the (descending) order.
let (codes, uniques) = desc.factorize();
assert_eq!(codes, vec![0, 1, 2, 3, 4]);
assert_eq!(vals(&uniques.to_flat_index()), vec![10, 8, 6, 4, 2]);
// take / repeat: order-preserving over the descending values.
assert_eq!(vals(&desc.take(&[0, 2, 4]).unwrap()), vec![10, 6, 2]);
assert_eq!(vals(&desc.repeat(2)), vec![10, 10, 8, 8, 6, 6, 4, 4, 2, 2]);
// where keeps the value where cond is TRUE (replaces where false);
// putmask replaces where the mask is TRUE — opposite conventions.
let m = [true, false, true, false, true];
assert_eq!(vals(&desc.r#where(&m, 99).unwrap()), vec![10, 99, 6, 99, 2]);
assert_eq!(vals(&desc.putmask(&m, 99).unwrap()), vec![99, 8, 99, 4, 99]);
}
#[test]
fn test_range_index_extended_parity_methods() {
let r = RangeIndex::from_range(2, 10, 2).unwrap();
assert_eq!(r.len(), 4);
assert!(r.contains(2));
assert!(r.contains(4));
assert!(r.contains(6));
assert!(r.contains(8));
assert!(!r.contains(0));
assert!(!r.contains(10));
assert!(!r.contains(3));
assert_eq!(r.get_slice_bound(4, "left").unwrap(), 1);
assert_eq!(r.get_slice_bound(4, "right").unwrap(), 2);
assert!(r.all());
assert!(r.any());
assert_eq!(r.argmax().unwrap(), 3);
assert_eq!(r.argmin().unwrap(), 0);
assert_eq!(r.argsort(), vec![0, 1, 2, 3]);
assert!(!r.hasnans());
assert_eq!(r.nlevels(), 1);
assert_eq!(r.isna(), vec![false, false, false, false]);
assert_eq!(r.isnull(), vec![false, false, false, false]);
assert_eq!(r.notna(), vec![true, true, true, true]);
assert_eq!(r.notnull(), vec![true, true, true, true]);
assert_eq!(r.unique(), r);
assert_eq!(r.drop_duplicates(), r);
assert_eq!(
r.duplicated(DuplicateKeep::First),
vec![false, false, false, false]
);
// Range containing 0
let r_with_zero = RangeIndex::new(0, 5, 1).unwrap();
assert!(!r_with_zero.all());
assert!(r_with_zero.any());
// Empty range
let r_empty = RangeIndex::new(0, 0, 1).unwrap();
assert!(r_empty.all());
assert!(!r_empty.any());
assert!(r_empty.argmax().is_err());
assert!(r_empty.argmin().is_err());
assert!(r_empty.argsort().is_empty());
assert!(!r_empty.contains(0));
// Descending range
let r_desc = RangeIndex::new(10, 0, -2).unwrap();
assert_eq!(r_desc.argmax().unwrap(), 0);
assert_eq!(r_desc.argmin().unwrap(), 4);
assert_eq!(r_desc.argsort(), vec![4, 3, 2, 1, 0]);
assert!(r_desc.all());
assert!(r_desc.any());
}
#[test]
#[allow(clippy::type_complexity)]
fn range_index_set_ops_match_pandas_2_2_3_differential_dustysummit() {
use super::RangeIndex;
// Data-driven differential vs pandas 2.2.3 for all four set operations.
// intersection uses sort=False (result ascending EXCEPT both operands
// descending -> descending); union/difference/symmetric_difference use
// sort=None (ascending EXCEPT empty-operand or value-equal passthrough).
// Cases cover descending operands, non-aligned step lattices, empty
// operands, value-equal operands, disjoint / overlapping / subset
// overlaps. Expected values were computed by real pandas; see
// testdata_rangeset_pandas_cases.rs.
let cases: &[(
(i64, i64, i64),
(i64, i64, i64),
&[i64],
&[i64],
&[i64],
&[i64],
)] = &include!("testdata_rangeset_pandas_cases.rs");
let vals = |idx: &super::Index| -> Vec<i64> {
idx.labels()
.iter()
.filter_map(|l| match l {
super::IndexLabel::Int64(v) => Some(*v),
_ => None,
})
.collect()
};
let r = |(s, e, st): (i64, i64, i64)| RangeIndex::new(s, e, st).unwrap();
let mut fails: Vec<String> = Vec::new();
for (i, (a, b, want_i, want_u, want_d, want_s)) in cases.iter().enumerate() {
let (ra, rb) = (r(*a), r(*b));
let got_i = vals(&ra.intersection(&rb));
let got_u = vals(&ra.union(&rb));
let got_d = vals(&ra.difference(&rb));
let got_s = vals(&ra.symmetric_difference(&rb));
if got_i != *want_i {
fails.push(format!(
"#{i} inter {a:?}∩{b:?}: got {got_i:?} want {want_i:?}"
));
}
if got_u != *want_u {
fails.push(format!(
"#{i} union {a:?}∪{b:?}: got {got_u:?} want {want_u:?}"
));
}
if got_d != *want_d {
fails.push(format!(
"#{i} diff {a:?}∖{b:?}: got {got_d:?} want {want_d:?}"
));
}
if got_s != *want_s {
fails.push(format!(
"#{i} symm {a:?}∆{b:?}: got {got_s:?} want {want_s:?}"
));
}
}
assert!(
fails.is_empty(),
"{} RangeIndex set-op divergences from pandas 2.2.3:\n{}",
fails.len(),
fails.join("\n")
);
}
#[test]
fn range_index_reduction_edge_cases_match_pandas_dustysummit() {
use super::RangeIndex;
// Empty range: min/max/median None; argmin/argmax error; both
// monotonicity predicates True (an empty index is monotonic in pandas);
// nunique 0.
let empty = RangeIndex::new(5, 5, 1).unwrap();
assert_eq!(empty.len(), 0);
assert_eq!(empty.min(), None);
assert_eq!(empty.max(), None);
assert_eq!(empty.median(), None);
assert!(empty.argmin().is_err());
assert!(empty.argmax().is_err());
assert!(empty.is_monotonic_increasing());
assert!(empty.is_monotonic_decreasing());
assert_eq!(empty.nunique(), 0);
// Single element: min == max; median == the value; argmin == argmax == 0;
// monotonic both ways.
let single = RangeIndex::new(7, 8, 1).unwrap();
assert_eq!(single.len(), 1);
assert_eq!(single.min(), Some(7));
assert_eq!(single.max(), Some(7));
assert_eq!(single.median(), Some(7.0));
assert_eq!(single.argmin().unwrap(), 0);
assert_eq!(single.argmax().unwrap(), 0);
assert!(single.is_monotonic_increasing());
assert!(single.is_monotonic_decreasing());
// Descending (odd length): [10,8,6,4,2]. min=2 (pos 4), max=10 (pos 0),
// median=6; increasing False, decreasing True.
let desc = RangeIndex::new(10, 0, -2).unwrap();
assert_eq!(desc.len(), 5);
assert_eq!(desc.min(), Some(2));
assert_eq!(desc.max(), Some(10));
assert_eq!(desc.median(), Some(6.0));
assert_eq!(desc.argmin().unwrap(), 4);
assert_eq!(desc.argmax().unwrap(), 0);
assert!(!desc.is_monotonic_increasing());
assert!(desc.is_monotonic_decreasing());
assert_eq!(desc.nunique(), 5);
// Descending (even length): [10,8,6,4]. median = (8+6)/2 = 7; argmin = 3.
let desc_even = RangeIndex::new(10, 2, -2).unwrap();
assert_eq!(desc_even.len(), 4);
assert_eq!(desc_even.median(), Some(7.0));
assert_eq!(desc_even.argmin().unwrap(), 3);
assert_eq!(desc_even.argmax().unwrap(), 0);
}
#[test]
fn range_index_std_var_median_closed_form_tkc0m() {
let r = super::RangeIndex::new(1, 11, 1).unwrap();
// 1..=10: median = 5.5; var = sum((x - 5.5)^2)/9; std = sqrt(var).
assert_eq!(r.median(), Some(5.5));
let var = r.var().unwrap();
// Expected variance for 1..=10 is 9.166666...
assert!((var - 9.1666666666).abs() < 1e-6);
let std_val = r.std().unwrap();
assert!((std_val - var.sqrt()).abs() < 1e-12);
// Single element: var/std None; median = the value.
let one = super::RangeIndex::new(5, 6, 1).unwrap();
assert_eq!(one.median(), Some(5.0));
assert_eq!(one.var(), None);
assert_eq!(one.std(), None);
let descending = super::RangeIndex::new(9, 0, -4).unwrap();
assert_eq!(descending.median(), Some(5.0));
let even_step = super::RangeIndex::new(2, 14, 3).unwrap();
assert_eq!(even_step.median(), Some(6.5));
// Empty: all None.
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert_eq!(empty.median(), None);
assert_eq!(empty.var(), None);
}
#[test]
fn range_index_prod_match_pandas_8yxw8() {
// 1..=5 prod = 120.
let r = super::RangeIndex::new(1, 6, 1).unwrap();
assert_eq!(r.prod(), 120);
// Empty prod = 1.
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert_eq!(empty.prod(), 1);
// Includes zero → prod = 0.
let with_zero = super::RangeIndex::new(0, 5, 1).unwrap();
assert_eq!(with_zero.prod(), 0);
}
#[test]
fn range_index_var_prod_use_direct_values_tzvt3() {
let descending = super::RangeIndex::new(9, 0, -4).unwrap();
assert_eq!(descending.var(), Some(16.0));
assert_eq!(descending.std(), Some(4.0));
assert_eq!(descending.prod(), 45);
let negative_step = super::RangeIndex::new(2, -7, -3).unwrap();
assert_eq!(negative_step.var(), Some(9.0));
assert_eq!(negative_step.prod(), 8);
let overflow = super::RangeIndex::new(i64::MAX, i64::MAX - 2, -1).unwrap();
assert_eq!(overflow.prod(), i64::MAX);
}
#[test]
fn range_index_prod_positive_saturation_matches_former_e87gz() {
fn former(range: &super::RangeIndex) -> i64 {
let mut total: i128 = 1;
for position in 0..range.len() {
total = total.saturating_mul(i128::from(range.value_at(position)));
}
i64::try_from(total).unwrap_or(if total > 0 { i64::MAX } else { i64::MIN })
}
for range in [
super::RangeIndex::new(0, 0, 1).unwrap(),
super::RangeIndex::new(1, 10, 1).unwrap(),
super::RangeIndex::new(1, 10_001, 1).unwrap(),
super::RangeIndex::new(10_000, 0, -1).unwrap(),
super::RangeIndex::new(-3, 4, 1).unwrap(),
super::RangeIndex::new(-1, -30, -1).unwrap(),
super::RangeIndex::new(i64::MAX - 4, i64::MAX, 1).unwrap(),
] {
assert_eq!(range.prod(), former(&range));
}
}
#[test]
fn range_index_reductions_use_wide_length_uza04173() {
let asc = super::RangeIndex::new(i64::MIN, i64::MAX, 1).unwrap();
assert_eq!(asc.min(), Some(i64::MIN));
assert_eq!(asc.max(), Some(i64::MAX - 1));
assert_eq!(asc.sum(), i64::MIN);
assert_eq!(asc.mean(), Some(-1.0));
let desc = super::RangeIndex::new(i64::MAX, i64::MIN, -1).unwrap();
assert_eq!(desc.min(), Some(i64::MIN + 1));
assert_eq!(desc.max(), Some(i64::MAX));
assert_eq!(desc.sum(), 0);
assert_eq!(desc.mean(), Some(0.0));
}
#[test]
fn range_index_memory_usage_saturates_uza04175() {
let small = super::RangeIndex::new(2, 11, 3).unwrap();
assert_eq!(small.memory_usage(false), 3 * std::mem::size_of::<i64>());
assert_eq!(small.nbytes(), small.memory_usage(false));
let wide = super::RangeIndex::new(i64::MIN, i64::MAX, 1).unwrap();
assert_eq!(wide.memory_usage(false), usize::MAX);
assert_eq!(wide.nbytes(), usize::MAX);
}
#[test]
fn range_index_searchsorted_direct_values_mv1e4() -> Result<(), super::IndexError> {
let stepped = super::RangeIndex::new(2, 20, 3).unwrap();
assert_eq!(stepped.searchsorted(1, "left")?, 0);
assert_eq!(stepped.searchsorted(2, "left")?, 0);
assert_eq!(stepped.searchsorted(2, "right")?, 1);
assert_eq!(stepped.searchsorted(8, "left")?, 2);
assert_eq!(stepped.searchsorted(9, "left")?, 3);
assert_eq!(stepped.searchsorted(20, "left")?, 6);
let empty = super::RangeIndex::new(5, 5, 1).unwrap();
assert_eq!(empty.searchsorted(5, "left")?, 0);
let descending = super::RangeIndex::new(9, 0, -3).unwrap();
assert!(descending.searchsorted(6, "left").is_err());
Ok(())
}
#[test]
fn range_index_searchsorted_uses_closed_form_uza04174() -> Result<(), super::IndexError> {
let stepped = super::RangeIndex::new(i64::MIN, i64::MIN + 10, 2).unwrap();
assert_eq!(stepped.searchsorted(i64::MIN, "left")?, 0);
assert_eq!(stepped.searchsorted(i64::MIN, "right")?, 1);
assert_eq!(stepped.searchsorted(i64::MIN + 3, "left")?, 2);
assert_eq!(stepped.searchsorted(i64::MIN + 4, "right")?, 3);
let wide = super::RangeIndex::new(i64::MIN, i64::MAX, 1).unwrap();
let zero_pos = usize::try_from(i128::from(i64::MAX) + 1).unwrap();
assert_eq!(wide.searchsorted(0, "left")?, zero_pos);
assert_eq!(wide.searchsorted(0, "right")?, zero_pos + 1);
assert_eq!(wide.searchsorted(i64::MAX, "left")?, wide.len());
Ok(())
}
#[test]
fn range_index_min_max_sum_mean_closed_form_fwlv4() {
let asc = super::RangeIndex::new(1, 11, 1).unwrap();
// Values 1..=10
assert_eq!(asc.min(), Some(1));
assert_eq!(asc.max(), Some(10));
assert_eq!(asc.sum(), 55);
assert_eq!(asc.mean(), Some(5.5));
let desc = super::RangeIndex::new(10, 0, -2).unwrap();
// Values 10, 8, 6, 4, 2 — sum=30, mean=6, min=2, max=10
assert_eq!(desc.min(), Some(2));
assert_eq!(desc.max(), Some(10));
assert_eq!(desc.sum(), 30);
assert_eq!(desc.mean(), Some(6.0));
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert_eq!(empty.min(), None);
assert_eq!(empty.max(), None);
assert_eq!(empty.sum(), 0);
assert_eq!(empty.mean(), None);
}
#[test]
fn datetime_index_where_putmask_match_pandas_nwqty() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, b, c]).set_name("ts");
// where: keep position 0 and 2; replace position 1 with i64::MIN (NAT).
let masked = dt.r#where(&[true, false, true], i64::MIN)?;
assert_eq!(masked.values(), vec![Some(a), None, Some(c)]);
assert_eq!(masked.name().map(|n| n.as_str()), Some("ts"));
// putmask: replace positions where mask=true with c.
let put = dt.putmask(&[true, false, false], c)?;
assert_eq!(put.values(), vec![Some(c), Some(b), Some(c)]);
// Length mismatch errors.
let bad_cond = dt.r#where(&[true, false], i64::MIN).unwrap_err();
assert!(matches!(
bad_cond,
super::IndexError::LengthMismatch {
expected: 3,
actual: 2,
..
}
));
let bad_mask = dt.putmask(&[true; 5], c).unwrap_err();
assert!(matches!(
bad_mask,
super::IndexError::LengthMismatch {
expected: 3,
actual: 5,
..
}
));
Ok(())
}
#[test]
fn timedelta_index_where_putmask_match_pandas_nwqty() -> Result<(), super::IndexError> {
let nat = fp_types::Timedelta::NAT;
let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]).set_name("d");
let masked = td.r#where(&[false, true, false], nat)?;
assert_eq!(masked.values(), vec![None, Some(200), None]);
assert_eq!(masked.name().map(|n| n.as_str()), Some("d"));
let put = td.putmask(&[false, true, true], 999)?;
assert_eq!(put.values(), vec![Some(100), Some(999), Some(999)]);
let bad = td.r#where(&[true, false], nat).unwrap_err();
assert!(matches!(
bad,
super::IndexError::LengthMismatch {
expected: 3,
actual: 2,
..
}
));
Ok(())
}
#[test]
fn index_variants_searchsorted_match_pandas_tam73() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, b, c]);
assert_eq!(dt.searchsorted(a, "left")?, 0);
assert_eq!(dt.searchsorted(a, "right")?, 1);
assert_eq!(dt.searchsorted(c, "right")?, 3);
// Mid-range insertion (between a and b).
let mid = a + 1;
assert_eq!(dt.searchsorted(mid, "left")?, 1);
// Bad side.
assert!(dt.searchsorted(a, "middle").is_err());
let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
assert_eq!(td.searchsorted(150, "left")?, 1);
assert_eq!(td.searchsorted(200, "right")?, 2);
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p2, p3]);
assert_eq!(pi.searchsorted(p2, "left")?, 1);
assert_eq!(pi.searchsorted(p3, "right")?, 3);
// Mismatched freq rejects.
let mismatch = Period::new(10, PeriodFreq::ANNUAL);
assert!(pi.searchsorted(mismatch, "left").is_err());
let r = super::RangeIndex::new(0, 10, 2).unwrap();
// Range values: [0, 2, 4, 6, 8].
assert_eq!(r.searchsorted(4, "left")?, 2);
assert_eq!(r.searchsorted(4, "right")?, 3);
assert_eq!(r.searchsorted(7, "left")?, 4);
// Descending range rejects.
let desc = super::RangeIndex::new(10, 0, -2).unwrap();
assert!(desc.searchsorted(4, "left").is_err());
Ok(())
}
#[test]
fn datetime_timedelta_get_indexer_non_unique_match_pandas_sm32a() {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
// 4-element index with a duplicated `a`.
let dt = super::DatetimeIndex::new(vec![a, b, a, b]);
let (positions, missing) = dt.get_indexer_non_unique(&[a, b + 99]);
// a matches positions 0 and 2; b+99 is missing.
assert_eq!(positions, vec![0, 2, -1]);
assert_eq!(missing, vec![1]);
let td = super::TimedeltaIndex::new(vec![100_i64, 200, 100]);
let (positions, missing) = td.get_indexer_non_unique(&[100, 999]);
assert_eq!(positions, vec![0, 2, -1]);
assert_eq!(missing, vec![1]);
}
#[test]
fn datetime_timedelta_get_loc_get_indexer_match_pandas_6x9de() -> Result<(), super::IndexError>
{
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, b, c]);
// get_loc finds first position.
assert_eq!(dt.get_loc(b)?, 1);
let missing_err = dt.get_loc(b + 1).unwrap_err();
assert!(matches!(
missing_err,
super::IndexError::InvalidArgument(ref msg) if msg.contains("get_loc")
));
// get_indexer maps each target.
let mapped = dt.get_indexer(&[c, a, b + 999]);
assert_eq!(mapped, vec![2, 0, -1]);
// TimedeltaIndex spot check.
let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
assert_eq!(td.get_loc(200)?, 1);
assert_eq!(td.get_indexer(&[300, 999, 100]), vec![2, -1, 0]);
Ok(())
}
#[test]
fn datetime_timedelta_slice_indexer_match_pandas_95eqf() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, b, c]);
assert_eq!(dt.slice_indexer(b, c)?, 1..3);
assert_eq!(dt.slice_indexer(a, c)?, 0..3);
let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
assert_eq!(td.slice_indexer(150, 250)?, 1..2);
Ok(())
}
#[test]
fn datetime_timedelta_get_slice_bound_match_pandas_x7r04() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, b, c]);
assert_eq!(dt.get_slice_bound(b, "left")?, 1);
assert_eq!(dt.get_slice_bound(b, "right")?, 2);
assert!(dt.get_slice_bound(b, "middle").is_err());
let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
assert_eq!(td.get_slice_bound(150, "left")?, 1);
assert_eq!(td.get_slice_bound(200, "right")?, 2);
Ok(())
}
#[test]
fn datetime_timedelta_slice_locs_match_pandas_mxedz() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let d = 1_707_350_400_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, b, c, d]);
// Slice [b, c]: positions [1, 3) (right is exclusive in slice_locs).
assert_eq!(dt.slice_locs(b, c)?, (1, 3));
// Slice [a, d]: full range.
assert_eq!(dt.slice_locs(a, d)?, (0, 4));
// Slice past the end: empty range.
assert_eq!(dt.slice_locs(d + 1, d + 2)?, (4, 4));
// Non-monotonic rejects.
let unsorted = super::DatetimeIndex::new(vec![c, a, b, d]);
assert!(unsorted.slice_locs(a, c).is_err());
// TimedeltaIndex spot check.
let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]);
assert_eq!(td.slice_locs(150, 250)?, (1, 2));
Ok(())
}
#[test]
fn index_variants_to_flat_index_match_pandas_wcpw5() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS]).set_name("ts");
let dt_flat = dt.to_flat_index();
assert_eq!(dt_flat.len(), 1);
assert_eq!(dt_flat.name().map(|n| n.as_str()), Some("ts"));
assert!(matches!(
dt_flat.labels()[0],
super::IndexLabel::Datetime64(_)
));
assert_eq!(dt.to_frame(), dt_flat.to_frame());
assert_eq!(dt.to_series(), dt_flat.to_series());
let td = super::TimedeltaIndex::new(vec![100_i64]).set_name("d");
let td_flat = td.to_flat_index();
assert_eq!(td_flat.len(), 1);
assert_eq!(td_flat.name().map(|n| n.as_str()), Some("d"));
assert_eq!(td.to_frame(), td_flat.to_frame());
assert_eq!(td.to_series(), td_flat.to_series());
use fp_types::{Period, PeriodFreq};
// TEST-CHANGE (45fzr): the flat labels are the periods themselves
// (they were their text; pandas' PeriodIndex.to_flat_index is the
// PeriodIndex).
let pi = super::PeriodIndex::new(vec![Period::new(10, PeriodFreq::Monthly)]).set_name("p");
let pi_flat = pi.to_flat_index();
assert_eq!(pi_flat.len(), 1);
assert_eq!(
pi_flat.labels()[0],
super::IndexLabel::Period(Period::new(10, PeriodFreq::Monthly))
);
assert_eq!(pi.to_frame(), pi_flat.to_frame());
assert_eq!(pi.to_series(), pi_flat.to_series());
let r = super::RangeIndex::new(0, 3, 1).unwrap().set_name("r");
let r_flat = r.to_flat_index();
assert_eq!(r_flat.len(), 3);
assert_eq!(r_flat.name().map(|n| n.as_str()), Some("r"));
assert_eq!(r.to_frame(), r_flat.to_frame());
assert_eq!(r.to_series(), r_flat.to_series());
let cat = super::CategoricalIndex::from_values(vec!["a".to_owned(), "b".to_owned()], false);
let cat_flat = cat.to_flat_index();
assert_eq!(cat_flat.len(), 2);
assert_eq!(cat.to_frame(), cat_flat.to_frame());
assert_eq!(cat.to_series(), cat_flat.to_series());
}
#[test]
fn index_variants_all_any_forward_flat_truthiness_ejwyw() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![0, NS]);
let dt_flat = dt.to_flat_index();
assert_eq!(dt.any(), dt_flat.any());
assert_eq!(dt.all(), dt_flat.all());
assert!(dt.any());
assert!(!dt.all());
let td = super::TimedeltaIndex::new(vec![0, 5]);
let td_flat = td.to_flat_index();
assert_eq!(td.any(), td_flat.any());
assert_eq!(td.all(), td_flat.all());
assert!(td.any());
assert!(!td.all());
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![
Period::new(1, PeriodFreq::Monthly),
Period::new(2, PeriodFreq::Monthly),
]);
let pi_flat = pi.to_flat_index();
assert_eq!(pi.any(), pi_flat.any());
assert_eq!(pi.all(), pi_flat.all());
assert!(pi.any());
assert!(pi.all());
let empty_pi = super::PeriodIndex::new(Vec::new());
assert_eq!(empty_pi.any(), empty_pi.to_flat_index().any());
assert!(!empty_pi.any());
// TEST-CHANGE (45fzr): a NaT period label is missing in the flat
// index now (it was its text 'NaT', truthy), so a NaT-only index
// is not any (pandas raises TypeError for PeriodIndex.any).
let nat_pi = super::PeriodIndex::new(vec![Period::new(i64::MIN, PeriodFreq::Daily)]);
assert_eq!(nat_pi.any(), nat_pi.to_flat_index().any());
assert!(!nat_pi.any());
let range = super::RangeIndex::new(0, 3, 1).unwrap();
let range_flat = range.to_flat_index();
assert_eq!(range.any(), range_flat.any());
assert_eq!(range.all(), range_flat.all());
assert!(range.any());
assert!(!range.all());
let empty_range = super::RangeIndex::new(0, 0, 1).unwrap();
assert!(!empty_range.any());
assert!(empty_range.all());
let cat = super::CategoricalIndex::from_values(vec![String::new(), "x".to_owned()], false);
let cat_flat = cat.to_flat_index();
assert_eq!(cat.any(), cat_flat.any());
assert_eq!(cat.all(), cat_flat.all());
assert!(cat.any());
assert!(!cat.all());
}
#[test]
#[ignore = "profile harness for br-frankenpandas-8blqp"]
fn period_index_any_nonempty_profile_8blqp() {
use fp_types::{Period, PeriodFreq};
fn former(index: &super::PeriodIndex) -> bool {
index.to_flat_index().any()
}
fn candidate(index: &super::PeriodIndex) -> bool {
index.any()
}
fn percentile(sorted_samples: &[u128], percentile: usize) -> u128 {
let rank = sorted_samples
.len()
.saturating_mul(percentile)
.div_ceil(100)
.saturating_sub(1);
sorted_samples[rank]
}
let parity_cases = [
super::PeriodIndex::new(Vec::new()),
super::PeriodIndex::new(vec![Period::new(i64::MIN, PeriodFreq::Daily)]),
super::PeriodIndex::new(vec![Period::new(0, PeriodFreq::ANNUAL)]).set_name("annual"),
super::PeriodIndex::new(vec![
Period::new(i64::MIN, PeriodFreq::Monthly),
Period::new(-1, PeriodFreq::QUARTERLY),
Period::new(0, PeriodFreq::Daily),
Period::new(i64::MAX, PeriodFreq::Secondly),
]),
];
for index in &parity_cases {
assert_eq!(candidate(index), former(index));
}
let index =
super::PeriodIndex::from_range(Period::new(-8_192, PeriodFreq::Minutely), 16_384)
.set_name("minute");
assert_eq!(candidate(&index), former(&index));
for _ in 0..2 {
std::hint::black_box(former(std::hint::black_box(&index)));
std::hint::black_box(candidate(std::hint::black_box(&index)));
}
let mut former_ns = Vec::with_capacity(12);
let mut candidate_ns = Vec::with_capacity(12);
for sample in 0..12 {
let (former_elapsed, candidate_elapsed) = if sample % 2 == 0 {
let started = std::time::Instant::now();
std::hint::black_box(former(std::hint::black_box(&index)));
let former_elapsed = started.elapsed().as_nanos();
let started = std::time::Instant::now();
std::hint::black_box(candidate(std::hint::black_box(&index)));
(former_elapsed, started.elapsed().as_nanos())
} else {
let started = std::time::Instant::now();
std::hint::black_box(candidate(std::hint::black_box(&index)));
let candidate_elapsed = started.elapsed().as_nanos();
let started = std::time::Instant::now();
std::hint::black_box(former(std::hint::black_box(&index)));
(started.elapsed().as_nanos(), candidate_elapsed)
};
former_ns.push(former_elapsed);
candidate_ns.push(candidate_elapsed);
}
former_ns.sort_unstable();
candidate_ns.sort_unstable();
let former_p50 = percentile(&former_ns, 50);
let candidate_p50 = percentile(&candidate_ns, 50);
println!(
"PERIOD_INDEX_ANY former_ns={former_ns:?} candidate_ns={candidate_ns:?} \
former_p50_ns={former_p50} former_p95_ns={} former_p99_ns={} \
candidate_p50_ns={candidate_p50} candidate_p95_ns={} candidate_p99_ns={} \
ratio={:.6}",
percentile(&former_ns, 95),
percentile(&former_ns, 99),
percentile(&candidate_ns, 95),
percentile(&candidate_ns, 99),
former_p50 as f64 / candidate_p50 as f64,
);
}
#[test]
fn index_variants_get_level_values_forward_flat_xf0zn() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![NS, 2 * NS]).set_name("ts");
assert_eq!(dt.get_level_values(0)?, dt.to_flat_index());
let td = super::TimedeltaIndex::new(vec![5, 10]).set_name("delta");
assert_eq!(td.get_level_values(0)?, td.to_flat_index());
use fp_types::{Period, PeriodFreq};
let pi =
super::PeriodIndex::new(vec![Period::new(1, PeriodFreq::Monthly)]).set_name("period");
assert_eq!(pi.get_level_values(0)?, pi.to_flat_index());
let range = super::RangeIndex::new(1, 4, 1)?.set_name("row");
assert_eq!(range.get_level_values(0)?, range.to_flat_index());
let cat =
super::CategoricalIndex::from_values(vec!["a".to_owned()], false).set_name("category");
assert_eq!(cat.get_level_values(0)?, cat.to_flat_index());
assert!(matches!(
cat.get_level_values(1),
Err(super::IndexError::OutOfBounds {
position: 1,
length: 1
})
));
Ok(())
}
#[test]
fn range_index_level_ops_handle_flat_contract_directly_ckbyh() -> Result<(), super::IndexError>
{
let range = super::RangeIndex::new(9, 0, -4)?.set_name("row");
let level_values = range.get_level_values(0)?;
assert_eq!(level_values.name().map(|n| n.as_str()), Some("row"));
assert_eq!(
level_values.labels.int64_view().unwrap().as_slice(),
&[9, 5, 1]
);
assert!(
level_values.labels.materialized.get().is_none(),
"RangeIndex::get_level_values should keep typed Int64 output backing"
);
assert!(matches!(
range.get_level_values(2),
Err(super::IndexError::OutOfBounds {
position: 2,
length: 1
})
));
assert!(matches!(
range.droplevel(0),
Err(super::IndexError::InvalidArgument(message))
if message == "cannot remove the only level from a flat Index"
));
assert!(matches!(
range.droplevel(2),
Err(super::IndexError::OutOfBounds {
position: 2,
length: 1
})
));
Ok(())
}
#[test]
fn index_variants_droplevel_forward_flat_errors_t8vpw() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![NS, 2 * NS]).set_name("ts");
assert!(matches!(
dt.droplevel(0),
Err(super::IndexError::InvalidArgument(message))
if message == "cannot remove the only level from a flat Index"
));
let td = super::TimedeltaIndex::new(vec![5, 10]).set_name("delta");
assert!(matches!(
td.droplevel(0),
Err(super::IndexError::InvalidArgument(message))
if message == "cannot remove the only level from a flat Index"
));
use fp_types::{Period, PeriodFreq};
let pi =
super::PeriodIndex::new(vec![Period::new(1, PeriodFreq::Monthly)]).set_name("period");
assert!(matches!(
pi.droplevel(0),
Err(super::IndexError::InvalidArgument(message))
if message == "cannot remove the only level from a flat Index"
));
let range = super::RangeIndex::new(1, 4, 1)?.set_name("row");
assert!(matches!(
range.droplevel(0),
Err(super::IndexError::InvalidArgument(message))
if message == "cannot remove the only level from a flat Index"
));
let cat =
super::CategoricalIndex::from_values(vec!["a".to_owned()], false).set_name("category");
assert!(matches!(
cat.droplevel(1),
Err(super::IndexError::OutOfBounds {
position: 1,
length: 1
})
));
Ok(())
}
#[test]
fn index_variants_groupby_forward_flat_buckets_vypi3() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![NS, 2 * NS, NS]);
assert_eq!(dt.groupby(), dt.to_flat_index().groupby());
let td = super::TimedeltaIndex::new(vec![5, 10, 5]);
assert_eq!(td.groupby(), td.to_flat_index().groupby());
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![
Period::new(1, PeriodFreq::Monthly),
Period::new(2, PeriodFreq::Monthly),
Period::new(1, PeriodFreq::Monthly),
]);
assert_eq!(pi.groupby(), pi.to_flat_index().groupby());
let range = super::RangeIndex::new(2, 8, 2).unwrap();
assert_eq!(range.groupby(), range.to_flat_index().groupby());
let cat = super::CategoricalIndex::from_values(
vec!["a".to_owned(), "b".to_owned(), "a".to_owned()],
false,
);
assert_eq!(cat.groupby(), cat.to_flat_index().groupby());
assert_eq!(
cat.groupby()
.get(&super::IndexLabel::Utf8("a".to_owned()))
.cloned(),
Some(vec![0, 2])
);
}
#[test]
fn index_variants_map_forward_flat_and_preserve_name_vxlfs() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![NS, 2 * NS]).set_name("ts");
let dt_mapped = dt.map(|label| match label {
super::IndexLabel::Datetime64(nanos) => super::IndexLabel::Int64(*nanos / NS),
other => other.clone(),
});
assert_eq!(
dt_mapped.labels(),
&[super::IndexLabel::Int64(1), super::IndexLabel::Int64(2)]
);
assert_eq!(dt_mapped.name().map(|n| n.as_str()), Some("ts"));
let td = super::TimedeltaIndex::new(vec![5, 10]).set_name("delta");
assert_eq!(
td.map(|label| match label {
super::IndexLabel::Timedelta64(nanos) => super::IndexLabel::Int64(*nanos * 2),
other => other.clone(),
}),
td.to_flat_index().map(|label| match label {
super::IndexLabel::Timedelta64(nanos) => super::IndexLabel::Int64(*nanos * 2),
other => other.clone(),
})
);
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![Period::new(1, PeriodFreq::Monthly)]);
assert_eq!(
pi.map(|label| super::IndexLabel::Utf8(format!("p:{label}"))),
pi.to_flat_index()
.map(|label| super::IndexLabel::Utf8(format!("p:{label}")))
);
let range = super::RangeIndex::new(1, 4, 1).unwrap();
assert_eq!(
range.map(|label| match label {
super::IndexLabel::Int64(v) => super::IndexLabel::Int64(*v + 10),
other => other.clone(),
}),
range.to_flat_index().map(|label| match label {
super::IndexLabel::Int64(v) => super::IndexLabel::Int64(*v + 10),
other => other.clone(),
})
);
let cat = super::CategoricalIndex::from_values(vec!["a".to_owned()], false);
assert_eq!(
cat.map(|label| super::IndexLabel::Utf8(label.to_string().to_uppercase())),
cat.to_flat_index()
.map(|label| super::IndexLabel::Utf8(label.to_string().to_uppercase()))
);
}
#[test]
fn index_variants_astype_forward_flat_and_preserve_name_o5pyg() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![NS, 2 * NS]).set_name("ts");
assert_eq!(
dt.astype("int64").unwrap(),
dt.to_flat_index().astype("int64").unwrap()
);
assert_eq!(
dt.astype("int64").unwrap().name().map(|n| n.as_str()),
Some("ts")
);
assert!(dt.astype("float64").is_err());
let td = super::TimedeltaIndex::new(vec![5, 10]).set_name("delta");
assert_eq!(
td.astype("string").unwrap(),
td.to_flat_index().astype("string").unwrap()
);
assert_eq!(
td.astype("string").unwrap().name().map(|n| n.as_str()),
Some("delta")
);
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![Period::new(1, PeriodFreq::Monthly)]);
assert_eq!(
pi.astype("object").unwrap(),
pi.to_flat_index().astype("object").unwrap()
);
let range = super::RangeIndex::new(1, 4, 1).unwrap().set_name("r");
assert_eq!(
range.astype("str").unwrap(),
range.to_flat_index().astype("str").unwrap()
);
assert_eq!(
range.astype("str").unwrap().name().map(|n| n.as_str()),
Some("r")
);
let cat = super::CategoricalIndex::from_values(vec!["7".to_owned()], false);
assert_eq!(
cat.astype("int").unwrap(),
cat.to_flat_index().astype("int").unwrap()
);
assert!(cat.astype("datetime64[ns]").is_err());
}
#[test]
fn range_index_astype_uses_direct_values_up4dq() {
let range = super::RangeIndex::new(9, 0, -4).unwrap().set_name("r");
let as_int = range.astype("int64").unwrap();
assert_eq!(as_int.name().map(|n| n.as_str()), Some("r"));
assert_eq!(as_int.labels.int64_view().unwrap().as_slice(), &[9, 5, 1]);
assert!(
as_int.labels.materialized.get().is_none(),
"RangeIndex::astype(int64) should keep typed Int64 output backing"
);
let as_string = range.astype("string").unwrap();
assert_eq!(as_string.name().map(|n| n.as_str()), Some("r"));
assert_eq!(
as_string.labels(),
&[
super::IndexLabel::Utf8("9".to_owned()),
super::IndexLabel::Utf8("5".to_owned()),
super::IndexLabel::Utf8("1".to_owned()),
]
);
assert!(matches!(
range.astype("float64"),
Err(super::IndexError::InvalidArgument(message))
if message == "unsupported Index.astype dtype \"float64\""
));
assert!(matches!(
range.astype("datetime64[ns]"),
Err(super::IndexError::InvalidArgument(message))
if message == "DatetimeIndex requires homogeneous DatetimeIndex labels"
));
assert!(matches!(
range.astype("timedelta64[ns]"),
Err(super::IndexError::InvalidArgument(message))
if message == "TimedeltaIndex requires homogeneous TimedeltaIndex labels"
));
let empty = super::RangeIndex::new(0, 0, 1).unwrap().set_name("empty");
assert_eq!(
empty
.astype("datetime64[ns]")
.unwrap()
.name()
.map(|n| n.as_str()),
Some("empty")
);
assert_eq!(empty.astype("timedelta64[ns]").unwrap().len(), 0);
}
#[test]
fn index_variants_asof_forward_flat_and_mask_locs_955dj() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![NS, 3 * NS, 5 * NS]);
let dt_key = super::IndexLabel::Datetime64(4 * NS);
assert_eq!(dt.asof(&dt_key), dt.to_flat_index().asof(&dt_key));
assert_eq!(dt.asof(&super::IndexLabel::Datetime64(0)), None);
let td = super::TimedeltaIndex::new(vec![10, 20, 30]);
let where_td = super::Index::new(vec![
super::IndexLabel::Timedelta64(5),
super::IndexLabel::Timedelta64(20),
super::IndexLabel::Timedelta64(25),
]);
let mask = [false, true, true];
assert_eq!(
td.asof_locs(&where_td, Some(&mask)),
td.to_flat_index().asof_locs(&where_td, Some(&mask))
);
assert_eq!(
td.asof_locs(&where_td, Some(&mask)),
vec![None, Some(1), Some(1)]
);
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![
Period::new(1, PeriodFreq::Monthly),
Period::new(2, PeriodFreq::Monthly),
]);
let period_key = pi.to_flat_index().labels()[1].clone();
assert_eq!(pi.asof(&period_key), pi.to_flat_index().asof(&period_key));
let range = super::RangeIndex::new(2, 8, 2).unwrap();
let range_key = super::IndexLabel::Int64(5);
assert_eq!(
range.asof(&range_key),
range.to_flat_index().asof(&range_key)
);
let cat = super::CategoricalIndex::from_values(
vec!["a".to_owned(), "c".to_owned(), "e".to_owned()],
false,
);
let cat_key = super::IndexLabel::Utf8("d".to_owned());
assert_eq!(cat.asof(&cat_key), cat.to_flat_index().asof(&cat_key));
}
#[test]
fn range_index_asof_locs_uses_direct_values_vuftp() {
let range = super::RangeIndex::new(2, 10, 2).unwrap();
let where_index = super::Index::from_i64_values(vec![1, 4, 5, 11]);
assert_eq!(
range.asof_locs(&where_index, None),
range.to_flat_index().asof_locs(&where_index, None)
);
assert_eq!(
range.asof_locs(&where_index, None),
vec![None, Some(1), Some(1), Some(3)]
);
let mask = [true, false, true, true];
assert_eq!(
range.asof_locs(&where_index, Some(&mask)),
range.to_flat_index().asof_locs(&where_index, Some(&mask))
);
assert_eq!(
range.asof_locs(&where_index, Some(&mask)),
vec![None, Some(0), Some(0), Some(3)]
);
let descending = super::RangeIndex::new(9, 0, -4).unwrap();
let descending_where = super::Index::from_i64_values(vec![0, 5, 10]);
assert_eq!(
descending.asof_locs(&descending_where, None),
descending
.to_flat_index()
.asof_locs(&descending_where, None)
);
let mixed_where = super::Index::new(vec![super::IndexLabel::Utf8("z".to_owned())]);
assert_eq!(
range.asof_locs(&mixed_where, Some(&[true, true])),
range
.to_flat_index()
.asof_locs(&mixed_where, Some(&[true, true]))
);
}
#[test]
fn index_variants_drop_join_sortlevel_forward_flat_gr6kj() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![NS, 3 * NS, 5 * NS]).set_name("ts");
let drop_dt = [super::IndexLabel::Datetime64(3 * NS)];
assert_eq!(dt.drop(&drop_dt), dt.to_flat_index().drop(&drop_dt));
assert_eq!(dt.drop(&drop_dt).name().map(|n| n.as_str()), Some("ts"));
let td = super::TimedeltaIndex::new(vec![30, 10, 20]);
let (td_sorted, td_order) = td.sortlevel();
let (flat_td_sorted, flat_td_order) = td.to_flat_index().sortlevel();
assert_eq!(td_sorted, flat_td_sorted);
assert_eq!(td_order, flat_td_order);
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![
Period::new(2, PeriodFreq::Monthly),
Period::new(1, PeriodFreq::Monthly),
]);
assert_eq!(
pi.join(&pi.to_flat_index(), "outer").unwrap(),
pi.to_flat_index()
);
let range = super::RangeIndex::new(2, 8, 2).unwrap();
let other = super::Index::new(vec![
super::IndexLabel::Int64(4),
super::IndexLabel::Int64(6),
super::IndexLabel::Int64(9),
]);
assert_eq!(
range.join(&other, "inner").unwrap(),
range.to_flat_index().join(&other, "inner").unwrap()
);
assert!(range.join(&other, "sideways").is_err());
let cat = super::CategoricalIndex::from_values(
vec!["b".to_owned(), "a".to_owned(), "b".to_owned()],
false,
);
let (cat_sorted, cat_order) = cat.sortlevel();
let (flat_cat_sorted, flat_cat_order) = cat.to_flat_index().sortlevel();
assert_eq!(cat_sorted, flat_cat_sorted);
assert_eq!(cat_order, flat_cat_order);
let drop_cat = [super::IndexLabel::Utf8("b".to_owned())];
assert_eq!(cat.drop(&drop_cat), cat.to_flat_index().drop(&drop_cat));
}
#[test]
fn index_variants_temporal_rounding_forwarders_dznxu() {
let hour = fp_types::Timedelta::NANOS_PER_HOUR;
let minute = fp_types::Timedelta::NANOS_PER_MIN;
let nat = fp_types::Timedelta::NAT;
let dt =
super::DatetimeIndex::new(vec![hour / 2, hour + 31 * minute, i64::MIN]).set_name("ts");
let dt_floor = dt.floor("h").unwrap();
assert_eq!(dt_floor.asi8(), vec![0, hour, i64::MIN]);
assert_eq!(dt_floor.name().map(|n| n.as_str()), Some("ts"));
let dt_ceil = dt.ceil("h").unwrap();
assert_eq!(dt_ceil.asi8(), vec![hour, 2 * hour, i64::MIN]);
let dt_round = dt.round("h").unwrap();
assert_eq!(dt_round.asi8(), vec![0, 2 * hour, i64::MIN]);
let dt_snap = dt.snap("h").unwrap();
assert_eq!(dt_snap.asi8(), dt.asi8());
assert!(dt.floor("not-a-frequency").is_err());
assert!(dt.snap("not-a-frequency").is_err());
let td = super::TimedeltaIndex::new(vec![hour / 2, hour + 31 * minute, nat]).set_name("d");
assert_eq!(td.floor("h").unwrap().asi8(), vec![0, hour, nat]);
assert_eq!(td.ceil("h").unwrap().asi8(), vec![hour, 2 * hour, nat]);
assert_eq!(td.round("h").unwrap().asi8(), vec![0, 2 * hour, nat]);
assert_eq!(td.round("h").unwrap().name().map(|n| n.as_str()), Some("d"));
assert!(td.ceil("not-a-frequency").is_err());
use fp_types::{Period, PeriodFreq};
let periods = super::PeriodIndex::new(vec![
Period::new(10, PeriodFreq::Monthly),
Period::new(11, PeriodFreq::Monthly),
])
.set_name("p");
let rounded_periods = periods.round("not-a-frequency");
assert_eq!(rounded_periods.values(), periods.values());
assert_eq!(rounded_periods.name().map(|n| n.as_str()), Some("p"));
}
#[test]
fn index_variants_diff_forwarders_lqs0a() {
let day = fp_types::Timedelta::NANOS_PER_DAY;
let nat = fp_types::Timedelta::NAT;
let dt = super::DatetimeIndex::new(vec![day, 3 * day, i64::MIN, 10 * day]).set_name("ts");
assert_eq!(dt.diff(1).asi8(), vec![nat, 2 * day, nat, nat]);
assert_eq!(dt.diff(-1).asi8(), vec![-2 * day, nat, nat, nat]);
assert_eq!(dt.diff(0).asi8(), vec![0, 0, nat, 0]);
assert_eq!(dt.diff(1).name().map(|n| n.as_str()), Some("ts"));
let td = super::TimedeltaIndex::new(vec![day, 4 * day, nat, 9 * day]).set_name("delta");
assert_eq!(td.diff(2).asi8(), vec![nat, nat, nat, 5 * day]);
assert_eq!(td.diff(-1).asi8(), vec![-3 * day, nat, nat, nat]);
assert_eq!(td.diff(0).asi8(), vec![0, 0, nat, 0]);
assert_eq!(td.diff(1).name().map(|n| n.as_str()), Some("delta"));
use fp_types::{Period, PeriodFreq};
let periods = super::PeriodIndex::new(vec![
Period::new(10, PeriodFreq::Monthly),
Period::new(12, PeriodFreq::Monthly),
Period::new(13, PeriodFreq::QUARTERLY),
Period::new(15, PeriodFreq::QUARTERLY),
]);
assert_eq!(periods.diff(1), vec![None, Some(2), None, Some(2)]);
assert_eq!(periods.diff(-1), vec![Some(-2), None, Some(-2), None]);
assert_eq!(periods.diff(0), vec![Some(0), Some(0), Some(0), Some(0)]);
let range = super::RangeIndex::new(2, 10, 2).unwrap().set_name("r");
assert_eq!(range.diff(1), vec![None, Some(2), Some(2), Some(2)]);
assert_eq!(range.diff(-2), vec![Some(-4), Some(-4), None, None]);
assert_eq!(range.diff(0), vec![Some(0), Some(0), Some(0), Some(0)]);
assert_eq!(range.name().map(|n| n.as_str()), Some("r"));
let descending = super::RangeIndex::new(9, 0, -3).unwrap();
assert_eq!(descending.diff(1), vec![None, Some(-3), Some(-3)]);
assert_eq!(descending.diff(-1), vec![Some(3), Some(3), None]);
let wide = super::RangeIndex::new(i64::MIN, i64::MAX, i64::MAX).unwrap();
assert_eq!(wide.diff(1), vec![None, Some(i64::MAX), Some(i64::MAX)]);
assert_eq!(wide.diff(-1), vec![Some(-i64::MAX), Some(-i64::MAX), None]);
assert_eq!(wide.diff(2), vec![None, None, None]);
assert_eq!(wide.diff(-2), vec![None, None, None]);
let cat = super::CategoricalIndex::from_values(vec!["a".to_owned(), "b".to_owned()], false);
let err = cat.diff(1).unwrap_err();
assert!(matches!(
err,
super::IndexError::InvalidArgument(message)
if message.contains("Categorical has no 'diff' method")
));
}
#[test]
fn datetime_index_to_period_matches_pandas_ordinals_002sq()
-> Result<(), Box<dyn std::error::Error>> {
fn ns(value: &str) -> Result<i64, super::DateRangeError> {
super::parse_datetime_to_nanos(value)
}
use fp_types::{Period, PeriodFreq};
let dt = super::DatetimeIndex::new(vec![
ns("1969-12-31 23:59:59")?,
ns("1970-01-01 00:00:00")?,
ns("2024-02-29 12:34:56")?,
])
.set_name("ts");
assert_eq!(
dt.to_period("Y")?.values(),
&[
Period::new(-1, PeriodFreq::ANNUAL),
Period::new(0, PeriodFreq::ANNUAL),
Period::new(54, PeriodFreq::ANNUAL),
]
);
assert_eq!(
dt.to_period("Q")?.values(),
&[
Period::new(-1, PeriodFreq::QUARTERLY),
Period::new(0, PeriodFreq::QUARTERLY),
Period::new(216, PeriodFreq::QUARTERLY),
]
);
assert_eq!(
dt.to_period("M")?.values(),
&[
Period::new(-1, PeriodFreq::Monthly),
Period::new(0, PeriodFreq::Monthly),
Period::new(649, PeriodFreq::Monthly),
]
);
assert_eq!(
dt.to_period("D")?.values(),
&[
Period::new(-1, PeriodFreq::Daily),
Period::new(0, PeriodFreq::Daily),
Period::new(19_782, PeriodFreq::Daily),
]
);
assert_eq!(
dt.to_period("W")?.values(),
&[
Period::new(1, PeriodFreq::WEEKLY),
Period::new(1, PeriodFreq::WEEKLY),
Period::new(2_827, PeriodFreq::WEEKLY),
]
);
assert_eq!(
dt.to_period("B")?.values(),
&[
Period::new(-1, PeriodFreq::Business),
Period::new(0, PeriodFreq::Business),
Period::new(14_130, PeriodFreq::Business),
]
);
assert_eq!(
dt.to_period("H")?.values(),
&[
Period::new(-1, PeriodFreq::Hourly),
Period::new(0, PeriodFreq::Hourly),
Period::new(474_780, PeriodFreq::Hourly),
]
);
let minutely = dt.to_period("min")?;
assert_eq!(
minutely.values(),
&[
Period::new(-1, PeriodFreq::Minutely),
Period::new(0, PeriodFreq::Minutely),
Period::new(28_486_834, PeriodFreq::Minutely),
]
);
assert_eq!(minutely.name().map(|n| n.as_str()), Some("ts"));
assert_eq!(
dt.to_period("S")?.values(),
&[
Period::new(-1, PeriodFreq::Secondly),
Period::new(0, PeriodFreq::Secondly),
Period::new(1_709_210_096, PeriodFreq::Secondly),
]
);
assert!(matches!(
super::DatetimeIndex::new(vec![i64::MIN]).to_period("M"),
Err(super::IndexError::InvalidArgument(message))
if message.contains("invalid or NaT datetime nanos")
));
assert!(matches!(
dt.to_period("fortnight"),
Err(super::IndexError::InvalidArgument(message))
if message.contains("unsupported frequency")
));
Ok(())
}
/// The RENDERED labels for the same three timestamps the ordinal test above
/// checks — the half that was missing, and the half that was wrong.
///
/// ⚠️ CORRECT ORDINALS DO NOT IMPLY CORRECT LABELS. That test verified
/// `to_period("W")` produces ordinals 1, 1, 2827 and `to_period("B")`
/// produces -1, 0, 14130, all of which agree with pandas — and every one of
/// them then rendered decades wrong, because those two ordinals are a WEEK
/// COUNT and a BUSINESS-DAY COUNT rather than day indices (fixed in
/// 08363d42f). Checking only the ordinal is what let it through.
///
/// This is also the path that makes the frequencies reachable at all:
/// `PeriodIndex::format` matches `pd.PeriodIndex.format()`, and `to_index`,
/// `to_flat_index` and the `.str` accessor all render through the same
/// `Display`. Every string below is transcribed from live pandas 2.2.3.
#[test]
fn period_index_labels_match_pandas_not_just_the_ordinals()
-> Result<(), Box<dyn std::error::Error>> {
fn ns(value: &str) -> Result<i64, super::DateRangeError> {
super::parse_datetime_to_nanos(value)
}
let dt = super::DatetimeIndex::new(vec![
ns("1969-12-31 23:59:59")?,
ns("1970-01-01 00:00:00")?,
ns("2024-02-29 12:34:56")?,
]);
// WEEKLY IS A RANGE. The first two timestamps straddle the epoch and
// land in the SAME week, which is why they render identically.
assert_eq!(
dt.to_period("W")?.format(),
vec![
"1969-12-29/1970-01-04".to_owned(),
"1969-12-29/1970-01-04".to_owned(),
"2024-02-26/2024-03-03".to_owned(),
]
);
// BUSINESS is a single date, but off a five-per-week axis.
assert_eq!(
dt.to_period("B")?.format(),
vec![
"1969-12-31".to_owned(),
"1970-01-01".to_owned(),
"2024-02-29".to_owned(),
]
);
// The frequencies whose ordinal IS a count of its own unit were always
// right; pinned here so the two groups are compared side by side.
assert_eq!(
dt.to_period("D")?.format(),
vec![
"1969-12-31".to_owned(),
"1970-01-01".to_owned(),
"2024-02-29".to_owned(),
]
);
assert_eq!(
dt.to_period("M")?.format(),
vec![
"1969-12".to_owned(),
"1970-01".to_owned(),
"2024-02".to_owned(),
]
);
// to_index / to_flat_index labels render through the same Display,
// so the weekly range has to survive the trip into a flat Index too.
// TEST-CHANGE (45fzr): the flat labels are periods (they were Utf8
// text); their text is compared.
assert_eq!(
dt.to_period("W")?
.to_flat_index()
.labels()
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>(),
vec![
"1969-12-29/1970-01-04".to_owned(),
"1969-12-29/1970-01-04".to_owned(),
"2024-02-26/2024-03-03".to_owned(),
]
);
Ok(())
}
#[test]
fn period_index_asfreq_boundary_conversion_h1zia() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let annual = super::PeriodIndex::new(vec![
Period::new(0, PeriodFreq::ANNUAL),
Period::new(1, PeriodFreq::ANNUAL),
])
.set_name("p");
assert_eq!(
annual.asfreq("M")?.values(),
&[
Period::new(11, PeriodFreq::Monthly),
Period::new(23, PeriodFreq::Monthly),
]
);
let annual_start = annual.asfreq_with_how("M", "start")?;
assert_eq!(
annual_start.values(),
&[
Period::new(0, PeriodFreq::Monthly),
Period::new(12, PeriodFreq::Monthly),
]
);
assert_eq!(annual_start.name().map(|n| n.as_str()), Some("p"));
let quarterly = super::PeriodIndex::new(vec![
Period::new(0, PeriodFreq::QUARTERLY),
Period::new(1, PeriodFreq::QUARTERLY),
]);
assert_eq!(
quarterly.asfreq("D")?.values(),
&[
Period::new(89, PeriodFreq::Daily),
Period::new(180, PeriodFreq::Daily),
]
);
assert_eq!(
quarterly.asfreq_with_how("D", "s")?.values(),
&[
Period::new(0, PeriodFreq::Daily),
Period::new(90, PeriodFreq::Daily),
]
);
let monthly = super::PeriodIndex::new(vec![
Period::new(0, PeriodFreq::Monthly),
Period::new(1, PeriodFreq::Monthly),
]);
assert_eq!(
monthly.asfreq("S")?.values(),
&[
Period::new(2_678_399, PeriodFreq::Secondly),
Period::new(5_097_599, PeriodFreq::Secondly),
]
);
assert_eq!(
monthly.asfreq_with_how("S", "begin")?.values(),
&[
Period::new(0, PeriodFreq::Secondly),
Period::new(2_678_400, PeriodFreq::Secondly),
]
);
assert_eq!(
monthly.asfreq("B")?.values(),
&[
Period::new(21, PeriodFreq::Business),
Period::new(41, PeriodFreq::Business),
]
);
assert_eq!(
monthly.asfreq_with_how("W", "start")?.values(),
&[
Period::new(1, PeriodFreq::WEEKLY),
Period::new(5, PeriodFreq::WEEKLY),
]
);
assert!(matches!(
monthly.asfreq_with_how("D", "middle"),
Err(super::IndexError::InvalidArgument(message))
if message.contains("asfreq how must be 'start' or 'end'")
));
assert!(matches!(
monthly.asfreq("fortnight"),
Err(super::IndexError::InvalidArgument(message))
if message.contains("unsupported frequency")
));
Ok(())
}
/// asfreq across the sub-second frequencies, in BOTH directions.
///
/// `asfreq_with_how` never enumerates frequencies itself -- it takes the
/// period's boundary instant and asks which target period contains it. That
/// means ms/us/ns came for free with the ordinal arms, and this test is what
/// proves "for free" was not "untested": every ordinal below is transcribed
/// from live pandas 2.2.3, `Timestamp(base).to_period(src).asfreq(dst, how)`.
///
/// The sweep behind it covered all 10x10 frequency pairs x 2 boundaries x 4
/// base timestamps -- 800 cases, 0 mismatches -- so the rows kept here are
/// the ones that would move first if the model were wrong: a coarse period
/// widening into ns (where the multiply is largest), a ns period collapsing
/// back, and the pre-epoch cases where a truncating divide would differ from
/// a floor.
#[test]
fn period_index_asfreq_subsecond_both_directions() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
// 2024-03-15, one whole day, widened to nanoseconds. End is the LAST
// nanosecond of the day, not the first of the next.
let daily = super::PeriodIndex::new(vec![Period::new(19_797, PeriodFreq::Daily)]);
assert_eq!(
daily.asfreq_with_how("ns", "start")?.values(),
&[Period::new(
1_710_460_800_000_000_000,
PeriodFreq::Nanoseconds
)]
);
assert_eq!(
daily.asfreq_with_how("ns", "end")?.values(),
&[Period::new(
1_710_547_199_999_999_999,
PeriodFreq::Nanoseconds
)]
);
// ...and the same day widened to milliseconds from the epoch.
let epoch_day = super::PeriodIndex::new(vec![Period::new(0, PeriodFreq::Daily)]);
assert_eq!(
epoch_day.asfreq_with_how("ms", "start")?.values(),
&[Period::new(0, PeriodFreq::Milliseconds)]
);
assert_eq!(
epoch_day.asfreq_with_how("ms", "end")?.values(),
&[Period::new(86_399_999, PeriodFreq::Milliseconds)]
);
// Nanoseconds collapsing back: a 1ns period has start == end, so both
// boundaries land on the same coarser period.
let nanos = super::PeriodIndex::new(vec![Period::new(
1_710_498_645_123_456_789,
PeriodFreq::Nanoseconds,
)]);
assert_eq!(
nanos.asfreq_with_how("D", "start")?.values(),
&[Period::new(19_797, PeriodFreq::Daily)]
);
assert_eq!(
nanos.asfreq_with_how("D", "end")?.values(),
&[Period::new(19_797, PeriodFreq::Daily)]
);
assert_eq!(
nanos.asfreq_with_how("ms", "start")?.values(),
&[Period::new(1_710_498_645_123, PeriodFreq::Milliseconds)]
);
// One step between adjacent sub-second units, each way.
let millis = super::PeriodIndex::new(vec![Period::new(
1_710_498_645_123,
PeriodFreq::Milliseconds,
)]);
assert_eq!(
millis.asfreq_with_how("ns", "start")?.values(),
&[Period::new(
1_710_498_645_123_000_000,
PeriodFreq::Nanoseconds
)]
);
assert_eq!(
millis.asfreq_with_how("ns", "end")?.values(),
&[Period::new(
1_710_498_645_123_999_999,
PeriodFreq::Nanoseconds
)]
);
let secondly =
super::PeriodIndex::new(vec![Period::new(1_710_498_645, PeriodFreq::Secondly)]);
assert_eq!(
secondly.asfreq_with_how("us", "start")?.values(),
&[Period::new(1_710_498_645_000_000, PeriodFreq::Microseconds)]
);
assert_eq!(
secondly.asfreq_with_how("us", "end")?.values(),
&[Period::new(1_710_498_645_999_999, PeriodFreq::Microseconds)]
);
// ⚠️ PRE-EPOCH, where a truncating divide would disagree with the floor.
// 1969-12-31 23:59:59.999000001 is ns ordinal -999999, and the ms period
// containing it is -1 (NOT 0).
let pre_epoch =
super::PeriodIndex::new(vec![Period::new(-999_999, PeriodFreq::Nanoseconds)]);
assert_eq!(
pre_epoch.asfreq_with_how("ms", "start")?.values(),
&[Period::new(-1, PeriodFreq::Milliseconds)]
);
assert_eq!(
pre_epoch.asfreq_with_how("ms", "end")?.values(),
&[Period::new(-1, PeriodFreq::Milliseconds)]
);
// ...and back out: ms period -1 spans ns ordinals -1_000_000 ..= -1.
let pre_epoch_ms = super::PeriodIndex::new(vec![Period::new(-1, PeriodFreq::Milliseconds)]);
assert_eq!(
pre_epoch_ms.asfreq_with_how("ns", "start")?.values(),
&[Period::new(-1_000_000, PeriodFreq::Nanoseconds)]
);
assert_eq!(
pre_epoch_ms.asfreq_with_how("ns", "end")?.values(),
&[Period::new(-1, PeriodFreq::Nanoseconds)]
);
Ok(())
}
#[test]
fn period_index_timestamp_boundaries_d44wh() -> Result<(), Box<dyn std::error::Error>> {
fn ns(value: &str) -> Result<i64, super::DateRangeError> {
super::parse_datetime_to_nanos(value)
}
use fp_types::{Period, PeriodFreq};
let monthly = super::PeriodIndex::new(vec![
Period::new(0, PeriodFreq::Monthly),
Period::new(1, PeriodFreq::Monthly),
])
.set_name("period");
assert_eq!(
monthly.start_time()?.asi8(),
vec![ns("1970-01-01 00:00:00")?, ns("1970-02-01 00:00:00")?]
);
assert_eq!(
monthly.end_time()?.asi8(),
vec![
ns("1970-02-01 00:00:00")? - 1,
ns("1970-03-01 00:00:00")? - 1
]
);
assert_eq!(
monthly.to_timestamp("start")?.asi8(),
monthly.start_time()?.asi8()
);
assert_eq!(
monthly.to_timestamp("end")?.asi8(),
monthly.end_time()?.asi8()
);
assert_eq!(
monthly.to_timestamp("")?.name().map(|n| n.as_str()),
Some("period")
);
assert_eq!(monthly.qyear()?, vec![1970, 1970]);
assert!(matches!(
monthly.to_timestamp("middle"),
Err(super::IndexError::InvalidArgument(message))
if message.contains("to_timestamp how must be 'start' or 'end'")
));
let quarterly = super::PeriodIndex::new(vec![
Period::new(-1, PeriodFreq::QUARTERLY),
Period::new(0, PeriodFreq::QUARTERLY),
]);
assert_eq!(
quarterly.start_time()?.asi8(),
vec![ns("1969-10-01 00:00:00")?, ns("1970-01-01 00:00:00")?]
);
assert_eq!(
quarterly.end_time()?.asi8(),
vec![
ns("1970-01-01 00:00:00")? - 1,
ns("1970-04-01 00:00:00")? - 1
]
);
assert_eq!(quarterly.qyear()?, vec![1969, 1970]);
let mixed_freq = super::PeriodIndex::new(vec![
Period::new(1, PeriodFreq::WEEKLY),
Period::new(2, PeriodFreq::Business),
Period::new(1, PeriodFreq::Hourly),
]);
assert_eq!(
mixed_freq.start_time()?.asi8(),
vec![
ns("1969-12-29 00:00:00")?,
ns("1970-01-05 00:00:00")?,
fp_types::Timedelta::NANOS_PER_HOUR
]
);
assert_eq!(
mixed_freq.end_time()?.asi8(),
vec![
ns("1970-01-05 00:00:00")? - 1,
ns("1970-01-06 00:00:00")? - 1,
2 * fp_types::Timedelta::NANOS_PER_HOUR - 1
]
);
assert_eq!(mixed_freq.qyear()?, vec![1970, 1970, 1970]);
Ok(())
}
#[test]
fn index_variants_view_transpose_ravel_nlevels_infer_objects_match_pandas_d0ph1() {
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS, i64::MIN]).set_name("ts");
assert!(dt.view().equals(&dt));
assert!(dt.transpose().equals(&dt));
assert!(dt.T().identical(&dt));
assert_eq!(dt.ravel(), dt.values());
assert_eq!(dt.nlevels(), 1);
assert!(dt.infer_objects().equals(&dt));
let td = super::TimedeltaIndex::new(vec![100_i64, fp_types::Timedelta::NAT]).set_name("d");
assert!(td.view().equals(&td));
assert!(td.T().identical(&td));
assert_eq!(td.ravel(), td.values());
assert_eq!(td.nlevels(), 1);
use fp_types::{Period, PeriodFreq};
let pi = super::PeriodIndex::new(vec![
Period::new(10, PeriodFreq::Monthly),
Period::new(11, PeriodFreq::Monthly),
]);
assert_eq!(pi.view().values(), pi.values());
assert!(pi.T().identical(&pi));
assert_eq!(pi.ravel(), pi.values().to_vec());
assert_eq!(pi.nlevels(), 1);
let r = super::RangeIndex::new(0, 5, 1).unwrap();
assert!(r.view().equals(&r));
assert!(r.T().identical(&r));
assert_eq!(r.ravel(), r.values().to_vec());
assert_eq!(r.nlevels(), 1);
let cat = super::CategoricalIndex::from_values(vec!["a".to_owned(), "b".to_owned()], false);
assert_eq!(cat.view().labels(), cat.labels());
assert!(cat.T().identical(&cat));
assert_eq!(cat.ravel(), cat.labels().to_vec());
assert_eq!(cat.nlevels(), 1);
}
#[test]
fn datetime_index_set_ops_match_pandas_ik8if() {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let d = 1_707_350_400_i64 * NS;
let left = super::DatetimeIndex::new(vec![a, b, c]).set_name("ts");
let right = super::DatetimeIndex::new(vec![b, c, d]).set_name("ts");
// intersection: b, c (in self order).
let inter = left.intersection(&right);
assert_eq!(inter.values(), vec![Some(b), Some(c)]);
assert_eq!(inter.name().map(|n| n.as_str()), Some("ts"));
// union: a, b, c then d.
let union = left.union(&right);
assert_eq!(union.values(), vec![Some(a), Some(b), Some(c), Some(d)]);
// difference: a (only in self).
let diff = left.difference(&right);
assert_eq!(diff.values(), vec![Some(a)]);
// symmetric_difference: a (self-only) then d (other-only).
let sym = left.symmetric_difference(&right);
assert_eq!(sym.values(), vec![Some(a), Some(d)]);
// Mismatched names drop the name.
let mismatched = super::DatetimeIndex::new(vec![b]).set_name("other");
assert_eq!(left.intersection(&mismatched).name(), None);
assert_eq!(left.union(&mismatched).name(), None);
}
#[test]
fn timedelta_index_set_ops_match_pandas_ik8if() {
let left = super::TimedeltaIndex::new(vec![100_i64, 200, 300]).set_name("d");
let right = super::TimedeltaIndex::new(vec![200_i64, 300, 400]).set_name("d");
let inter = left.intersection(&right);
assert_eq!(inter.values(), vec![Some(200), Some(300)]);
assert_eq!(inter.name().map(|n| n.as_str()), Some("d"));
let union = left.union(&right);
assert_eq!(
union.values(),
vec![Some(100), Some(200), Some(300), Some(400)]
);
let diff = left.difference(&right);
assert_eq!(diff.values(), vec![Some(100)]);
let sym = left.symmetric_difference(&right);
assert_eq!(sym.values(), vec![Some(100), Some(400)]);
}
#[test]
fn timedelta_index_sum_match_pandas_qi04e() {
let nat = fp_types::Timedelta::NAT;
let td = super::TimedeltaIndex::new(vec![10_i64, 20, 30, nat]);
assert_eq!(td.sum(), Some(60));
let only_nat = super::TimedeltaIndex::new(vec![nat, nat]);
assert_eq!(only_nat.sum(), Some(0));
let empty = super::TimedeltaIndex::new(vec![]);
assert_eq!(empty.sum(), Some(0));
}
#[test]
fn datetime_timedelta_var_match_pandas_pw5sn() {
// [10, 20, 30] sample variance with ddof=1: ((100 + 0 + 100)/2) = 100.
let td = super::TimedeltaIndex::new(vec![10_i64, 20, 30]);
assert!((td.var().unwrap() - 100.0).abs() < 1e-9);
// Single element: not enough data.
let one = super::TimedeltaIndex::new(vec![5_i64]);
assert_eq!(one.var(), None);
// DatetimeIndex spot check.
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![10 * NS, 20 * NS, 30 * NS]);
assert!(dt.var().is_some());
}
#[test]
fn datetime_timedelta_std_match_pandas_3hb3t() {
// [10, 20, 30] sample std with ddof=1: sqrt((100 + 0 + 100) / 2) = 10.
let td = super::TimedeltaIndex::new(vec![10_i64, 20, 30]);
assert_eq!(td.std(), Some(10));
// [10, 30] sample std: sqrt(((10-20)^2 + (30-20)^2) / 1) = sqrt(200).
let td2 = super::TimedeltaIndex::new(vec![10_i64, 30]);
let expected = 200f64.sqrt() as i64;
assert_eq!(td2.std(), Some(expected));
// Single element / NAT-only: not enough data.
let one = super::TimedeltaIndex::new(vec![5_i64]);
assert_eq!(one.std(), None);
let nat = super::TimedeltaIndex::new(vec![fp_types::Timedelta::NAT]);
assert_eq!(nat.std(), None);
// DatetimeIndex spot check.
const NS: i64 = 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![10 * NS, 20 * NS, 30 * NS]);
assert!(dt.std().is_some());
}
#[test]
fn datetime_timedelta_shift_match_pandas_1y3sx() {
const NS: i64 = 1_000_000_000;
let day_ns = 86_400 * NS;
let dt = super::DatetimeIndex::new(vec![1_704_067_200_i64 * NS, i64::MIN]).set_name("ts");
// Shift by 2 days.
let shifted = dt.shift(2, day_ns);
assert_eq!(
shifted.values()[0],
Some(1_704_067_200_i64 * NS + 2 * day_ns)
);
assert_eq!(shifted.values()[1], None);
assert_eq!(shifted.name().map(|n| n.as_str()), Some("ts"));
// Negative shift.
let back = dt.shift(-1, day_ns);
assert_eq!(back.values()[0], Some(1_704_067_200_i64 * NS - day_ns));
// TimedeltaIndex spot check.
let td = super::TimedeltaIndex::new(vec![100_i64, fp_types::Timedelta::NAT]);
let shifted_td = td.shift(3, 50);
assert_eq!(shifted_td.values()[0], Some(250));
assert_eq!(shifted_td.values()[1], None);
}
#[test]
fn datetime_timedelta_mean_median_match_pandas_wp0gr() {
const NS: i64 = 1_000_000_000;
let a = 1_000_000_000_i64 * NS;
let b = 2_000_000_000_i64 * NS;
let c = 3_000_000_000_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, b, c, i64::MIN]);
// Mean: (a + b + c) / 3 = b (the middle, since arithmetic).
assert_eq!(dt.mean(), Some(b));
// Median: middle of three sorted values = b.
assert_eq!(dt.median(), Some(b));
// Even-length set: median is average of two middles.
let dt_even = super::DatetimeIndex::new(vec![a, b]);
let total = i128::from(a) + i128::from(b);
let expected = i64::try_from(total / 2).unwrap();
assert_eq!(dt_even.median(), Some(expected));
// All-NAT.
let nat = super::DatetimeIndex::new(vec![i64::MIN; 3]);
assert_eq!(nat.mean(), None);
assert_eq!(nat.median(), None);
// Timedelta spot check.
let td = super::TimedeltaIndex::new(vec![10_i64, 20, 30]);
assert_eq!(td.mean(), Some(20));
assert_eq!(td.median(), Some(20));
}
#[test]
fn datetime_index_min_max_sort_values_match_pandas_kastf() {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![b, c, i64::MIN, a]).set_name("ts");
assert_eq!(dt.min(), Some(a));
assert_eq!(dt.max(), Some(c));
let sorted = dt.sort_values();
let sorted_alias = dt.sort();
// NAT sorts first (na_position='first' default).
assert_eq!(sorted.values(), vec![None, Some(a), Some(b), Some(c)]);
assert_eq!(sorted_alias.values(), sorted.values());
assert_eq!(sorted.name().map(|n| n.as_str()), Some("ts"));
assert_eq!(sorted_alias.name().map(|n| n.as_str()), Some("ts"));
let all_nat = super::DatetimeIndex::new(vec![i64::MIN, i64::MIN]);
assert_eq!(all_nat.min(), None);
assert_eq!(all_nat.max(), None);
let empty = super::DatetimeIndex::new(vec![]);
assert_eq!(empty.min(), None);
assert_eq!(empty.max(), None);
assert!(empty.sort_values().is_empty());
assert!(empty.sort().is_empty());
}
#[test]
fn timedelta_index_min_max_sort_values_match_pandas_kastf() {
let nat = fp_types::Timedelta::NAT;
let td = super::TimedeltaIndex::new(vec![300_i64, nat, 100, 200]).set_name("d");
assert_eq!(td.min(), Some(100));
assert_eq!(td.max(), Some(300));
let sorted = td.sort_values();
let sorted_alias = td.sort();
assert_eq!(sorted.values(), vec![None, Some(100), Some(200), Some(300)]);
assert_eq!(sorted_alias.values(), sorted.values());
assert_eq!(sorted.name().map(|n| n.as_str()), Some("d"));
assert_eq!(sorted_alias.name().map(|n| n.as_str()), Some("d"));
let all_nat = super::TimedeltaIndex::new(vec![nat, nat]);
assert_eq!(all_nat.min(), None);
assert_eq!(all_nat.max(), None);
let empty = super::TimedeltaIndex::new(vec![]);
assert_eq!(empty.min(), None);
assert_eq!(empty.max(), None);
assert!(empty.sort().is_empty());
}
#[test]
fn datetime_index_append_delete_match_pandas_834v9() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let left = super::DatetimeIndex::new(vec![a, b]).set_name("ts");
let right = super::DatetimeIndex::new(vec![c]).set_name("ts");
let merged = left.append(&right);
assert_eq!(merged.values(), vec![Some(a), Some(b), Some(c)]);
assert_eq!(merged.name().map(|n| n.as_str()), Some("ts"));
let mismatched = super::DatetimeIndex::new(vec![c]).set_name("other");
assert_eq!(left.append(&mismatched).name(), None);
let trimmed = left.append(&right).delete(1)?;
assert_eq!(trimmed.values(), vec![Some(a), Some(c)]);
assert_eq!(trimmed.name().map(|n| n.as_str()), Some("ts"));
let oob = left.delete(5).unwrap_err();
assert!(matches!(
oob,
super::IndexError::OutOfBounds {
position: 5,
length: 2
}
));
Ok(())
}
#[test]
fn timedelta_index_append_delete_match_pandas_834v9() -> Result<(), super::IndexError> {
let left = super::TimedeltaIndex::new(vec![1_i64, 2]).set_name("d");
let right = super::TimedeltaIndex::new(vec![3_i64]).set_name("d");
let merged = left.append(&right);
assert_eq!(merged.values(), vec![Some(1), Some(2), Some(3)]);
assert_eq!(merged.name().map(|n| n.as_str()), Some("d"));
let trimmed = merged.delete(0)?;
assert_eq!(trimmed.values(), vec![Some(2), Some(3)]);
assert!(matches!(
left.delete(7).unwrap_err(),
super::IndexError::OutOfBounds {
position: 7,
length: 2
}
));
Ok(())
}
#[test]
fn period_index_append_delete_match_pandas_834v9() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let left = super::PeriodIndex::new(vec![p1, p2]).set_name("p");
let right = super::PeriodIndex::new(vec![p3]).set_name("p");
let merged = left.append(&right);
assert_eq!(merged.values(), &[p1, p2, p3]);
assert_eq!(merged.name().map(|n| n.as_str()), Some("p"));
let mismatched = super::PeriodIndex::new(vec![p3]).set_name("other");
assert_eq!(left.append(&mismatched).name(), None);
let trimmed = merged.delete(1)?;
assert_eq!(trimmed.values(), &[p1, p3]);
assert!(matches!(
left.delete(5).unwrap_err(),
super::IndexError::OutOfBounds {
position: 5,
length: 2
}
));
Ok(())
}
#[test]
fn range_index_append_delete_match_pandas_834v9() -> Result<(), super::IndexError> {
let left = super::RangeIndex::new(0, 3, 1).unwrap();
let right = super::RangeIndex::new(10, 12, 1).unwrap();
let merged = left.append(&right);
let merged_labels = int64_labels(&merged);
assert_eq!(merged_labels, vec![0, 1, 2, 10, 11]);
let trimmed = left.delete(1)?;
let trimmed_labels = int64_labels(&trimmed);
assert_eq!(trimmed_labels, vec![0, 2]);
assert!(matches!(
left.delete(99).unwrap_err(),
super::IndexError::OutOfBounds {
position: 99,
length: 3
}
));
Ok(())
}
#[test]
fn range_index_values_generate_arithmetic_progression_without_flat_index_w6q7d() {
let positive = super::RangeIndex::new(2, 11, 3).unwrap();
assert_eq!(positive.values().to_vec(), vec![2, 5, 8]);
assert_eq!(positive.values().get(3), None);
let descending = super::RangeIndex::new(9, 0, -4).unwrap();
assert_eq!(descending.values().to_vec(), vec![9, 5, 1]);
let empty = super::RangeIndex::new(5, 5, 1).unwrap();
assert!(empty.values().is_empty());
}
#[test]
fn range_index_equals_compares_sequence_shape_x7tr6() {
let empty_a = super::RangeIndex::new(5, 5, 1).unwrap();
let empty_b = super::RangeIndex::new(10, 0, 2).unwrap();
assert!(empty_a.equals(&empty_b));
let singleton_a = super::RangeIndex::new(7, 8, 1).unwrap();
let singleton_b = super::RangeIndex::new(7, 100, 93).unwrap();
assert!(singleton_a.equals(&singleton_b));
let same_values_a = super::RangeIndex::new(0, 5, 2).unwrap();
let same_values_b = super::RangeIndex::new(0, 6, 2).unwrap();
assert!(same_values_a.equals(&same_values_b));
let different_step = super::RangeIndex::new(0, 6, 3).unwrap();
assert!(!same_values_a.equals(&different_step));
}
#[test]
fn index_repeat_capacity_checks_output_length_uza04182() {
assert_eq!(super::repeat_output_capacity(3, 4), 12);
assert_eq!(super::repeat_output_capacity(0, usize::MAX), 0);
}
#[test]
#[should_panic(expected = "index repeat output length overflow")]
fn index_repeat_capacity_rejects_overflow_uza04182() {
let _ = super::repeat_output_capacity(usize::MAX, 2);
}
#[test]
fn index_combined_capacity_checks_output_length_uza04183() {
assert_eq!(super::combined_output_capacity(3, 4), 7);
assert_eq!(super::insert_output_capacity(3), 4);
}
#[test]
#[should_panic(expected = "index combined output length overflow")]
fn index_combined_capacity_rejects_overflow_uza04183() {
let _ = super::combined_output_capacity(usize::MAX, 1);
}
#[test]
#[should_panic(expected = "index insert output length overflow")]
fn index_insert_capacity_rejects_overflow_uza04183() {
let _ = super::insert_output_capacity(usize::MAX);
}
#[test]
fn index_aggregate_capacity_checks_output_length_uza04185() {
assert_eq!(super::aggregate_output_capacity([2, 3, 4]), 9);
assert_eq!(super::aggregate_output_capacity([0, 0]), 0);
}
#[test]
#[should_panic(expected = "index aggregate output length overflow")]
fn index_aggregate_capacity_rejects_overflow_uza04185() {
let _ = super::aggregate_output_capacity([usize::MAX, 1]);
}
#[test]
fn range_index_take_repeat_keep_typed_backing_uza04166() -> Result<(), super::IndexError> {
let range = super::RangeIndex::new(2, 11, 3).unwrap().set_name("r");
let taken = range.take(&[2, 0, 2])?;
assert_eq!(taken.name().map(|n| n.as_str()), Some("r"));
assert_eq!(taken.labels.int64_view().unwrap().as_slice(), &[8, 2, 8]);
assert!(
taken.labels.materialized.get().is_none(),
"RangeIndex::take should keep typed Int64 output backing"
);
let repeated = range.repeat(2);
assert_eq!(repeated.name().map(|n| n.as_str()), Some("r"));
assert_eq!(
repeated.labels.int64_view().unwrap().as_slice(),
&[2, 2, 5, 5, 8, 8]
);
assert!(
repeated.labels.materialized.get().is_none(),
"RangeIndex::repeat should keep typed Int64 output backing"
);
Ok(())
}
#[test]
fn range_index_take_arithmetic_keep_affine_uza04205() -> Result<(), super::IndexError> {
let range = super::RangeIndex::new(10, 40, 3).unwrap().set_name("r");
let ascending = range.take(&[1, 3, 5])?;
assert_eq!(ascending.name().map(|n| n.as_str()), Some("r"));
assert_eq!(
ascending.labels.int64_view().unwrap().as_slice(),
&[13, 19, 25]
);
let affine = ascending
.labels
.int64_affine_range()
.expect("arithmetic take should keep lazy affine backing");
assert_eq!((affine.start, affine.step, affine.len), (13, 6, 3));
assert!(
ascending.labels.materialized.get().is_none(),
"arithmetic RangeIndex::take should not materialize labels"
);
let descending = range.take(&[5, 3, 1])?;
assert_eq!(
descending.labels.int64_view().unwrap().as_slice(),
&[25, 19, 13]
);
let affine = descending
.labels
.int64_affine_range()
.expect("descending arithmetic take should keep lazy affine backing");
assert_eq!((affine.start, affine.step, affine.len), (25, -6, 3));
let singleton = range.take(&[4])?;
assert_eq!(singleton.labels.int64_view().unwrap().as_slice(), &[22]);
assert!(
singleton.labels.int64_affine_range().is_some(),
"singleton take can stay lazy affine"
);
let empty = range.take(&[])?;
assert!(empty.labels.int64_view().unwrap().is_empty());
assert!(
empty.labels.int64_affine_range().is_some(),
"empty take can stay lazy affine"
);
let duplicate = range.take(&[1, 1, 2])?;
assert_eq!(
duplicate.labels.int64_view().unwrap().as_slice(),
&[13, 13, 16]
);
assert!(
duplicate.labels.int64_affine_range().is_none(),
"duplicate selectors must preserve materialized typed fallback"
);
assert!(
duplicate.labels.materialized.get().is_none(),
"fallback should remain typed Int64, not enum materialized"
);
Ok(())
}
#[test]
fn range_index_take_uses_wide_position_values_uza04176() -> Result<(), super::IndexError> {
let range = super::RangeIndex::new(i64::MIN, i64::MAX, 1)
.unwrap()
.set_name("wide");
let zero_pos = usize::try_from(i128::from(i64::MAX) + 1).unwrap();
let taken = range.take(&[0, zero_pos, range.len() - 1])?;
assert_eq!(taken.name().map(|n| n.as_str()), Some("wide"));
assert_eq!(
taken.labels.int64_view().unwrap().as_slice(),
&[i64::MIN, 0, i64::MAX - 1]
);
Ok(())
}
#[test]
fn range_index_take_repeat_use_direct_values_86gwy() -> Result<(), super::IndexError> {
let range = super::RangeIndex::new(9, 0, -4).unwrap().set_name("r");
let taken = range.take(&[2, 0])?;
assert_eq!(taken.name().map(|n| n.as_str()), Some("r"));
assert_eq!(taken.labels.int64_view().unwrap().as_slice(), &[1, 9]);
assert!(
taken.labels.materialized.get().is_none(),
"RangeIndex::take should gather direct i64 labels into typed backing"
);
let oob = range.take(&[3]).unwrap_err();
assert!(matches!(
oob,
super::IndexError::OutOfBounds {
position: 3,
length: 3
}
));
let repeated = range.repeat(2);
assert_eq!(repeated.name().map(|n| n.as_str()), Some("r"));
assert_eq!(
repeated.labels.int64_view().unwrap().as_slice(),
&[9, 9, 5, 5, 1, 1]
);
assert!(
repeated.labels.materialized.get().is_none(),
"RangeIndex::repeat should emit direct i64 labels into typed backing"
);
Ok(())
}
#[test]
fn range_index_to_flat_index_keeps_typed_backing_uza04167() {
let range = super::RangeIndex::new(9, 0, -4).unwrap().set_name("r");
let flat = range.to_flat_index();
assert_eq!(flat.name().map(|n| n.as_str()), Some("r"));
assert_eq!(flat.labels.int64_view().unwrap().as_slice(), &[9, 5, 1]);
assert!(
flat.labels.materialized.get().is_none(),
"RangeIndex::to_flat_index should keep typed Int64 output backing"
);
let positive = super::RangeIndex::new(2, 11, 3).unwrap().to_flat_index();
assert_eq!(positive.labels.int64_view().unwrap().as_slice(), &[2, 5, 8]);
assert!(positive.labels.materialized.get().is_none());
let empty = super::RangeIndex::new(5, 5, 1).unwrap().to_flat_index();
assert!(empty.is_empty());
assert!(empty.labels.materialized.get().is_none());
}
#[test]
fn range_index_where_putmask_keep_typed_backing_uza04153() -> Result<(), super::IndexError> {
let range = super::RangeIndex::new(2, 11, 3).unwrap().set_name("r");
let replaced = range.r#where(&[true, false, true], 99)?;
assert_eq!(replaced.name().map(|n| n.as_str()), Some("r"));
assert_eq!(
replaced.labels.int64_view().unwrap().as_slice(),
&[2, 99, 8]
);
assert!(
replaced.labels.materialized.get().is_none(),
"RangeIndex::where should keep typed Int64 output backing"
);
let masked = range.putmask(&[false, true, false], -7)?;
assert_eq!(masked.name().map(|n| n.as_str()), Some("r"));
assert_eq!(masked.labels.int64_view().unwrap().as_slice(), &[2, -7, 8]);
assert!(
masked.labels.materialized.get().is_none(),
"RangeIndex::putmask should keep typed Int64 output backing"
);
Ok(())
}
#[test]
fn range_index_where_putmask_use_direct_values_k1xts() -> Result<(), super::IndexError> {
let range = super::RangeIndex::new(9, 0, -4).unwrap().set_name("r");
let replaced = range.r#where(&[true, false, true], 99)?;
assert_eq!(replaced.name().map(|n| n.as_str()), Some("r"));
assert_eq!(
replaced.labels.int64_view().unwrap().as_slice(),
&[9, 99, 1]
);
assert!(
replaced.labels.materialized.get().is_none(),
"RangeIndex::where should mask direct i64 labels into typed backing"
);
let masked = range.putmask(&[false, true, false], -7)?;
assert_eq!(masked.name().map(|n| n.as_str()), Some("r"));
assert_eq!(masked.labels.int64_view().unwrap().as_slice(), &[9, -7, 1]);
assert!(
masked.labels.materialized.get().is_none(),
"RangeIndex::putmask should mask direct i64 labels into typed backing"
);
let where_err = range.r#where(&[true], 0).unwrap_err();
assert!(matches!(
where_err,
super::IndexError::LengthMismatch {
expected: 3,
actual: 1,
..
}
));
let putmask_err = range.putmask(&[false, true], 0).unwrap_err();
assert!(matches!(
putmask_err,
super::IndexError::LengthMismatch {
expected: 3,
actual: 2,
..
}
));
Ok(())
}
#[test]
fn range_index_set_ops_keep_typed_backing_uza04168() {
let left = super::RangeIndex::new(0, 5, 1).unwrap().set_name("k");
let right = super::RangeIndex::new(2, 7, 1).unwrap().set_name("k");
let intersection = left.intersection(&right);
let union = left.union(&right);
let difference = left.difference(&right);
let symmetric = left.symmetric_difference(&right);
assert_eq!(intersection.name().map(|n| n.as_str()), Some("k"));
assert_eq!(union.name().map(|n| n.as_str()), Some("k"));
assert_eq!(difference.name().map(|n| n.as_str()), Some("k"));
assert_eq!(symmetric.name().map(|n| n.as_str()), Some("k"));
assert_eq!(
intersection.labels.int64_view().unwrap().as_slice(),
&[2, 3, 4]
);
assert_eq!(
union.labels.int64_view().unwrap().as_slice(),
&[0, 1, 2, 3, 4, 5, 6]
);
assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[0, 1]);
assert_eq!(
symmetric.labels.int64_view().unwrap().as_slice(),
&[0, 1, 5, 6]
);
for output in [&intersection, &union, &difference, &symmetric] {
assert!(
output.labels.materialized.get().is_none(),
"RangeIndex set ops should keep typed Int64 output backing"
);
}
}
#[test]
fn range_index_set_ops_use_direct_values_b7nxg() {
let left = super::RangeIndex::new(9, -3, -3).unwrap().set_name("k");
let right = super::RangeIndex::new(6, -6, -3).unwrap().set_name("k");
let intersection = left.intersection(&right);
let union = left.union(&right);
let difference = left.difference(&right);
let symmetric = left.symmetric_difference(&right);
assert_eq!(intersection.name().map(|n| n.as_str()), Some("k"));
assert_eq!(union.name().map(|n| n.as_str()), Some("k"));
assert_eq!(difference.name().map(|n| n.as_str()), Some("k"));
assert_eq!(symmetric.name().map(|n| n.as_str()), Some("k"));
// pandas 2.2.3: intersection uses sort=False (self-order, descending
// preserved); union/difference/symmetric_difference use sort=None and
// return ascending-sorted results for these both-non-empty operands.
assert_eq!(
intersection.labels.int64_view().unwrap().as_slice(),
&[6, 3, 0]
);
assert_eq!(
union.labels.int64_view().unwrap().as_slice(),
&[-3, 0, 3, 6, 9]
);
assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[9]);
assert_eq!(symmetric.labels.int64_view().unwrap().as_slice(), &[-3, 9]);
let mismatched = right.set_name("other");
assert_eq!(left.intersection(&mismatched).name(), None);
assert_eq!(left.union(&mismatched).name(), None);
assert_eq!(left.symmetric_difference(&mismatched).name(), None);
assert_eq!(
left.difference(&mismatched).name().map(|n| n.as_str()),
Some("k")
);
// intersection (self-order) and this single-span difference keep lazy
// affine backing; union/symmetric materialize because reconciling the
// interleaved descending lattices to pandas' ascending order requires a
// sort (the affine fast paths still apply to aligned ascending inputs).
for output in [&intersection, &difference] {
assert!(
output.labels.materialized.get().is_none(),
"self-order intersection and single-span difference keep typed lazy backing"
);
}
}
#[test]
fn range_index_set_ops_closed_form_membership_preserves_order_iatnc() {
let left = super::RangeIndex::new(9, -3, -3).unwrap().set_name("k");
let right = super::RangeIndex::new(6, -9, -6).unwrap().set_name("k");
let intersection = left.intersection(&right);
let union = left.union(&right);
let difference = left.difference(&right);
let symmetric = left.symmetric_difference(&right);
assert_eq!(intersection.name().map(|n| n.as_str()), Some("k"));
assert_eq!(union.name().map(|n| n.as_str()), Some("k"));
assert_eq!(difference.name().map(|n| n.as_str()), Some("k"));
assert_eq!(symmetric.name().map(|n| n.as_str()), Some("k"));
// pandas 2.2.3: intersection sort=False (self-order); union/difference/
// symmetric_difference sort=None -> ascending for both-non-empty inputs.
assert_eq!(
intersection.labels.int64_view().unwrap().as_slice(),
&[6, 0]
);
assert_eq!(
union.labels.int64_view().unwrap().as_slice(),
&[-6, 0, 3, 6, 9]
);
assert_eq!(difference.labels.int64_view().unwrap().as_slice(), &[3, 9]);
assert_eq!(
symmetric.labels.int64_view().unwrap().as_slice(),
&[-6, 3, 9]
);
let disjoint = super::RangeIndex::new(20, 26, 2).unwrap().set_name("k");
assert!(left.intersection(&disjoint).is_empty());
assert_eq!(
left.symmetric_difference(&disjoint)
.labels
.int64_view()
.unwrap()
.as_slice(),
&[0, 3, 6, 9, 20, 22, 24]
);
// intersection keeps self-order lazy backing; union/difference/
// symmetric materialize when the ascending sort reorders the
// interleaved descending lattices (pandas sort=None).
assert!(
intersection.labels.materialized.get().is_none(),
"self-order intersection keeps typed lazy backing"
);
}
#[test]
fn range_index_set_ops_return_affine_spans_iatnc() {
let left = super::RangeIndex::new(0, 1_000_000, 1)
.unwrap()
.set_name("k");
let right = super::RangeIndex::new(500_000, 1_500_000, 1)
.unwrap()
.set_name("k");
let intersection = left.intersection(&right);
let union = left.union(&right);
let difference = left.difference(&right);
let symmetric = left.symmetric_difference(&right);
assert_eq!(
intersection.labels.int64_affine_range(),
Some(Int64AffineLabels {
start: 500_000,
step: 1,
len: 500_000,
})
);
assert_eq!(
union.labels.int64_affine_range(),
Some(Int64AffineLabels {
start: 0,
step: 1,
len: 1_500_000,
})
);
assert_eq!(
difference.labels.int64_affine_range(),
Some(Int64AffineLabels {
start: 0,
step: 1,
len: 500_000,
})
);
for output in [&intersection, &union, &difference] {
assert!(
output.labels.materialized.get().is_none(),
"single-span RangeIndex set ops should return lazy affine backing"
);
}
assert_eq!(symmetric.len(), 1_000_000);
assert!(
symmetric.labels.int64_affine_range().is_none(),
"split symmetric_difference should not lie as one affine span"
);
assert_eq!(
symmetric.labels.int64_two_affine.as_deref().copied(),
Some(Int64TwoAffineLabels {
first: Int64AffineLabels {
start: 0,
step: 1,
len: 500_000,
},
second: Int64AffineLabels {
start: 1_000_000,
step: 1,
len: 500_000,
},
})
);
assert!(
symmetric.labels.materialized.get().is_none(),
"split symmetric_difference should carry two lazy Int64 runs"
);
let descending_left = super::RangeIndex::new(9, -3, -3).unwrap().set_name("k");
let descending_right = super::RangeIndex::new(6, -6, -3).unwrap().set_name("k");
assert_eq!(
descending_left
.intersection(&descending_right)
.labels
.int64_affine_range(),
Some(Int64AffineLabels {
start: 6,
step: -3,
len: 3,
})
);
// pandas 2.2.3 union (sort=None) returns ascending [-3, 0, 3, 6, 9] for
// these interleaved descending lattices; reconciling to ascending order
// materializes the labels rather than returning a descending affine span.
// (The aligned-ascending union above still returns a lazy affine span.)
assert_eq!(
descending_left
.union(&descending_right)
.labels
.int64_view()
.unwrap()
.as_slice(),
&[-3, 0, 3, 6, 9]
);
let adjacent_left = super::RangeIndex::new(0, 3, 1).unwrap().set_name("k");
let adjacent_right = super::RangeIndex::new(3, 6, 1).unwrap().set_name("k");
assert_eq!(
adjacent_left
.symmetric_difference(&adjacent_right)
.labels
.int64_affine_range(),
Some(Int64AffineLabels {
start: 0,
step: 1,
len: 6,
})
);
}
#[test]
fn range_index_splice_outputs_keep_typed_backing_uza04169() -> Result<(), super::IndexError> {
let left = super::RangeIndex::new(0, 3, 1).unwrap().set_name("k");
let right = super::RangeIndex::new(10, 12, 1).unwrap().set_name("k");
let inserted = left.insert(1, 99)?;
let appended = left.append(&right);
let deleted = left.delete(1)?;
assert_eq!(inserted.name().map(|n| n.as_str()), Some("k"));
assert_eq!(appended.name().map(|n| n.as_str()), Some("k"));
assert_eq!(deleted.name().map(|n| n.as_str()), Some("k"));
assert_eq!(
inserted.labels.int64_view().unwrap().as_slice(),
&[0, 99, 1, 2]
);
assert_eq!(
appended.labels.int64_view().unwrap().as_slice(),
&[0, 1, 2, 10, 11]
);
assert_eq!(deleted.labels.int64_view().unwrap().as_slice(), &[0, 2]);
assert_eq!(
appended.labels.int64_two_affine.as_deref().copied(),
Some(Int64TwoAffineLabels {
first: Int64AffineLabels {
start: 0,
step: 1,
len: 3,
},
second: Int64AffineLabels {
start: 10,
step: 1,
len: 2,
},
})
);
assert_eq!(
deleted.labels.int64_two_affine.as_deref().copied(),
Some(Int64TwoAffineLabels {
first: Int64AffineLabels {
start: 0,
step: 1,
len: 1,
},
second: Int64AffineLabels {
start: 2,
step: 1,
len: 1,
},
})
);
for output in [&inserted, &appended, &deleted] {
assert!(
output.labels.materialized.get().is_none(),
"RangeIndex splice outputs should keep typed Int64 output backing"
);
}
Ok(())
}
#[test]
fn range_index_splice_uses_direct_values_un6on() -> Result<(), super::IndexError> {
let left = super::RangeIndex::new(9, 0, -4).unwrap().set_name("k");
let right = super::RangeIndex::new(-1, -6, -2).unwrap().set_name("k");
let inserted = left.insert(2, 99)?;
assert_eq!(inserted.name().map(|n| n.as_str()), Some("k"));
assert_eq!(
inserted.labels.int64_view().unwrap().as_slice(),
&[9, 5, 99, 1]
);
let appended = left.append(&right);
assert_eq!(appended.name().map(|n| n.as_str()), Some("k"));
assert_eq!(
appended.labels.int64_view().unwrap().as_slice(),
&[9, 5, 1, -1, -3, -5]
);
assert_eq!(
appended.labels.int64_two_affine.as_deref().copied(),
Some(Int64TwoAffineLabels {
first: Int64AffineLabels {
start: 9,
step: -4,
len: 3,
},
second: Int64AffineLabels {
start: -1,
step: -2,
len: 3,
},
})
);
let mismatched_name = right.set_name("other");
assert_eq!(left.append(&mismatched_name).name(), None);
let deleted = left.delete(1)?;
assert_eq!(deleted.name().map(|n| n.as_str()), Some("k"));
assert_eq!(deleted.labels.int64_view().unwrap().as_slice(), &[9, 1]);
assert_eq!(
deleted.labels.int64_two_affine.as_deref().copied(),
Some(Int64TwoAffineLabels {
first: Int64AffineLabels {
start: 9,
step: -4,
len: 1,
},
second: Int64AffineLabels {
start: 1,
step: -4,
len: 1,
},
})
);
let insert_err = left.insert(4, 0).unwrap_err();
assert!(matches!(
insert_err,
super::IndexError::OutOfBounds {
position: 4,
length: 3
}
));
let delete_err = left.delete(3).unwrap_err();
assert!(matches!(
delete_err,
super::IndexError::OutOfBounds {
position: 3,
length: 3
}
));
for output in [&inserted, &appended, &deleted] {
assert!(
output.labels.materialized.get().is_none(),
"RangeIndex splice should stream direct i64 labels into typed backing"
);
}
Ok(())
}
#[test]
fn datetime_index_take_repeat_isin_match_pandas_bbgg3() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
let dt = super::DatetimeIndex::new(vec![a, b, c]).set_name("ts");
let taken = dt.take(&[2, 0, 0])?;
assert_eq!(taken.values(), vec![Some(c), Some(a), Some(a)]);
assert_eq!(taken.name().map(|n| n.as_str()), Some("ts"));
let oob = dt.take(&[3]).unwrap_err();
assert!(matches!(
oob,
super::IndexError::OutOfBounds {
position: 3,
length: 3
}
));
let repeated = dt.repeat(2);
assert_eq!(
repeated.values(),
vec![Some(a), Some(a), Some(b), Some(b), Some(c), Some(c)]
);
assert_eq!(repeated.name().map(|n| n.as_str()), Some("ts"));
let mask = dt.isin(&[a, c]);
assert_eq!(mask, vec![true, false, true]);
let nat_idx = super::DatetimeIndex::new(vec![i64::MIN, a]);
assert_eq!(nat_idx.isin(&[i64::MIN]), vec![true, false]);
Ok(())
}
#[test]
fn timedelta_index_take_repeat_isin_match_pandas_bbgg3() -> Result<(), super::IndexError> {
let td = super::TimedeltaIndex::new(vec![100_i64, 200, 300]).set_name("d");
let taken = td.take(&[2, 0])?;
assert_eq!(taken.values(), vec![Some(300), Some(100)]);
assert_eq!(taken.name().map(|n| n.as_str()), Some("d"));
assert!(matches!(
td.take(&[7]).unwrap_err(),
super::IndexError::OutOfBounds {
position: 7,
length: 3
}
));
let repeated = td.repeat(2);
assert_eq!(
repeated.values(),
vec![
Some(100),
Some(100),
Some(200),
Some(200),
Some(300),
Some(300)
]
);
let mask = td.isin(&[200, 999]);
assert_eq!(mask, vec![false, true, false]);
Ok(())
}
#[test]
fn period_index_take_repeat_isin_match_pandas_bbgg3() -> Result<(), super::IndexError> {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p2, p3]).set_name("pp");
let taken = pi.take(&[2, 1])?;
assert_eq!(taken.values(), &[p3, p2]);
assert_eq!(taken.name().map(|n| n.as_str()), Some("pp"));
assert!(matches!(
pi.take(&[5]).unwrap_err(),
super::IndexError::OutOfBounds {
position: 5,
length: 3
}
));
let repeated = pi.repeat(2);
assert_eq!(repeated.values(), &[p1, p1, p2, p2, p3, p3]);
let mask = pi.isin(&[p1, p3]);
assert_eq!(mask, vec![true, false, true]);
Ok(())
}
#[test]
fn range_index_take_repeat_isin_match_pandas_bbgg3() -> Result<(), super::IndexError> {
let r = super::RangeIndex::new(0, 5, 1).unwrap();
let taken = r.take(&[2, 4, 0])?;
let labels = int64_labels(&taken);
assert_eq!(labels, vec![2, 4, 0]);
assert!(matches!(
r.take(&[10]).unwrap_err(),
super::IndexError::OutOfBounds {
position: 10,
length: 5
}
));
let repeated = r.repeat(2);
let repeat_labels = int64_labels(&repeated);
assert_eq!(repeat_labels, vec![0, 0, 1, 1, 2, 2, 3, 3, 4, 4]);
let mask = r.isin(&[1, 3, 99]);
assert_eq!(mask, vec![false, true, false, true, false]);
Ok(())
}
#[test]
fn range_index_isin_iterates_direct_values_djhvr() {
let descending = super::RangeIndex::new(10, 0, -2).unwrap();
assert_eq!(
descending.isin(&[4, 10, 4, 99]),
vec![true, false, false, true, false]
);
let empty = super::RangeIndex::new(5, 5, 1).unwrap();
assert!(empty.isin(&[5]).is_empty());
}
#[test]
fn range_index_isin_marks_positions_without_hash_ruthb() {
let ascending = super::RangeIndex::new(-2, 5, 2).unwrap();
assert_eq!(
ascending.isin(&[4, -2, 4, 99, 1]),
vec![true, false, false, true]
);
let descending = super::RangeIndex::new(9, -3, -3).unwrap();
assert_eq!(
descending.isin(&[0, 12, 9, 0, -3]),
vec![true, false, false, true]
);
let empty = super::RangeIndex::new(3, 3, 1).unwrap();
assert!(empty.isin(&[3, 99]).is_empty());
}
#[test]
fn range_index_any_all_closed_form_taw0w() {
let empty = super::RangeIndex::new(5, 5, 1).unwrap();
assert!(!empty.any());
assert!(empty.all());
let singleton_zero = super::RangeIndex::new(0, 1, 1).unwrap();
assert!(!singleton_zero.any());
assert!(!singleton_zero.all());
let ascending_with_zero = super::RangeIndex::new(-2, 3, 1).unwrap();
assert!(ascending_with_zero.any());
assert!(!ascending_with_zero.all());
let descending_with_zero = super::RangeIndex::new(4, -2, -2).unwrap();
assert!(descending_with_zero.any());
assert!(!descending_with_zero.all());
let nonzero = super::RangeIndex::new(2, 8, 2).unwrap();
assert!(nonzero.any());
assert!(nonzero.all());
}
#[test]
fn range_index_groupby_builds_direct_buckets_wvlfh() {
let descending = super::RangeIndex::new(8, 0, -2).unwrap();
let groups = descending.groupby();
assert_eq!(groups[&IndexLabel::Int64(8)], vec![0]);
assert_eq!(groups[&IndexLabel::Int64(6)], vec![1]);
assert_eq!(groups[&IndexLabel::Int64(4)], vec![2]);
assert_eq!(groups[&IndexLabel::Int64(2)], vec![3]);
assert_eq!(groups.len(), 4);
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert!(empty.groupby().is_empty());
}
#[test]
fn range_index_map_iterates_direct_labels_80jbg() {
let range = super::RangeIndex::new(5, -1, -2).unwrap().set_name("r");
let mapped = range.map(|label| match label {
IndexLabel::Int64(value) => IndexLabel::Utf8(format!("v{value}")),
other => other.clone(),
});
assert_eq!(mapped.name().map(|n| n.as_str()), Some("r"));
assert_eq!(
mapped.labels(),
&[
IndexLabel::Utf8("v5".to_owned()),
IndexLabel::Utf8("v3".to_owned()),
IndexLabel::Utf8("v1".to_owned())
]
);
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert!(empty.map(|label| label.clone()).is_empty());
}
#[test]
fn range_index_asof_scans_direct_labels_ue0y9() {
let ascending = super::RangeIndex::new(2, 10, 2).unwrap();
assert_eq!(
ascending.asof(&IndexLabel::Int64(7)),
Some(IndexLabel::Int64(6))
);
assert_eq!(ascending.asof(&IndexLabel::Int64(1)), None);
assert_eq!(
ascending.asof(&IndexLabel::Utf8("x".to_owned())),
Some(IndexLabel::Int64(8))
);
let descending = super::RangeIndex::new(8, 0, -2).unwrap();
assert_eq!(descending.asof(&IndexLabel::Int64(7)), None);
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert_eq!(empty.asof(&IndexLabel::Int64(0)), None);
}
#[test]
fn range_index_asof_uses_closed_form_for_ascending_i64_jlv2o() {
let range = super::RangeIndex::new(-7, 20, 4).unwrap();
for needle in [-20, -7, -6, 0, 1, 17, 18, 99] {
let key = IndexLabel::Int64(needle);
assert_eq!(range.asof(&key), range.to_flat_index().asof(&key));
}
let singleton = super::RangeIndex::new(42, 100, 1000).unwrap();
assert_eq!(
singleton.asof(&IndexLabel::Int64(42)),
Some(IndexLabel::Int64(42))
);
assert_eq!(singleton.asof(&IndexLabel::Int64(41)), None);
let descending = super::RangeIndex::new(8, 0, -2).unwrap();
assert_eq!(descending.asof(&IndexLabel::Int64(7)), None);
let empty = super::RangeIndex::new(5, 5, 1).unwrap();
assert_eq!(empty.asof(&IndexLabel::Int64(5)), None);
}
#[test]
fn range_index_drop_filters_direct_values_ayakf() {
let range = super::RangeIndex::new(8, 0, -2).unwrap().set_name("r");
let dropped = range.drop(&[
IndexLabel::Int64(6),
IndexLabel::Utf8("6".to_owned()),
IndexLabel::Int64(2),
]);
assert_eq!(dropped.name().map(|n| n.as_str()), Some("r"));
assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[8, 4]);
assert!(
dropped.labels.materialized.get().is_none(),
"RangeIndex::drop should keep typed Int64 output backing"
);
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert!(empty.drop(&[IndexLabel::Int64(0)]).is_empty());
}
#[test]
fn range_index_drop_marks_positions_without_hash_uza04155() {
let range = super::RangeIndex::new(9, -3, -3).unwrap().set_name("r");
let dropped = range.drop(&[
IndexLabel::Int64(6),
IndexLabel::Int64(6),
IndexLabel::Utf8("6".to_owned()),
IndexLabel::Int64(99),
IndexLabel::Int64(0),
]);
assert_eq!(dropped.name().map(|n| n.as_str()), Some("r"));
assert_eq!(dropped.labels.int64_view().unwrap().as_slice(), &[9, 3]);
assert!(
dropped.labels.materialized.get().is_none(),
"RangeIndex::drop should write a typed Int64 result without object materialization"
);
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert!(
empty
.drop(&[IndexLabel::Int64(0), IndexLabel::Utf8("0".to_owned())])
.is_empty()
);
}
#[test]
fn range_index_sortlevel_builds_direct_output_puano() {
let descending = super::RangeIndex::new(8, 0, -2).unwrap().set_name("r");
let (sorted, order) = descending.sortlevel();
assert_eq!(order, vec![3, 2, 1, 0]);
assert_eq!(sorted.name().map(|n| n.as_str()), Some("r"));
assert_eq!(
sorted.labels.int64_view().unwrap().as_slice(),
&[2, 4, 6, 8]
);
assert!(
sorted.labels.materialized.get().is_none(),
"RangeIndex::sortlevel should keep typed Int64 output backing"
);
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
let (empty_sorted, empty_order) = empty.sortlevel();
assert!(empty_sorted.is_empty());
assert!(empty_order.is_empty());
}
#[test]
fn range_index_join_direct_i64_matches_flat_oracle_uza04190() -> Result<(), super::IndexError> {
let range = super::RangeIndex::new(9, 0, -3).unwrap().set_name("k");
let other = super::Index::from_i64_values(vec![6, 12, 6, 0]).set_name("k");
let inner = range.join(&other, "inner")?;
assert_eq!(inner.name().map(|n| n.as_str()), Some("k"));
assert_eq!(inner.labels.int64_view().unwrap().as_slice(), &[6]);
assert!(
inner.labels.materialized.get().is_none(),
"RangeIndex::join(inner) should keep typed Int64 output backing"
);
let outer = range.join(&other, "outer")?;
assert_eq!(outer.name().map(|n| n.as_str()), Some("k"));
assert_eq!(
outer.labels.int64_view().unwrap().as_slice(),
&[9, 6, 6, 3, 12, 0]
);
assert!(
outer.labels.materialized.get().is_none(),
"RangeIndex::join(outer) should keep typed Int64 output backing"
);
for how in ["left", "right", "inner", "outer"] {
let direct = range.join(&other, how)?;
let oracle = range.to_flat_index().join(&other, how)?;
assert_eq!(direct.name(), oracle.name(), "name mismatch for {how}");
assert_eq!(direct, oracle, "label mismatch for {how}");
}
let seq_range = super::RangeIndex::new(0, 6, 1).unwrap().set_name("k");
let seq_other = super::Index::from_i64_values(vec![3, 4, 5, 6, 7]).set_name("k");
let seq_inner = seq_range.join(&seq_other, "inner")?;
assert_eq!(
seq_inner.labels.int64_view().unwrap().as_slice(),
&[3, 4, 5]
);
assert!(
seq_inner.labels.materialized.get().is_none(),
"same-lattice RangeIndex::join(inner) should stay lazy"
);
let seq_outer = seq_range.join(&seq_other, "outer")?;
assert_eq!(
seq_outer.labels.int64_view().unwrap().as_slice(),
&[0, 1, 2, 3, 4, 5, 6, 7]
);
assert!(
seq_outer.labels.materialized.get().is_none(),
"same-lattice RangeIndex::join(outer) should stay lazy"
);
for how in ["inner", "outer"] {
assert_eq!(
seq_range.join(&seq_other, how)?,
seq_range.to_flat_index().join(&seq_other, how)?
);
}
let mismatched_name = other.set_name("other");
assert_eq!(range.join(&mismatched_name, "inner")?.name(), None);
assert_eq!(range.join(&mismatched_name, "outer")?.name(), None);
let mixed = super::Index::new(vec![
super::IndexLabel::Int64(6),
super::IndexLabel::Utf8("x".to_owned()),
]);
assert_eq!(
range.join(&mixed, "inner")?,
range.to_flat_index().join(&mixed, "inner")?
);
assert!(matches!(
range.join(&other, "sideways"),
Err(super::IndexError::InvalidArgument(message))
if message == "join: how must be 'left', 'right', 'inner', or 'outer', got \"sideways\""
));
Ok(())
}
#[test]
fn range_index_frame_series_views_materialize_directly_u2jv1() {
let descending = super::RangeIndex::new(6, 0, -2).unwrap();
assert_eq!(
descending.to_frame(),
vec![
vec![IndexLabel::Int64(6)],
vec![IndexLabel::Int64(4)],
vec![IndexLabel::Int64(2)]
]
);
assert_eq!(
descending.to_series(),
vec![
(IndexLabel::Int64(6), IndexLabel::Int64(6)),
(IndexLabel::Int64(4), IndexLabel::Int64(4)),
(IndexLabel::Int64(2), IndexLabel::Int64(2))
]
);
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert!(empty.to_frame().is_empty());
assert!(empty.to_series().is_empty());
}
#[test]
fn period_index_forwarder_methods_match_pandas_zke9k() {
use fp_types::{Period, PeriodFreq};
let p1 = Period::new(10, PeriodFreq::Monthly);
let p2 = Period::new(11, PeriodFreq::Monthly);
let p3 = Period::new(12, PeriodFreq::Monthly);
let pi = super::PeriodIndex::new(vec![p1, p2, p1, p3, p2, p1]).set_name("p");
let unique = pi.unique();
assert_eq!(unique.values(), &[p1, p2, p3]);
assert_eq!(unique.name().map(|n| n.as_str()), Some("p"));
let dup_first = pi.duplicated(super::DuplicateKeep::First);
assert_eq!(dup_first, vec![false, false, true, false, true, true]);
let dup_last = pi.duplicated(super::DuplicateKeep::Last);
assert_eq!(dup_last, vec![true, true, true, false, false, false]);
let dup_none = pi.duplicated(super::DuplicateKeep::None);
// None marks every position whose value occurs >1 time.
assert_eq!(dup_none, vec![true, true, true, false, true, true]);
let dropped = pi.drop_duplicates();
assert_eq!(dropped.values(), &[p1, p2, p3]);
let counts = pi.value_counts();
let total: usize = counts.iter().map(|(_, n)| n).sum();
assert_eq!(total, pi.len());
// First entry is the most frequent (p1 with 3 occurrences).
assert_eq!(counts[0].1, 3);
let p1_count = counts
.iter()
.find_map(|(period, n)| (*period == p1).then_some(*n))
.expect("p1 should be counted");
assert_eq!(p1_count, 3);
let (codes, factor_uniques) = pi.factorize();
assert_eq!(codes, vec![0, 1, 0, 2, 1, 0]);
assert_eq!(factor_uniques.values(), &[p1, p2, p3]);
}
#[test]
fn period_index_unique_handles_empty_zke9k() {
let pi = super::PeriodIndex::new(Vec::new());
assert!(pi.unique().is_empty());
assert!(pi.drop_duplicates().is_empty());
assert!(pi.value_counts().is_empty());
let (codes, uniques) = pi.factorize();
assert!(codes.is_empty());
assert!(uniques.is_empty());
}
fn period_index_is_unique_hash_former_dcqru(index: &super::PeriodIndex) -> bool {
let unique: super::FxHashSet<&fp_types::Period> = index.values().iter().collect();
unique.len() == index.len()
}
#[test]
fn period_index_is_unique_monotonic_matches_hash_fallback_dcqru() {
use fp_types::{Period, PeriodFreq};
let cases = [
Vec::new(),
vec![Period::new(7, PeriodFreq::Monthly)],
vec![
Period::new(1, PeriodFreq::Monthly),
Period::new(2, PeriodFreq::Monthly),
Period::new(3, PeriodFreq::Monthly),
],
vec![
Period::new(3, PeriodFreq::Monthly),
Period::new(2, PeriodFreq::Monthly),
Period::new(1, PeriodFreq::Monthly),
],
vec![
Period::new(1, PeriodFreq::Monthly),
Period::new(2, PeriodFreq::Monthly),
Period::new(2, PeriodFreq::Monthly),
],
vec![
Period::new(2, PeriodFreq::Monthly),
Period::new(1, PeriodFreq::Monthly),
Period::new(3, PeriodFreq::Monthly),
],
vec![
Period::new(1, PeriodFreq::Monthly),
Period::new(1, PeriodFreq::Daily),
Period::new(2, PeriodFreq::Monthly),
],
vec![
Period::new(1, PeriodFreq::Monthly),
Period::new(1, PeriodFreq::Daily),
Period::new(1, PeriodFreq::Monthly),
],
];
for values in cases {
let index = super::PeriodIndex::new(values);
assert_eq!(
index.is_unique(),
period_index_is_unique_hash_former_dcqru(&index)
);
}
}
#[test]
#[ignore = "foreground release attribution harness"]
fn period_index_is_unique_monotonic_ab_dcqru() {
use fp_types::{Period, PeriodFreq};
fn elapsed(index: &super::PeriodIndex, candidate: bool) -> u128 {
let started = std::time::Instant::now();
let result = if candidate {
std::hint::black_box(index).is_unique()
} else {
period_index_is_unique_hash_former_dcqru(std::hint::black_box(index))
};
std::hint::black_box(result);
started.elapsed().as_nanos()
}
fn percentile(samples: &mut [u128], pct: usize) -> u128 {
samples.sort_unstable();
let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
samples[rank]
}
let index =
super::PeriodIndex::from_range(Period::new(-100_000, PeriodFreq::Minutely), 200_000);
assert!(index.is_unique());
assert!(period_index_is_unique_hash_former_dcqru(&index));
for _ in 0..2 {
std::hint::black_box(elapsed(&index, false));
std::hint::black_box(elapsed(&index, true));
}
let mut former_a = Vec::with_capacity(9);
let mut former_b = Vec::with_capacity(9);
let mut candidate_a = Vec::with_capacity(9);
let mut candidate_b = Vec::with_capacity(9);
for block in 0_usize..9 {
if block.is_multiple_of(2) {
former_a.push(elapsed(&index, false));
candidate_a.push(elapsed(&index, true));
candidate_b.push(elapsed(&index, true));
former_b.push(elapsed(&index, false));
} else {
candidate_b.push(elapsed(&index, true));
former_b.push(elapsed(&index, false));
former_a.push(elapsed(&index, false));
candidate_a.push(elapsed(&index, true));
}
}
let former_a_p50 = percentile(&mut former_a, 50);
let former_b_p50 = percentile(&mut former_b, 50);
let candidate_a_p50 = percentile(&mut candidate_a, 50);
let candidate_b_p50 = percentile(&mut candidate_b, 50);
let former_p50 = (former_a_p50 + former_b_p50) as f64 / 2.0;
let candidate_p50 = (candidate_a_p50 + candidate_b_p50) as f64 / 2.0;
eprintln!(
"PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION len={} former_a_p50_ns={former_a_p50} former_b_p50_ns={former_b_p50} candidate_a_p50_ns={candidate_a_p50} candidate_b_p50_ns={candidate_b_p50} ratio={:.6}",
index.len(),
former_p50 / candidate_p50,
);
eprintln!("PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION former_a_ns={former_a:?}");
eprintln!("PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION former_b_ns={former_b:?}");
eprintln!("PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION candidate_a_ns={candidate_a:?}");
eprintln!("PERIOD_INDEX_IS_UNIQUE_ATTRIBUTION candidate_b_ns={candidate_b:?}");
}
#[test]
fn categorical_index_missingness_methods_are_closed_form_c0knj() {
let cat = super::CategoricalIndex::from_values(
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
false,
);
assert_eq!(cat.isnull(), vec![false, false, false]);
assert_eq!(cat.notnull(), vec![true, true, true]);
assert!(!cat.hasnans());
let dropped = cat.dropna();
assert_eq!(dropped.labels(), cat.labels());
let filled = cat
.fillna(&IndexLabel::from("z"))
.expect("fillna of an index with no missing label");
assert_eq!(filled.labels(), cat.labels());
let empty = super::CategoricalIndex::from_values(Vec::<String>::new(), false);
assert_eq!(empty.isnull(), Vec::<bool>::new());
assert!(!empty.hasnans());
}
/// pandas 2.2.3: a CategoricalIndex holds any label kind and missing
/// labels (br-frankenpandas-lztvp; it held non-missing text only).
#[test]
fn categorical_index_typed_and_missing_labels_like_pandas_lztvp()
-> Result<(), super::IndexError> {
let nan = || IndexLabel::Null(fp_types::NullKind::NaN);
// CategoricalIndex([3, 1, 3, 2], categories=[1, 2, 3]).
let ints = super::CategoricalIndex::with_categories(
vec![3_i64, 1, 3, 2],
vec![1_i64, 2, 3],
false,
)?;
assert_eq!(ints.codes(), vec![Some(2), Some(0), Some(2), Some(1)]);
assert_eq!(ints.categories()[0], IndexLabel::Int64(1));
assert_eq!(ints.get_loc(&IndexLabel::Int64(2))?, 3);
assert_eq!(
ints.value_counts(),
vec![
(IndexLabel::Int64(3), 2),
(IndexLabel::Int64(1), 1),
(IndexLabel::Int64(2), 1)
]
);
// A label outside the categories (and a missing one) is NaN.
let text = super::CategoricalIndex::with_categories(
vec![
IndexLabel::from("b"),
nan(),
IndexLabel::from("z"),
IndexLabel::from("a"),
],
vec!["a", "b"],
false,
)?;
assert_eq!(text.isna(), vec![false, true, true, false]);
assert!(text.hasnans());
assert_eq!(text.codes(), vec![Some(1), None, None, Some(0)]);
assert_eq!(text.nunique(), 2);
assert_eq!(
text.value_counts(),
vec![(IndexLabel::from("b"), 1), (IndexLabel::from("a"), 1)]
);
// factorize: NaN is -1 and no unique.
let (codes, uniques) = text.factorize();
assert_eq!(codes, vec![0, -1, -1, 1]);
assert_eq!(
uniques.labels(),
&[IndexLabel::from("b"), IndexLabel::from("a")]
);
// Sorting puts NaN last; dropna drops it; fillna with a category fills.
assert_eq!(
text.sort_values().labels(),
&[IndexLabel::from("a"), IndexLabel::from("b"), nan(), nan()]
);
assert_eq!(
text.dropna().labels(),
&[IndexLabel::from("b"), IndexLabel::from("a")]
);
assert_eq!(
text.fillna(&IndexLabel::from("a"))?.labels(),
&[
IndexLabel::from("b"),
IndexLabel::from("a"),
IndexLabel::from("a"),
IndexLabel::from("a")
]
);
// Negatives: filling with a new category, inserting one, and
// repeated or missing categories are refused.
assert!(text.fillna(&IndexLabel::from("z")).is_err());
assert!(text.insert(0, &IndexLabel::from("z")).is_err());
assert!(
super::CategoricalIndex::with_categories(vec!["a"], vec!["a", "a"], false).is_err()
);
assert!(super::CategoricalIndex::with_categories(vec!["a"], vec![nan()], false).is_err());
Ok(())
}
#[test]
fn categorical_index_append_delete_insert_repeat_match_pandas_tns52()
-> Result<(), super::IndexError> {
let cat = super::CategoricalIndex::with_categories(
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
vec![
"a".to_owned(),
"b".to_owned(),
"c".to_owned(),
"d".to_owned(),
],
false,
)?
.set_name("level");
// append: merge categories.
let other = super::CategoricalIndex::with_categories(
vec!["d".to_owned()],
vec!["d".to_owned(), "e".to_owned()],
false,
)?
.set_name("level");
let merged = cat.append(&other);
assert_eq!(
merged.labels(),
vec![
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("c"),
IndexLabel::from("d")
]
.as_slice()
);
assert_eq!(merged.name().map(|n| n.as_str()), Some("level"));
assert!(merged.categories().contains(&IndexLabel::from("e")));
// delete OOB.
assert!(matches!(
cat.delete(99).unwrap_err(),
super::IndexError::OutOfBounds {
position: 99,
length: 3
}
));
let trimmed = cat.delete(0)?;
assert_eq!(
trimmed.labels(),
vec![IndexLabel::from("b"), IndexLabel::from("c")].as_slice()
);
// insert.
let inserted = cat.insert(1, &IndexLabel::from("d"))?;
assert_eq!(
inserted.labels(),
vec![
IndexLabel::from("a"),
IndexLabel::from("d"),
IndexLabel::from("b"),
IndexLabel::from("c")
]
.as_slice()
);
assert!(cat.insert(1, &IndexLabel::from("zzz")).is_err());
// repeat.
let repeated = cat.repeat(2);
assert_eq!(repeated.labels().len(), 6);
assert_eq!(repeated.labels()[0], IndexLabel::from("a"));
assert_eq!(repeated.labels()[1], IndexLabel::from("a"));
assert_eq!(repeated.labels()[2], IndexLabel::from("b"));
Ok(())
}
#[test]
fn categorical_index_slice_locs_indexer_match_pandas_y93vb() -> Result<(), super::IndexError> {
let cat = super::CategoricalIndex::with_categories(
vec![
"a".to_owned(),
"b".to_owned(),
"c".to_owned(),
"d".to_owned(),
],
vec![
"a".to_owned(),
"b".to_owned(),
"c".to_owned(),
"d".to_owned(),
],
true,
)?;
assert_eq!(
cat.slice_locs(&IndexLabel::from("b"), &IndexLabel::from("c"))?,
(1, 3)
);
assert_eq!(
cat.slice_indexer(&IndexLabel::from("b"), &IndexLabel::from("c"))?,
1..3
);
assert_eq!(
cat.slice_locs(&IndexLabel::from("a"), &IndexLabel::from("d"))?,
(0, 4)
);
// Non-monotonic rejects.
let unsorted = super::CategoricalIndex::from_values(
vec!["c".to_owned(), "a".to_owned(), "b".to_owned()],
false,
);
assert!(
unsorted
.slice_locs(&IndexLabel::from("a"), &IndexLabel::from("c"))
.is_err()
);
Ok(())
}
#[test]
fn categorical_index_searchsorted_set_ops_match_pandas_cmvs7() -> Result<(), super::IndexError>
{
let cat = super::CategoricalIndex::with_categories(
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
true,
)?;
// searchsorted on the sorted utf8 index.
assert_eq!(cat.searchsorted(&IndexLabel::from("b"), "left")?, 1);
assert_eq!(cat.searchsorted(&IndexLabel::from("c"), "right")?, 3);
assert!(cat.searchsorted(&IndexLabel::from("b"), "middle").is_err());
let other = super::CategoricalIndex::from_values(
vec!["b".to_owned(), "c".to_owned(), "d".to_owned()],
false,
);
assert_eq!(
cat.intersection(&other).labels(),
vec![IndexLabel::from("b"), IndexLabel::from("c")].as_slice()
);
assert_eq!(
cat.union(&other).labels(),
vec![
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("c"),
IndexLabel::from("d"),
]
.as_slice()
);
assert_eq!(
cat.difference(&other).labels(),
vec![IndexLabel::from("a")].as_slice()
);
// symmetric_difference: a (only in cat) + d (only in other).
assert_eq!(
cat.symmetric_difference(&other).labels(),
vec![IndexLabel::from("a"), IndexLabel::from("d")].as_slice()
);
Ok(())
}
#[test]
fn categorical_index_argmax_argmin_match_pandas_d46wi() -> Result<(), super::IndexError> {
let cat = super::CategoricalIndex::with_categories(
vec!["b".to_owned(), "a".to_owned(), "c".to_owned()],
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
true,
)?;
assert_eq!(cat.argmax()?, 2);
assert_eq!(cat.argmin()?, 1);
let empty = super::CategoricalIndex::from_values(Vec::<String>::new(), false);
assert!(empty.argmax().is_err());
assert!(empty.argmin().is_err());
Ok(())
}
#[test]
fn categorical_index_forwarders_match_pandas_e2p82() -> Result<(), super::IndexError> {
let cat = super::CategoricalIndex::with_categories(
vec![
"b".to_owned(),
"a".to_owned(),
"c".to_owned(),
"a".to_owned(),
],
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
true,
)?;
// argsort: positions sorted by lexicographic label.
let positions = cat.argsort();
let labels: Vec<&IndexLabel> = positions.iter().map(|&p| &cat.labels()[p]).collect();
for w in labels.windows(2) {
assert!(w[0] <= w[1]);
}
// take swaps positions.
let taken = cat.take(&[2, 0, 0])?;
assert_eq!(
taken.labels(),
vec![
IndexLabel::from("c"),
IndexLabel::from("b"),
IndexLabel::from("b")
]
.as_slice()
);
assert!(matches!(
cat.take(&[7]).unwrap_err(),
super::IndexError::OutOfBounds {
position: 7,
length: 4
}
));
// isin membership.
assert_eq!(
cat.isin(&[IndexLabel::from("a"), IndexLabel::from("z")]),
vec![false, true, false, true]
);
// get_loc finds first; missing rejects.
assert_eq!(cat.get_loc(&IndexLabel::from("c"))?, 2);
assert!(cat.get_loc(&IndexLabel::from("zzz")).is_err());
// min/max with ordered=true uses category order.
assert_eq!(cat.min(), Some(&IndexLabel::from("a")));
assert_eq!(cat.max(), Some(&IndexLabel::from("c")));
// Empty.
let empty = super::CategoricalIndex::from_values(Vec::<String>::new(), false);
assert_eq!(empty.min(), None);
assert_eq!(empty.max(), None);
assert!(empty.argsort().is_empty());
Ok(())
}
#[test]
fn categorical_index_category_management_match_pandas_zy2vd() -> Result<(), super::IndexError> {
let cat = super::CategoricalIndex::with_categories(
vec!["a".to_owned(), "b".to_owned()],
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
false,
)?;
// as_ordered / as_unordered.
assert!(cat.as_ordered().ordered());
assert!(!cat.as_ordered().as_unordered().ordered());
// add_categories: appends "d".
let added = cat.add_categories(vec!["d".to_owned()])?;
assert_eq!(
added.categories(),
vec![
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("c"),
IndexLabel::from("d")
]
.as_slice()
);
// Adding a duplicate rejects.
assert!(cat.add_categories(vec!["a".to_owned()]).is_err());
// remove_categories drops "c" (unused).
let pruned = cat.remove_categories(&[IndexLabel::from("c")])?;
assert_eq!(
pruned.categories(),
vec![IndexLabel::from("a"), IndexLabel::from("b")].as_slice()
);
// Removing a category that's still in use makes its labels NaN,
// as pandas' remove_categories.
let removed_in_use = cat.remove_categories(&[IndexLabel::from("a")])?;
assert_eq!(
removed_in_use.labels(),
vec![
IndexLabel::Null(fp_types::NullKind::NaN),
IndexLabel::from("b")
]
.as_slice()
);
assert!(removed_in_use.labels()[0].is_missing());
assert_eq!(
removed_in_use.categories(),
vec![IndexLabel::from("b"), IndexLabel::from("c")].as_slice()
);
// Removing a missing category rejects.
assert!(cat.remove_categories(&[IndexLabel::from("zzz")]).is_err());
// remove_unused_categories trims "c" automatically.
let trimmed = cat.remove_unused_categories();
assert_eq!(
trimmed.categories(),
vec![IndexLabel::from("a"), IndexLabel::from("b")].as_slice()
);
// set_categories: extending to {a, b, c, d}.
let extended = cat.set_categories(vec![
"a".to_owned(),
"b".to_owned(),
"c".to_owned(),
"d".to_owned(),
])?;
assert_eq!(extended.categories().len(), 4);
// set_categories dropping a current label's category makes that
// label NaN, as pandas' set_categories.
let narrowed = cat.set_categories(vec!["b".to_owned(), "c".to_owned()])?;
assert_eq!(
narrowed.labels(),
vec![
IndexLabel::Null(fp_types::NullKind::NaN),
IndexLabel::from("b")
]
.as_slice()
);
assert!(narrowed.labels()[0].is_missing());
assert_eq!(
narrowed.categories(),
vec![IndexLabel::from("b"), IndexLabel::from("c")].as_slice()
);
// A duplicate among the new categories rejects.
assert!(
cat.set_categories(vec!["a".to_owned(), "a".to_owned()])
.is_err()
);
// rename_categories: a→A, b→B, c→C.
let renamed =
cat.rename_categories(vec!["A".to_owned(), "B".to_owned(), "C".to_owned()])?;
assert_eq!(
renamed.labels(),
vec![IndexLabel::from("A"), IndexLabel::from("B")].as_slice()
);
assert_eq!(
renamed.categories(),
vec![
IndexLabel::from("A"),
IndexLabel::from("B"),
IndexLabel::from("C")
]
.as_slice()
);
// Wrong length rejects.
assert!(cat.rename_categories(vec!["X".to_owned()]).is_err());
// reorder_categories: permutation passes; ordered flag flips.
let reordered =
cat.reorder_categories(vec!["c".to_owned(), "b".to_owned(), "a".to_owned()], true)?;
assert!(reordered.ordered());
assert_eq!(
reordered.categories(),
vec![
IndexLabel::from("c"),
IndexLabel::from("b"),
IndexLabel::from("a")
]
.as_slice()
);
// Non-permutation rejects.
assert!(
cat.reorder_categories(vec!["a".to_owned(), "b".to_owned(), "x".to_owned()], false)
.is_err()
);
// Duplicate-bearing input rejects.
assert!(
cat.reorder_categories(vec!["a".to_owned(), "a".to_owned(), "b".to_owned()], false)
.is_err()
);
Ok(())
}
#[test]
fn categorical_index_forwarder_methods_match_pandas_i1q1c() {
let labels = vec![
"low".to_owned(),
"high".to_owned(),
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"low".to_owned(),
];
let categorical =
super::CategoricalIndex::from_values(labels.clone(), false).set_name("level");
// unique: first-seen low, high, med.
let unique = categorical.unique();
assert_eq!(
unique.labels(),
vec![
IndexLabel::from("low"),
IndexLabel::from("high"),
IndexLabel::from("med")
]
.as_slice()
);
assert_eq!(unique.name().map(|n| n.as_str()), Some("level"));
// duplicated keep=First: positions 2, 4, 5 are duplicates of earlier.
let dup_first = categorical.duplicated(super::DuplicateKeep::First);
assert_eq!(dup_first, vec![false, false, true, false, true, true]);
// drop_duplicates returns same as unique.
let dropped = categorical.drop_duplicates();
assert_eq!(dropped.labels(), unique.labels());
// value_counts: low=3, high=2, med=1; total = 6 = len.
let counts = categorical.value_counts();
let total: usize = counts.iter().map(|(_, n)| n).sum();
assert_eq!(total, categorical.len());
let low_count = counts
.iter()
.find_map(|(label, n)| (*label == IndexLabel::from("low")).then_some(*n))
.expect("low should be counted");
assert_eq!(low_count, 3);
// First entry is the most frequent (descending sort).
assert_eq!(counts[0].1, 3);
// factorize: codes encode first-seen positions; uniques == unique().
let (codes, factor_uniques) = categorical.factorize();
assert_eq!(codes.len(), categorical.len());
assert_eq!(codes, vec![0, 1, 0, 2, 1, 0]);
assert_eq!(factor_uniques.labels(), unique.labels());
}
#[test]
fn categorical_index_unique_preserves_categories_and_ordered_i1q1c() {
let labels = vec!["a".to_owned(), "b".to_owned(), "a".to_owned()];
let categories = vec![
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("c"),
];
let cat = super::CategoricalIndex::with_categories(labels, categories.clone(), true)
.expect("with_categories");
let unique = cat.unique();
assert_eq!(unique.categories(), categories.as_slice());
assert!(unique.ordered());
}
#[test]
fn categorical_index_monotonic_scans_ranks_without_codes_vec_uza04196() {
let increasing = super::CategoricalIndex::with_categories(
vec![
"bronze".to_owned(),
"silver".to_owned(),
"silver".to_owned(),
"gold".to_owned(),
],
vec!["bronze".to_owned(), "silver".to_owned(), "gold".to_owned()],
true,
)
.expect("categorical index");
assert!(increasing.is_monotonic_increasing());
assert!(!increasing.is_monotonic_decreasing());
let mut increasing_without_codes = increasing.clone();
increasing_without_codes.category_codes = None;
assert_eq!(
increasing_without_codes.is_monotonic_increasing(),
increasing.is_monotonic_increasing()
);
assert_eq!(
increasing_without_codes.is_monotonic_decreasing(),
increasing.is_monotonic_decreasing()
);
let mut increasing_malformed_codes = increasing.clone();
increasing_malformed_codes.category_codes = Some(vec![usize::MAX; increasing.len()]);
assert_eq!(
increasing_malformed_codes.is_monotonic_increasing(),
increasing_without_codes.is_monotonic_increasing()
);
assert_eq!(
increasing_malformed_codes.is_monotonic_decreasing(),
increasing_without_codes.is_monotonic_decreasing()
);
let decreasing = super::CategoricalIndex::with_categories(
vec![
"gold".to_owned(),
"silver".to_owned(),
"silver".to_owned(),
"bronze".to_owned(),
],
vec!["bronze".to_owned(), "silver".to_owned(), "gold".to_owned()],
true,
)
.expect("categorical index");
assert!(!decreasing.is_monotonic_increasing());
assert!(decreasing.is_monotonic_decreasing());
let invalid = super::CategoricalIndex {
labels: vec![IndexLabel::from("missing"), IndexLabel::from("bronze")],
categories: vec![IndexLabel::from("bronze")],
ordered: true,
name: None,
category_codes: None,
};
let codes = invalid.codes();
assert_eq!(codes, vec![None, Some(0)]);
assert_eq!(
invalid.is_monotonic_increasing(),
codes.windows(2).all(|window| window[0] <= window[1])
);
assert_eq!(
invalid.is_monotonic_decreasing(),
codes.windows(2).all(|window| window[0] >= window[1])
);
}
#[test]
fn categorical_index_unique_nunique_use_rank_bitset_uza04197() {
let categories = vec![
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"unused".to_owned(),
];
let repeated = super::CategoricalIndex::with_categories(
vec![
"low".to_owned(),
"high".to_owned(),
"low".to_owned(),
"med".to_owned(),
],
categories.clone(),
true,
)
.expect("categorical index");
assert!(repeated.category_rank_unique_scan_is_bounded());
assert!(!repeated.is_unique());
assert!(repeated.has_duplicates());
assert_eq!(repeated.nunique(), 3);
let mut without_codes = repeated.clone();
without_codes.category_codes = None;
assert_eq!(without_codes.is_unique(), repeated.is_unique());
assert_eq!(without_codes.nunique(), repeated.nunique());
let mut malformed_codes = repeated.clone();
malformed_codes.category_codes = Some(vec![usize::MAX; repeated.len()]);
assert_eq!(malformed_codes.is_unique(), repeated.is_unique());
assert_eq!(malformed_codes.nunique(), repeated.nunique());
let unique = super::CategoricalIndex::with_categories(
vec!["high".to_owned(), "low".to_owned(), "med".to_owned()],
categories,
true,
)
.expect("categorical index");
assert!(unique.is_unique());
assert!(!unique.has_duplicates());
assert_eq!(unique.nunique(), 3);
let invalid = super::CategoricalIndex {
labels: vec![
IndexLabel::from("ghost"),
IndexLabel::from("low"),
IndexLabel::from("ghost"),
IndexLabel::from("other"),
IndexLabel::from("low"),
],
categories: vec![IndexLabel::from("low")],
ordered: false,
name: None,
category_codes: None,
};
let mut oracle = std::collections::HashSet::<&IndexLabel>::new();
for label in invalid.labels() {
oracle.insert(label);
}
assert_eq!(invalid.nunique(), oracle.len());
assert_eq!(invalid.is_unique(), oracle.len() == invalid.len());
let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
let sparse = super::CategoricalIndex {
labels: vec![
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("a"),
],
categories: large_categories,
ordered: false,
name: None,
category_codes: None,
};
assert!(!sparse.category_rank_unique_scan_is_bounded());
assert!(!sparse.is_unique());
assert_eq!(sparse.nunique(), 2);
}
#[test]
fn categorical_index_duplicated_uses_rank_bitset_uza04198() {
fn assert_matches_flat(index: &super::CategoricalIndex) {
for keep in [
super::DuplicateKeep::First,
super::DuplicateKeep::Last,
super::DuplicateKeep::None,
] {
assert_eq!(
index.duplicated(keep),
index.to_flat_index().duplicated(keep)
);
}
}
let categories = vec![
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"unused".to_owned(),
];
let repeated = super::CategoricalIndex::with_categories(
vec![
"low".to_owned(),
"high".to_owned(),
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"low".to_owned(),
],
categories,
true,
)
.expect("categorical index");
assert!(repeated.category_rank_unique_scan_is_bounded());
assert_eq!(
repeated.duplicated(super::DuplicateKeep::First),
vec![false, false, true, false, true, true]
);
assert_eq!(
repeated.duplicated(super::DuplicateKeep::Last),
vec![true, true, true, false, false, false]
);
assert_eq!(
repeated.duplicated(super::DuplicateKeep::None),
vec![true, true, true, false, true, true]
);
assert_matches_flat(&repeated);
let same_public_state_without_sidecar = super::CategoricalIndex {
labels: repeated.labels().to_vec(),
categories: repeated.categories().to_vec(),
ordered: repeated.ordered(),
name: repeated.name().cloned(),
category_codes: None,
};
assert_matches_flat(&same_public_state_without_sidecar);
for keep in [
super::DuplicateKeep::First,
super::DuplicateKeep::Last,
super::DuplicateKeep::None,
] {
assert_eq!(
repeated.duplicated(keep),
same_public_state_without_sidecar.duplicated(keep)
);
}
let malformed_sidecar = super::CategoricalIndex {
labels: repeated.labels().to_vec(),
categories: repeated.categories().to_vec(),
ordered: repeated.ordered(),
name: repeated.name().cloned(),
category_codes: Some(vec![usize::MAX; repeated.len()]),
};
assert_matches_flat(&malformed_sidecar);
for keep in [
super::DuplicateKeep::First,
super::DuplicateKeep::Last,
super::DuplicateKeep::None,
] {
assert_eq!(
repeated.duplicated(keep),
malformed_sidecar.duplicated(keep)
);
}
let invalid = super::CategoricalIndex {
labels: vec![
IndexLabel::from("ghost"),
IndexLabel::from("low"),
IndexLabel::from("ghost"),
IndexLabel::from("other"),
IndexLabel::from("low"),
],
categories: vec![IndexLabel::from("low")],
ordered: false,
name: None,
category_codes: None,
};
assert_matches_flat(&invalid);
let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
let sparse = super::CategoricalIndex {
labels: vec![
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("a"),
IndexLabel::from("b"),
],
categories: large_categories,
ordered: false,
name: None,
category_codes: None,
};
assert!(!sparse.category_rank_unique_scan_is_bounded());
assert_matches_flat(&sparse);
}
#[test]
fn categorical_index_unique_drop_duplicates_use_rank_bitset_uza04199() {
fn first_seen_oracle(labels: &[IndexLabel]) -> Vec<IndexLabel> {
let mut seen = std::collections::HashSet::<&IndexLabel>::new();
let mut unique = Vec::new();
for label in labels {
if seen.insert(label) {
unique.push(label.clone());
}
}
unique
}
fn assert_unique_matches_oracle(index: &super::CategoricalIndex) {
let expected = first_seen_oracle(index.labels());
let unique = index.unique();
assert_eq!(unique.labels(), expected.as_slice());
assert_eq!(unique.categories(), index.categories());
assert_eq!(unique.ordered(), index.ordered());
assert_eq!(unique.name(), index.name());
assert_eq!(index.drop_duplicates().labels(), unique.labels());
}
let categories = vec![
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"unused".to_owned(),
];
let repeated = super::CategoricalIndex::with_categories(
vec![
"low".to_owned(),
"high".to_owned(),
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"low".to_owned(),
],
categories,
true,
)
.expect("categorical index")
.set_name("priority");
assert!(repeated.category_rank_unique_scan_is_bounded());
assert_unique_matches_oracle(&repeated);
assert_eq!(
repeated.unique().category_codes.as_deref(),
Some([0usize, 2, 1].as_slice())
);
let mut without_codes = repeated.clone();
without_codes.category_codes = None;
assert_unique_matches_oracle(&without_codes);
let mut malformed_codes = repeated.clone();
malformed_codes.category_codes = Some(vec![usize::MAX; repeated.len()]);
assert_unique_matches_oracle(&malformed_codes);
let invalid = super::CategoricalIndex {
labels: vec![
IndexLabel::from("ghost"),
IndexLabel::from("low"),
IndexLabel::from("ghost"),
IndexLabel::from("other"),
IndexLabel::from("low"),
],
categories: vec![IndexLabel::from("low")],
ordered: true,
name: Some("dirty".into()),
category_codes: None,
};
assert!(invalid.category_rank_unique_scan_is_bounded());
assert_unique_matches_oracle(&invalid);
let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
let sparse = super::CategoricalIndex {
labels: vec![
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("a"),
IndexLabel::from("b"),
],
categories: large_categories,
ordered: false,
name: None,
category_codes: None,
};
assert!(!sparse.category_rank_unique_scan_is_bounded());
assert_unique_matches_oracle(&sparse);
}
#[test]
fn categorical_index_value_counts_use_rank_counts_uza04200() {
fn value_counts_oracle(labels: &[IndexLabel]) -> Vec<(IndexLabel, usize)> {
let mut order = Vec::<&IndexLabel>::new();
let mut counts = std::collections::HashMap::<&IndexLabel, usize>::new();
for label in labels {
let entry = counts.entry(label).or_insert_with(|| {
order.push(label);
0
});
*entry += 1;
}
let mut pairs: Vec<(IndexLabel, usize)> = order
.iter()
.map(|label| {
let label = *label;
(label.clone(), counts[label])
})
.collect();
pairs.sort_by_key(|entry| std::cmp::Reverse(entry.1));
pairs
}
fn assert_value_counts_matches_oracle(index: &super::CategoricalIndex) {
assert_eq!(index.value_counts(), value_counts_oracle(index.labels()));
}
let categories = vec![
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"unused".to_owned(),
];
let repeated = super::CategoricalIndex::with_categories(
vec![
"low".to_owned(),
"high".to_owned(),
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"low".to_owned(),
],
categories,
true,
)
.expect("categorical index");
assert!(repeated.category_rank_unique_scan_is_bounded());
assert_eq!(
repeated.value_counts(),
vec![
(IndexLabel::from("low"), 3),
(IndexLabel::from("high"), 2),
(IndexLabel::from("med"), 1),
]
);
assert_value_counts_matches_oracle(&repeated);
let same_public_state_without_sidecar = super::CategoricalIndex {
labels: repeated.labels().to_vec(),
categories: repeated.categories().to_vec(),
ordered: repeated.ordered(),
name: repeated.name().cloned(),
category_codes: None,
};
assert_eq!(
repeated.value_counts(),
same_public_state_without_sidecar.value_counts()
);
assert_value_counts_matches_oracle(&same_public_state_without_sidecar);
let malformed_sidecar = super::CategoricalIndex {
labels: repeated.labels().to_vec(),
categories: repeated.categories().to_vec(),
ordered: repeated.ordered(),
name: repeated.name().cloned(),
category_codes: Some(vec![usize::MAX; repeated.len()]),
};
assert_eq!(repeated.value_counts(), malformed_sidecar.value_counts());
assert_value_counts_matches_oracle(&malformed_sidecar);
let tied = super::CategoricalIndex::with_categories(
vec![
"b".to_owned(),
"a".to_owned(),
"b".to_owned(),
"a".to_owned(),
"c".to_owned(),
],
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
false,
)
.expect("categorical index");
assert_eq!(
tied.value_counts(),
vec![
(IndexLabel::from("b"), 2),
(IndexLabel::from("a"), 2),
(IndexLabel::from("c"), 1),
]
);
assert_value_counts_matches_oracle(&tied);
let invalid = super::CategoricalIndex {
labels: vec![
IndexLabel::from("ghost"),
IndexLabel::from("low"),
IndexLabel::from("ghost"),
IndexLabel::from("other"),
IndexLabel::from("low"),
],
categories: vec![IndexLabel::from("low")],
ordered: false,
name: None,
category_codes: None,
};
assert!(invalid.category_rank_unique_scan_is_bounded());
assert_eq!(
invalid.value_counts(),
vec![
(IndexLabel::from("ghost"), 2),
(IndexLabel::from("low"), 2),
(IndexLabel::from("other"), 1),
]
);
assert_value_counts_matches_oracle(&invalid);
let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
let sparse = super::CategoricalIndex {
labels: vec![
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("a"),
IndexLabel::from("b"),
],
categories: large_categories,
ordered: false,
name: None,
category_codes: None,
};
assert!(!sparse.category_rank_unique_scan_is_bounded());
assert_value_counts_matches_oracle(&sparse);
}
#[test]
fn categorical_index_factorize_uses_rank_codes_uza04201() {
fn factorize_oracle(labels: &[IndexLabel]) -> (Vec<isize>, Vec<IndexLabel>) {
let mut positions = std::collections::HashMap::<&IndexLabel, isize>::new();
let mut uniques = Vec::<IndexLabel>::new();
let mut codes = Vec::<isize>::with_capacity(labels.len());
for label in labels {
if let Some(code) = positions.get(label) {
codes.push(*code);
} else {
let code = isize::try_from(uniques.len()).unwrap_or(isize::MAX);
positions.insert(label, code);
uniques.push(label.clone());
codes.push(code);
}
}
(codes, uniques)
}
fn assert_factorize_matches_oracle(index: &super::CategoricalIndex) {
let (expected_codes, expected_uniques) = factorize_oracle(index.labels());
let (codes, uniques) = index.factorize();
assert_eq!(codes, expected_codes);
assert_eq!(uniques.labels(), expected_uniques.as_slice());
assert_eq!(uniques.categories(), index.categories());
assert_eq!(uniques.ordered(), index.ordered());
assert_eq!(uniques.name(), index.name());
}
let categories = vec![
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"unused".to_owned(),
];
let repeated = super::CategoricalIndex::with_categories(
vec![
"low".to_owned(),
"high".to_owned(),
"low".to_owned(),
"med".to_owned(),
"high".to_owned(),
"low".to_owned(),
],
categories,
true,
)
.expect("categorical index")
.set_name("priority");
assert!(repeated.category_rank_unique_scan_is_bounded());
let (codes, uniques) = repeated.factorize();
assert_eq!(codes, vec![0, 1, 0, 2, 1, 0]);
assert_eq!(
uniques.labels(),
vec![
IndexLabel::from("low"),
IndexLabel::from("high"),
IndexLabel::from("med")
]
.as_slice()
);
assert_factorize_matches_oracle(&repeated);
let same_public_state_without_sidecar = super::CategoricalIndex {
labels: repeated.labels().to_vec(),
categories: repeated.categories().to_vec(),
ordered: repeated.ordered(),
name: repeated.name().cloned(),
category_codes: None,
};
assert_eq!(repeated, same_public_state_without_sidecar);
assert_factorize_matches_oracle(&same_public_state_without_sidecar);
let invalid = super::CategoricalIndex {
labels: vec![
IndexLabel::from("ghost"),
IndexLabel::from("low"),
IndexLabel::from("ghost"),
IndexLabel::from("other"),
IndexLabel::from("low"),
],
categories: vec![IndexLabel::from("low")],
ordered: true,
name: Some("dirty".into()),
category_codes: None,
};
assert!(invalid.category_rank_unique_scan_is_bounded());
assert_factorize_matches_oracle(&invalid);
let mut large_categories = vec![IndexLabel::from("a"), IndexLabel::from("b")];
large_categories.extend((0..50).map(|value| IndexLabel::Utf8(format!("unused-{value}"))));
let sparse = super::CategoricalIndex {
labels: vec![
IndexLabel::from("a"),
IndexLabel::from("b"),
IndexLabel::from("a"),
IndexLabel::from("b"),
],
categories: large_categories,
ordered: false,
name: None,
category_codes: None,
};
assert!(!sparse.category_rank_unique_scan_is_bounded());
assert_factorize_matches_oracle(&sparse);
}
#[test]
fn timedelta_index_forwarder_methods_match_index_vq4pf() -> Result<(), super::IndexError> {
let a: i64 = 1_000;
let b: i64 = 2_000;
let c: i64 = 3_000;
let nat = fp_types::Timedelta::NAT;
// a, c, b, a, NAT, c (duplicates + NAT)
let td = super::TimedeltaIndex::new(vec![a, c, b, a, nat, c]);
assert_eq!(td.argmax()?, 1);
assert_eq!(td.argmin()?, 0);
let positions = td.argsort();
assert_eq!(positions.len(), td.len());
let unique = td.unique()?;
assert_eq!(unique.values(), vec![Some(a), Some(c), Some(b), None]);
let (codes, uniques) = td.factorize()?;
assert_eq!(codes.len(), td.len());
assert_eq!(uniques.values(), vec![Some(a), Some(c), Some(b)]);
assert_eq!(codes[4], -1);
let counts = td.value_counts();
let total: usize = counts.iter().map(|(_, n)| n).sum();
assert_eq!(total, 5); // NAT dropped
let dup_first = td.duplicated(super::DuplicateKeep::First);
assert_eq!(dup_first, vec![false, false, false, true, false, true]);
let deduped = td.drop_duplicates()?;
assert_eq!(deduped.values(), vec![Some(a), Some(c), Some(b), None]);
let dropped = td.dropna();
assert_eq!(
dropped.values(),
vec![Some(a), Some(c), Some(b), Some(a), Some(c)]
);
Ok(())
}
#[test]
fn timedelta_index_argmax_argmin_reject_empty_vq4pf() {
let empty = super::TimedeltaIndex::new(vec![]);
let err_max = empty.argmax().unwrap_err();
assert!(matches!(
err_max,
super::IndexError::InvalidArgument(ref message)
if message == "attempt to get argmax of an empty sequence"
));
let err_min = empty.argmin().unwrap_err();
assert!(matches!(
err_min,
super::IndexError::InvalidArgument(ref message)
if message == "attempt to get argmin of an empty sequence"
));
let only_nat =
super::TimedeltaIndex::new(vec![fp_types::Timedelta::NAT, fp_types::Timedelta::NAT]);
assert!(only_nat.argmax().is_err());
assert!(only_nat.argmin().is_err());
}
#[test]
fn timedelta_index_dropna_preserves_name_vq4pf() {
let td =
super::TimedeltaIndex::new(vec![fp_types::Timedelta::NAT, 0_i64]).set_name("delta");
let dropped = td.dropna();
assert_eq!(dropped.values(), vec![Some(0)]);
assert_eq!(dropped.name().map(|n| n.as_str()), Some("delta"));
}
#[test]
fn datetime_index_forwarder_methods_match_index_z9guv() -> Result<(), super::IndexError> {
const NS: i64 = 1_000_000_000;
let a = 1_704_067_200_i64 * NS;
let b = 1_705_276_800_i64 * NS;
let c = 1_706_140_800_i64 * NS;
// a, c, b, a, NAT, c (duplicates + NAT to exercise every branch).
let dt = super::DatetimeIndex::new(vec![a, c, b, a, i64::MIN, c]);
// argmax / argmin skip NAT to match pandas skipna=True default.
assert_eq!(dt.argmax()?, 1); // c at position 1 is first-seen max
assert_eq!(dt.argmin()?, 0); // a at position 0 is first-seen min
// argsort returns positions in ascending label order (NAT sorts lowest
// because i64::MIN < every datetime). Stable on ties.
let positions = dt.argsort();
assert_eq!(positions.len(), dt.len());
let sorted_labels: Vec<&super::IndexLabel> = positions
.iter()
.map(|&p| &dt.as_index().labels()[p])
.collect();
for w in sorted_labels.windows(2) {
assert!(w[0].cmp(w[1]).is_le());
}
let unique = dt.unique()?;
// First-seen order including NAT: a, c, b, NAT.
assert_eq!(unique.values(), vec![Some(a), Some(c), Some(b), None]);
let (codes, uniques) = dt.factorize()?;
assert_eq!(codes.len(), dt.len());
// factorize skips NAT in the uniques and emits -1 codes for NAT inputs
// (matches pandas).
assert_eq!(uniques.values(), vec![Some(a), Some(c), Some(b)]);
// Position 4 is the NAT input.
assert_eq!(codes[4], -1);
let counts = dt.value_counts();
// value_counts drops NAT by default (matches pandas dropna=True), so
// total = 5: a:2, c:2, b:1.
let total_count: usize = counts.iter().map(|(_, n)| n).sum();
assert_eq!(total_count, 5);
let a_count = counts
.iter()
.find_map(|(label, n)| match label {
super::IndexLabel::Datetime64(nanos) if *nanos == a => Some(*n),
_ => None,
})
.expect("a should be counted");
assert_eq!(a_count, 2);
let dup_first = dt.duplicated(super::DuplicateKeep::First);
// Positions 3 (second a) and 5 (second c) are duplicates.
assert_eq!(dup_first, vec![false, false, false, true, false, true]);
let deduped = dt.drop_duplicates()?;
// drop_duplicates preserves the NAT entry — only literal duplicates go.
assert_eq!(deduped.values(), vec![Some(a), Some(c), Some(b), None]);
let dropped = dt.dropna();
assert_eq!(
dropped.values(),
vec![Some(a), Some(c), Some(b), Some(a), Some(c)]
);
Ok(())
}
#[test]
fn datetime_index_argmax_argmin_reject_empty_z9guv() {
let empty = super::DatetimeIndex::new(vec![]);
let err_max = empty.argmax().unwrap_err();
assert!(matches!(
err_max,
super::IndexError::InvalidArgument(ref message)
if message == "attempt to get argmax of an empty sequence"
));
let err_min = empty.argmin().unwrap_err();
assert!(matches!(
err_min,
super::IndexError::InvalidArgument(ref message)
if message == "attempt to get argmin of an empty sequence"
));
assert!(empty.argsort().is_empty());
assert!(empty.dropna().is_empty());
}
#[test]
fn datetime_index_dropna_preserves_name_z9guv() {
let dt = super::DatetimeIndex::new(vec![i64::MIN, 0_i64, i64::MIN]).set_name("ts");
let dropped = dt.dropna();
assert_eq!(dropped.values(), vec![Some(0)]);
assert_eq!(dropped.name().map(|n| n.as_str()), Some("ts"));
}
#[test]
fn datetime_index_asi8_round_trips_nanos_teeck() {
const NS: i64 = 1_000_000_000;
let total: i64 = 1_704_067_200_i64 * NS + 123;
let dt = super::DatetimeIndex::new(vec![total, i64::MIN, 0]);
assert_eq!(dt.asi8(), vec![total, i64::MIN, 0]);
let empty = super::DatetimeIndex::new(vec![]);
assert!(empty.asi8().is_empty());
}
#[test]
fn datetime_index_strftime_formats_each_label_teeck() {
const NS: i64 = 1_000_000_000;
// 2024-01-15T12:34:56.789Z:
// 2024-01-01 00:00:00Z = 1704067200 sec.
// + 14 * 86400 = 1209600 -> 2024-01-15 00:00:00 = 1705276800
// + 12*3600 + 34*60 + 56 -> 1705322096
// * 1e9 + 789_000_000 ns
let with_ms: i64 = 1_705_322_096_i64 * NS + 789_000_000;
let dt = super::DatetimeIndex::new(vec![with_ms, i64::MIN]);
// TEST-CHANGE: this used chrono's `%.3f`, which pandas (Python's
// strftime) does not know - it prints '%.3f' as written (measured,
// pandas 2.2.3); Python's `%f` is six-digit microseconds.
assert_eq!(
dt.strftime("%Y-%m-%dT%H:%M:%S.%f"),
vec![Some("2024-01-15T12:34:56.789000".to_owned()), None]
);
assert_eq!(
dt.strftime("%Y-%m-%dT%H:%M:%S%.3f"),
vec![Some("2024-01-15T12:34:56%.3f".to_owned()), None]
);
}
#[test]
fn range_span_marks_a_range_index_and_slices_like_python_fvsao_18() {
// The default index is pandas' RangeIndex, kept by a clone and a
// slice; an Index that merely holds 0..n is not one.
let default = Index::default_range(4);
assert_eq!(default.range_span(), Some((0, 4, 1)));
assert_eq!(default.clone().range_span(), Some((0, 4, 1)));
assert_eq!(Index::from_i64(vec![0, 1, 2, 3]).range_span(), None);
assert_eq!(default.slice(1, 2).range_span(), Some((1, 3, 1)));
assert_eq!(default.slice(9, 2).range_span(), Some((4, 4, 1)));
// A take, even of every position in order, is a plain Index.
assert_eq!(default.take(&[0, 1, 2, 3]).range_span(), None);
// Python's range slicing: range(4)[1::2] is range(1, 4, 2), [::-1]
// range(3, -1, -1); a range(2, 11, 3) slice scales by its step.
assert_eq!(default.sliced_range_span(1, 4, 2), Some((1, 4, 2)));
assert_eq!(default.sliced_range_span(3, -1, -1), Some((3, -1, -1)));
let stepped = Index::from_range(2, 11, 3);
assert_eq!(stepped.range_span(), Some((2, 11, 3)));
assert_eq!(stepped.sliced_range_span(2, -1, -1), Some((8, -1, -3)));
assert_eq!(Index::from_i64(vec![0, 2]).sliced_range_span(0, 2, 1), None);
// A span that no longer describes the labels answers nothing.
let stale = Index::from_i64(vec![0, 1, 5]).with_range_span(Some((0, 3, 1)));
assert_eq!(stale.range_span(), None);
let short = Index::from_i64(vec![0, 1]).with_range_span(Some((0, 3, 1)));
assert_eq!(short.range_span(), None);
// The labels' own range, the stop one step past the last.
assert_eq!(
Index::from_i64(vec![8, 5, 2]).int64_range_span(),
Some((8, -1, -3))
);
assert_eq!(Index::from_i64(vec![0, 1, 3]).int64_range_span(), None);
// Equality ignores the mark.
assert_eq!(default, Index::from_i64(vec![0, 1, 2, 3]));
}
#[test]
fn datetime_index_freq_is_carried_and_inferred_like_pandas_fvsao_61() {
// Live pandas 2.2.3 (br-frankenpandas-rc0923-epic-python-honest-dropin-fvsao.61).
const DAY: i64 = 86_400_000_000_000;
let canonical = |alias: &str| super::canonical_freq(alias);
assert_eq!(canonical("W").as_deref(), Some("W-SUN"));
assert_eq!(canonical("12H").as_deref(), Some("12h"));
assert_eq!(canonical("M").as_deref(), Some("ME"));
assert_eq!(canonical("Q").as_deref(), Some("QE-DEC"));
assert_eq!(canonical("QS").as_deref(), Some("QS-JAN"));
assert_eq!(canonical("SME").as_deref(), Some("SME-15"));
assert_eq!(canonical("T").as_deref(), Some("min"));
assert_eq!(canonical("1D").as_deref(), Some("D"));
assert_eq!(canonical("D1"), None);
assert_eq!(super::scale_freq("D", 2).as_deref(), Some("2D"));
assert_eq!(super::scale_freq("D", -1).as_deref(), Some("-1D"));
// pandas' Tick * float / Tick / number (b9lc7).
let times = |freq: &str, factor: f64| super::multiply_tick_freq(freq, factor);
assert_eq!(times("D", 1.5), Ok(Some("36h".to_owned())));
assert_eq!(times("D", 0.1), Ok(Some("144min".to_owned())));
assert_eq!(times("s", 0.0015), Ok(Some("1500us".to_owned())));
assert_eq!(times("D", -0.5), Ok(Some("-12h".to_owned())));
assert_eq!(times("3h", 2.0), Ok(Some("6h".to_owned())));
assert_eq!(times("D", 0.0), Ok(None));
assert_eq!(times("D", f64::NAN), Ok(None));
assert_eq!(times("ME", 1.5), Ok(None));
assert!(times("ns", 1.5).is_err());
let over = |freq: &str, divisor: f64| super::divide_tick_freq(freq, divisor);
assert_eq!(over("D", 2.0).as_deref(), Some("12h"));
assert_eq!(over("D", 7.0).as_deref(), Some("12342s"));
assert_eq!(over("-1D", 7.0).as_deref(), Some("-12342s"));
assert_eq!(over("h", 7.0).as_deref(), Some("514s"));
assert_eq!(over("D", 0.5).as_deref(), Some("2D"));
assert_eq!(over("D", 2.5).as_deref(), Some("576min"));
assert_eq!(over("5us", 2.0).as_deref(), Some("2us"));
assert_eq!(over("3h", -2.0).as_deref(), Some("-90min"));
// A second / 3 truncates to nothing at second resolution.
assert_eq!(over("s", 3.0), None);
assert_eq!(over("ns", 2.0), None);
assert_eq!(over("D", 0.0), None);
assert_eq!(over("W-SUN", 2.0), None);
let days = |values: &[&str]| {
let nanos: Vec<i64> = values
.iter()
.map(|text| fp_types::Timestamp::parse(text).unwrap().nanos)
.collect();
DatetimeIndex::new(nanos)
};
let infer = |values: &[&str]| days(values).inferred_freq();
assert_eq!(
infer(&["2024-01-01", "2024-01-02", "2024-01-03"]).as_deref(),
Some("D")
);
assert_eq!(
infer(&["2024-01-01", "2024-02-01", "2024-03-01"]).as_deref(),
Some("MS")
);
assert_eq!(
infer(&["2024-01-31", "2024-02-29", "2024-03-31"]).as_deref(),
Some("ME")
);
// pandas' quarter naming quirk: a January-April-July run is QS-OCT.
assert_eq!(
infer(&["2024-01-01", "2024-04-01", "2024-07-01"]).as_deref(),
Some("QS-OCT")
);
assert_eq!(
infer(&["2024-01-07", "2024-01-14", "2024-01-21"]).as_deref(),
Some("W-SUN")
);
assert_eq!(
infer(&["2024-01-04", "2024-01-05", "2024-01-08", "2024-01-09"]).as_deref(),
Some("B")
);
assert_eq!(
infer(&["2024-01-03", "2024-01-02", "2024-01-01"]).as_deref(),
Some("-1D")
);
// NEGATIVES: an irregular run and fewer than three labels have none.
assert_eq!(infer(&["2024-01-01", "2024-01-02", "2024-01-04"]), None);
assert_eq!(infer(&["2024-01-01", "2024-01-02"]), None);
let range = DatetimeIndex::new((0..6).map(|day| day * DAY).collect())
.with_freq(Some("D".to_owned()));
assert_eq!(range.freq().as_deref(), Some("D"));
// pandas' take reads positions in one constant step as a slice: the
// freq scales by the step; a gap or a repeat drops it.
assert_eq!(range.take(&[1, 2, 3]).unwrap().freq().as_deref(), Some("D"));
assert_eq!(range.take(&[0, 2]).unwrap().freq().as_deref(), Some("2D"));
assert_eq!(range.take(&[3, 2]).unwrap().freq().as_deref(), Some("-1D"));
assert_eq!(range.take(&[0, 1, 3]).unwrap().freq(), None);
assert_eq!(range.take(&[0, 0]).unwrap().freq(), None);
assert_eq!(
range.as_index().slice(2, 3).freq(),
Some("D"),
"a slice keeps the freq"
);
assert_eq!(range.shift(1, DAY).freq().as_deref(), Some("D"));
// pandas keeps it through tz_localize only for UTC.
assert_eq!(
range.tz_localize(Some("UTC")).unwrap().freq().as_deref(),
Some("D")
);
assert_eq!(range.tz_localize(Some("US/Eastern")).unwrap().freq(), None);
// Adjacent runs union into one run; equality ignores the freq.
let (head, tail) = (
range.take(&[0, 1, 2]).unwrap(),
range.take(&[3, 4, 5]).unwrap(),
);
assert_eq!(head.union(&tail).freq().as_deref(), Some("D"));
assert_eq!(
range,
DatetimeIndex::new((0..6).map(|day| day * DAY).collect())
);
}
#[test]
fn format_datetime_ns_keeps_subsecond_and_pre_epoch_precision_dt64fmt() {
const NS: i64 = 1_000_000_000;
let base: i64 = 1_705_322_096_i64 * NS; // 2024-01-15 12:34:56 UTC
// No subsecond: unchanged plain "%Y-%m-%d %H:%M:%S".
assert_eq!(super::format_datetime_ns(base), "2024-01-15 12:34:56");
// Millisecond fraction is carried (was DROPPED before dt64fmt), with the
// same trailing-zero trimming format_naive_datetime uses.
assert_eq!(
super::format_datetime_ns(base + 789_000_000),
"2024-01-15 12:34:56.789"
);
// Full nanosecond precision survives.
assert_eq!(
super::format_datetime_ns(base + 123_456_789),
"2024-01-15 12:34:56.123456789"
);
// Pre-epoch instants decompose with floor semantics: -0.5s is
// 1969-12-31 23:59:59.5, not 1970-01-01 00:00:00.5.
assert_eq!(
super::format_datetime_ns(-500_000_000),
"1969-12-31 23:59:59.5"
);
// NaT sentinel is preserved.
assert_eq!(super::format_datetime_ns(i64::MIN), "NaT");
}
#[test]
fn format_datetime_ns_bit_identical_to_chrono_over_full_range_dtns() {
// Differential guard for the hand-rolled civil+ASCII rewrite
// (br-frankenpandas-dtns): must match chrono byte-for-byte across the
// entire i64-ns datetime64 range, both whole-second and sub-second.
fn chrono_ref(nanos: i64) -> String {
if nanos == i64::MIN {
return "NaT".to_owned();
}
let dt = chrono::DateTime::from_timestamp_nanos(nanos);
let mut rendered = dt.format("%Y-%m-%d %H:%M:%S").to_string();
let subsec_nanos = dt.timestamp_subsec_nanos();
if subsec_nanos != 0 {
let mut fractional = format!("{subsec_nanos:09}");
while fractional.ends_with('0') {
fractional.pop();
}
rendered.push('.');
rendered.push_str(&fractional);
}
rendered
}
// Edge cases: the representable datetime64[ns] bounds, the epoch, and
// pre-epoch fractions where floor semantics bite.
let edges = [
i64::MIN,
i64::MIN + 1, // 1677-09-21 ...
i64::MAX, // 2262-04-11 ...
0,
-1,
1,
-500_000_000,
-999_999_999,
-1_000_000_000,
500_000_000,
123_456_789,
-86_400_000_000_000, // exactly one day pre-epoch
];
for ns in edges {
assert_eq!(super::format_datetime_ns(ns), chrono_ref(ns), "ns={ns}");
}
// Dense sweep across the full range with a large odd step (covers every
// month/day/leap combination + sub-second fractions via the prime step).
let step: i64 = 4_801_357_913_i64; // ~4.8s, coprime-ish, exercises subsec
let mut ns = i64::MIN + 1;
let mut count = 0u64;
while count < 3_000_000 {
assert_eq!(super::format_datetime_ns(ns), chrono_ref(ns), "ns={ns}");
match ns.checked_add(step) {
Some(next) => ns = next,
None => break,
}
count += 1;
}
}
#[test]
fn timedelta_index_asi8_microseconds_nanoseconds_match_pandas_teeck() -> Result<(), &'static str>
{
// 1 day + 2:34:56.789012345
let one_day = fp_types::Timedelta::NANOS_PER_DAY;
let extra = 2 * fp_types::Timedelta::NANOS_PER_HOUR
+ 34 * fp_types::Timedelta::NANOS_PER_MIN
+ 56 * fp_types::Timedelta::NANOS_PER_SEC
+ 789_012_345;
let total = one_day + extra;
let td = super::TimedeltaIndex::new(vec![total, fp_types::Timedelta::NAT, 0, -1]);
assert_eq!(td.asi8(), vec![total, fp_types::Timedelta::NAT, 0, -1]);
// microseconds: 789_012_345 % 1_000_000_000 / 1_000 == 789_012
assert_eq!(
td.microseconds(),
vec![Some(789_012), None, Some(0), Some(999_999)]
);
// nanoseconds: 789_012_345 % 1_000 == 345
assert_eq!(td.nanoseconds(), vec![Some(345), None, Some(0), Some(999)]);
let components = td.components();
let positive = components
.first()
.copied()
.flatten()
.ok_or("positive components")?;
assert_eq!(positive.days, 1);
assert_eq!(positive.hours, 2);
assert_eq!(positive.minutes, 34);
assert_eq!(positive.seconds, 56);
assert_eq!(positive.milliseconds, 789);
assert_eq!(positive.microseconds, 12);
assert_eq!(positive.nanoseconds, 345);
assert_eq!(
components.get(1).copied().flatten().map(|row| row.days),
None
);
let zero = components
.get(2)
.copied()
.flatten()
.ok_or("zero components")?;
assert_eq!(zero.days, 0);
assert_eq!(zero.hours, 0);
assert_eq!(zero.minutes, 0);
assert_eq!(zero.seconds, 0);
assert_eq!(zero.milliseconds, 0);
assert_eq!(zero.microseconds, 0);
assert_eq!(zero.nanoseconds, 0);
let negative = components
.get(3)
.copied()
.flatten()
.ok_or("negative components")?;
assert_eq!(negative.days, -1);
assert_eq!(negative.hours, 23);
assert_eq!(negative.minutes, 59);
assert_eq!(negative.seconds, 59);
assert_eq!(negative.milliseconds, 999);
assert_eq!(negative.microseconds, 999);
assert_eq!(negative.nanoseconds, 999);
Ok(())
}
#[test]
fn datetime_index_month_name_and_day_name_match_pandas_fqkiu() {
// 2024-01-15 (Monday in January), 2024-12-31 (Tuesday in December),
// i64::MIN (NAT).
const NS: i64 = 1_000_000_000;
let mon_jan: i64 = 1_705_276_800_i64 * NS;
let tue_dec: i64 = 1_735_603_200_i64 * NS;
let dt = super::DatetimeIndex::new(vec![mon_jan, tue_dec, i64::MIN]);
assert_eq!(
dt.month_name(),
vec![
Some("January".to_owned()),
Some("December".to_owned()),
None
]
);
assert_eq!(
dt.day_name(),
vec![Some("Monday".to_owned()), Some("Tuesday".to_owned()), None]
);
}
#[test]
fn datetime_index_normalize_truncates_to_midnight_utc_fqkiu() {
const NS: i64 = 1_000_000_000;
// 2024-01-15 12:34:56.789Z plus midnight 2024-01-21Z plus NAT.
let mid_day: i64 = 1_705_276_800_i64 * NS + 12 * 3600 * NS + 34 * 60 * NS + 56 * NS + 789;
let midnight: i64 = 1_705_795_200_i64 * NS;
let nat = i64::MIN;
let dt = super::DatetimeIndex::new(vec![mid_day, midnight, nat]).set_name("when");
let normed = dt.normalize().expect("a naive index normalizes");
// Each non-NAT entry is now at midnight; NAT stays NAT; name preserved.
assert_eq!(
normed.values(),
vec![Some(1_705_276_800_i64 * NS), Some(midnight), None]
);
assert_eq!(normed.name().map(|n| n.as_str()), Some("when"));
assert!(normed.is_normalized());
}
#[test]
fn datetime_index_is_normalized_returns_false_when_any_non_midnight_fqkiu() {
const NS: i64 = 1_000_000_000;
let mid_day: i64 = 1_705_276_800_i64 * NS + 1; // 1ns past midnight
let midnight: i64 = 1_705_795_200_i64 * NS;
let mixed = super::DatetimeIndex::new(vec![midnight, mid_day]);
assert!(!mixed.is_normalized());
let only_midnight = super::DatetimeIndex::new(vec![midnight]);
assert!(only_midnight.is_normalized());
let only_nat = super::DatetimeIndex::new(vec![i64::MIN, i64::MIN]);
assert!(only_nat.is_normalized());
let empty = super::DatetimeIndex::new(vec![]);
assert!(empty.is_normalized());
}
#[test]
fn datetime_index_feb_28_in_non_leap_year_is_month_end_qy7yd() {
// 2023-02-28 00:00:00Z is the month-end of February 2023 (28 days).
let feb_28_2023: i64 = 1_677_542_400_i64 * 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![feb_28_2023]);
assert_eq!(dt.is_month_end(), vec![Some(true)]);
}
#[test]
fn datetime_index_leap_year_century_rule_k860x() {
// 2000-06-15 (leap), 2100-06-15 (not leap), 2024-02-15 (leap),
// 2023-02-15 (not leap), Feb in leap vs non-leap year.
let y2000: i64 = 960_076_800 * 1_000_000_000;
let y2100: i64 = 4_117_046_400 * 1_000_000_000;
let y2024feb: i64 = 1_708_002_000 * 1_000_000_000;
let y2023feb: i64 = 1_676_466_000 * 1_000_000_000;
let dt = super::DatetimeIndex::new(vec![y2000, y2100, y2024feb, y2023feb]);
assert_eq!(
dt.is_leap_year(),
vec![Some(true), Some(false), Some(true), Some(false)]
);
// Feb in leap year -> 29 days; non-leap -> 28.
let dim = dt.days_in_month();
assert_eq!(dim[2], Some(29));
assert_eq!(dim[3], Some(28));
}
#[test]
fn datetime_index_time_of_day_accessors_handle_empty_znejf() {
let dt = super::DatetimeIndex::new(vec![]);
assert!(dt.hour().is_empty());
assert!(dt.minute().is_empty());
assert!(dt.second().is_empty());
assert!(dt.microsecond().is_empty());
assert!(dt.nanosecond().is_empty());
}
#[test]
fn range_index_missingness_methods_are_closed_form_a4fih() {
let asc = super::RangeIndex::new(0, 5, 1).unwrap();
assert_eq!(asc.isna(), vec![false; 5]);
assert_eq!(asc.isnull(), vec![false; 5]);
assert_eq!(asc.notna(), vec![true; 5]);
assert_eq!(asc.notnull(), vec![true; 5]);
assert!(!asc.hasnans());
assert!(asc.dropna().equals(&asc));
assert!(asc.fillna(99).equals(&asc));
let desc = super::RangeIndex::new(10, 0, -2).unwrap();
assert_eq!(desc.isna().len(), desc.len());
assert!(!desc.hasnans());
assert!(desc.dropna().equals(&desc));
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert_eq!(empty.isna(), Vec::<bool>::new());
assert_eq!(empty.notna(), Vec::<bool>::new());
assert!(!empty.hasnans());
assert!(empty.dropna().is_empty());
assert!(empty.fillna(0).is_empty());
}
#[test]
fn range_index_format_stringifies_each_value_a4fih() {
let asc = super::RangeIndex::new(0, 4, 1).unwrap();
assert_eq!(asc.format(), vec!["0", "1", "2", "3"]);
let desc = super::RangeIndex::new(5, 0, -2).unwrap();
assert_eq!(desc.format(), vec!["5", "3", "1"]);
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert_eq!(empty.format(), Vec::<String>::new());
}
#[test]
fn range_index_format_uses_direct_values_nkivs() {
let stepped = super::RangeIndex::new(-3, 6, 3).unwrap();
assert_eq!(stepped.format(), vec!["-3", "0", "3"]);
let descending = super::RangeIndex::new(4, -5, -4).unwrap();
assert_eq!(descending.format(), vec!["4", "0", "-4"]);
}
#[test]
fn range_index_factorize_is_identity_a4fih() {
let asc = super::RangeIndex::new(0, 5, 1).unwrap();
let (codes, uniques) = asc.factorize();
assert_eq!(codes, vec![0, 1, 2, 3, 4]);
assert!(uniques.equals(&asc));
let desc = super::RangeIndex::new(10, 0, -2).unwrap();
let (desc_codes, desc_uniques) = desc.factorize();
assert_eq!(desc_codes, (0..desc.len()).collect::<Vec<_>>());
assert!(desc_uniques.equals(&desc));
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
let (empty_codes, empty_uniques) = empty.factorize();
assert!(empty_codes.is_empty());
assert!(empty_uniques.is_empty());
}
#[test]
fn range_index_duplicated_drop_duplicates_are_no_ops_mrchb() {
let asc = super::RangeIndex::new(0, 5, 1).unwrap();
for keep in [
super::DuplicateKeep::First,
super::DuplicateKeep::Last,
super::DuplicateKeep::None,
] {
assert_eq!(asc.duplicated(keep), vec![false; asc.len()]);
}
let cloned = asc.drop_duplicates();
assert!(cloned.equals(&asc));
assert_eq!(cloned.len(), asc.len());
let empty = super::RangeIndex::new(0, 0, 1).unwrap();
assert_eq!(
empty.duplicated(super::DuplicateKeep::First),
Vec::<bool>::new()
);
assert!(empty.drop_duplicates().is_empty());
}
#[test]
fn multi_index_asof_rejects_tuple_comparison_d89fe13() -> Result<(), super::IndexError> {
let string_level = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let int_level = MultiIndex::from_tuples(vec![
vec![1_i64.into(), "a".into()],
vec![2_i64.into(), "b".into()],
])?;
let string_err = string_level
.asof(&[IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)])
.unwrap_err();
let int_err = int_level
.asof(&[IndexLabel::Int64(1), IndexLabel::Utf8("a".into())])
.unwrap_err();
assert!(matches!(
string_err,
super::IndexError::InvalidArgument(message)
if message == "'<' not supported between instances of 'tuple' and 'str'"
));
assert!(matches!(
int_err,
super::IndexError::InvalidArgument(message)
if message == "'<' not supported between instances of 'tuple' and 'int'"
));
assert_eq!(MultiIndex::from_tuples(Vec::new())?.asof(&[])?, None);
Ok(())
}
#[test]
fn multi_index_asof_locs_rejects_mask_and_broadcast_paths_d89fe14()
-> Result<(), super::IndexError> {
let source = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 3_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let where_index = MultiIndex::from_tuples(vec![
vec!["a".into(), 0_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["b".into(), 2_i64.into()],
])?;
let no_mask = source.asof_locs(&where_index, None).unwrap_err();
let mismatched_mask = source
.asof_locs(&where_index, Some(&[true, true]))
.unwrap_err();
let empty_take = source
.asof_locs(&where_index, Some(&[false, false, false]))
.unwrap_err();
let broadcast = source
.asof_locs(&where_index, Some(&[true, false, true]))
.unwrap_err();
let empty_source = MultiIndex::from_arrays(vec![Vec::new(), Vec::new()])?;
let empty_mask = empty_source
.asof_locs(&empty_source, Some(&[]))
.unwrap_err();
assert!(matches!(
no_mask,
super::IndexError::InvalidArgument(message)
if message == "object too deep for desired array"
));
assert!(matches!(
mismatched_mask,
super::IndexError::InvalidArgument(message)
if message == "boolean index did not match indexed array along axis 0; size of axis is 3 but size of corresponding boolean axis is 2"
));
assert!(matches!(
empty_take,
super::IndexError::InvalidArgument(message)
if message == "cannot do a non-empty take from an empty axes."
));
assert!(matches!(
broadcast,
super::IndexError::InvalidArgument(message)
if message == "operands could not be broadcast together with shapes (3,) (2,)"
));
assert!(matches!(
empty_mask,
super::IndexError::InvalidArgument(message)
if message == "attempt to get argmax of an empty sequence"
));
Ok(())
}
#[test]
fn multi_index_drop_duplicates_append_repeat_and_dropna() {
let left = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec![IndexLabel::Datetime64(i64::MIN), 3_i64.into()],
vec![
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Timedelta64(Timedelta::NAT),
],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
assert_eq!(
left.drop_duplicates().to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Datetime64(i64::MIN), IndexLabel::Int64(3)],
vec![
IndexLabel::Datetime64(i64::MIN),
IndexLabel::Timedelta64(Timedelta::NAT),
],
]
);
assert_eq!(
left.dropna().to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
]
);
assert_eq!(left.dropna_all().len(), 4);
let right = MultiIndex::from_tuples(vec![vec!["c".into(), 3_i64.into()]])
.unwrap()
.set_names(vec![Some("letter".into()), Some("other".into())]);
let appended = left.append(&right).unwrap();
assert_eq!(appended.len(), 6);
assert_eq!(appended.names(), &[Some("letter".into()), None]);
let repeated = right.repeat(2);
assert_eq!(
repeated.to_list(),
vec![
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
]
);
assert_eq!(right.repeat(0).len(), 0);
}
#[test]
fn multi_index_insert_delete_and_drop_tuples() {
let mi = MultiIndex::from_tuples(vec![
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let inserted = mi.insert(1, vec!["z".into(), 9_i64.into()]).unwrap();
assert_eq!(
inserted.to_list(),
vec![
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(9)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
]
);
assert_eq!(inserted.names(), mi.names());
let deleted = inserted.delete(1).unwrap();
assert_eq!(deleted, mi);
assert!(mi.insert(0, vec!["short".into()]).is_err());
assert!(mi.delete(99).is_err());
let dropped = mi
.drop(&[vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)]])
.unwrap();
assert_eq!(
dropped.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
]
);
assert!(
mi.drop(&[vec![
IndexLabel::Utf8("missing".into()),
IndexLabel::Int64(0)
]])
.is_err()
);
}
#[test]
fn multi_index_factorize_sort_and_reduce_tuples() {
let mi = MultiIndex::from_tuples(vec![
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 2_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["c".into(), 3_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let (codes, uniques) = mi.factorize();
assert_eq!(codes, vec![0, 1, 2, 0, 1, 3]);
assert_eq!(
uniques.to_list(),
vec![
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
]
);
assert_eq!(uniques.names(), mi.names());
assert_eq!(mi.unique(), uniques);
assert_eq!(mi.nunique(), 4);
assert_eq!(
mi.value_counts(),
vec![
(vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)], 2),
(vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)], 2),
(vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)], 1),
(vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)], 1),
]
);
let sorted = mi.sort_values();
assert_eq!(
sorted.to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
]
);
let (sortlevel, order) = mi.sortlevel();
assert_eq!(sortlevel, sorted);
assert_eq!(order, vec![2, 1, 4, 0, 3, 5]);
assert_eq!(mi.sort(), sorted);
assert_eq!(
mi.min().unwrap(),
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)]
);
assert_eq!(
mi.max().unwrap(),
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)]
);
assert_eq!(mi.argmin(), Some(2));
assert_eq!(mi.argmax(), Some(5));
let empty = MultiIndex::from_tuples(Vec::new()).unwrap();
assert_eq!(empty.min(), None);
assert_eq!(empty.max(), None);
assert_eq!(empty.argmin(), None);
assert_eq!(empty.argmax(), None);
}
#[test]
fn multi_index_factorize_value_counts_fxhash_order_uza04194() {
let mi = MultiIndex::from_tuples(vec![
vec!["z".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["z".into(), 2_i64.into()],
vec!["b".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["b".into(), 1_i64.into()],
vec!["c".into(), 3_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let (codes, uniques) = mi.factorize();
assert_eq!(codes, vec![0, 1, 0, 2, 1, 2, 3]);
assert_eq!(
uniques.to_list(),
vec![
vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
]
);
assert_eq!(uniques.names(), mi.names());
assert_eq!(
mi.value_counts(),
vec![
(vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)], 2),
(vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)], 2),
(vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)], 2),
(vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)], 1),
]
);
}
#[test]
fn multi_index_value_counts_compact_matches_tuple_oracle() {
fn oracle(mi: &MultiIndex) -> Vec<(Vec<IndexLabel>, usize)> {
let mut counts = std::collections::HashMap::<Vec<IndexLabel>, usize>::new();
for tuple in mi.to_list() {
*counts.entry(tuple).or_insert(0) += 1;
}
let mut pairs: Vec<_> = counts.into_iter().collect();
pairs.sort_by(|(left_tuple, left_count), (right_tuple, right_count)| {
right_count
.cmp(left_count)
.then_with(|| left_tuple.cmp(right_tuple))
});
pairs
}
let mi = MultiIndex::from_tuples(vec![
vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Int64(7), IndexLabel::Utf8("a".into())],
vec![IndexLabel::Utf8("z".into()), IndexLabel::Int64(2)],
vec![
IndexLabel::Bool(true),
IndexLabel::Null(fp_types::NullKind::NaN),
],
vec![IndexLabel::Int64(7), IndexLabel::Utf8("a".into())],
vec![
IndexLabel::Bool(false),
IndexLabel::Null(fp_types::NullKind::NaN),
],
vec![
IndexLabel::Bool(true),
IndexLabel::Null(fp_types::NullKind::NaN),
],
])
.expect("two-level MultiIndex");
assert!(mi.compact_two_level_identity_layout().is_some());
assert_eq!(mi.value_counts(), oracle(&mi));
let without_sidecar = super::MultiIndex {
levels: mi.levels.clone(),
names: mi.names.clone(),
identity_codes: None,
missing_is_a_level: false,
};
assert!(
without_sidecar
.compact_two_level_identity_layout()
.is_none()
);
assert_eq!(without_sidecar.value_counts(), oracle(&without_sidecar));
assert_eq!(mi.value_counts(), without_sidecar.value_counts());
}
#[test]
fn multi_index_nunique_counts_without_unique_output_uza04195() {
let mi = MultiIndex::from_tuples(vec![
vec!["z".into(), 2_i64.into()],
vec!["a".into(), 1_i64.into()],
vec!["z".into(), 2_i64.into()],
vec!["b".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
])
.unwrap();
assert_eq!(mi.nunique(), 3);
assert_eq!(mi.nunique(), mi.unique().len());
let zero_row = vec![IndexLabel::Int64(0); 65];
let one_row = vec![IndexLabel::Int64(1); 65];
let wide = MultiIndex::from_tuples(vec![zero_row.clone(), one_row, zero_row]).unwrap();
assert_eq!(wide.nunique(), 2);
assert_eq!(wide.nunique(), wide.unique().len());
}
#[test]
fn multi_index_tuple_set_ops_preserve_order_and_shared_names() {
let left = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into()],
vec!["a".into(), 2_i64.into()],
vec!["b".into(), 1_i64.into()],
vec!["a".into(), 1_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("number".into())]);
let right = MultiIndex::from_tuples(vec![
vec!["a".into(), 2_i64.into()],
vec!["c".into(), 3_i64.into()],
])
.unwrap()
.set_names(vec![Some("letter".into()), Some("other".into())]);
let intersection = left.intersection(&right).unwrap();
assert_eq!(
intersection.to_list(),
vec![vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)]]
);
assert_eq!(intersection.names(), &[Some("letter".into()), None]);
assert_eq!(
left.union(&right).unwrap().to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(2)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
]
);
assert_eq!(
left.difference(&right).unwrap().to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
]
);
assert_eq!(
left.symmetric_difference(&right).unwrap().to_list(),
vec![
vec![IndexLabel::Utf8("a".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("b".into()), IndexLabel::Int64(1)],
vec![IndexLabel::Utf8("c".into()), IndexLabel::Int64(3)],
]
);
}
#[test]
fn multi_index_reorder_levels() {
let mi = MultiIndex::from_tuples(vec![
vec!["a".into(), 1_i64.into(), "x".into()],
vec!["b".into(), 2_i64.into(), "y".into()],
])
.unwrap()
.set_names(vec![
Some("letter".into()),
Some("number".into()),
Some("code".into()),
]);
// Reorder: [2, 0, 1] → code, letter, number.
let reordered = mi.reorder_levels(&[2, 0, 1]).unwrap();
assert_eq!(reordered.nlevels(), 3);
assert_eq!(
reordered.names(),
&[
Some("code".into()),
Some("letter".into()),
Some("number".into())
]
);
// First row should be ("x", "a", 1).
let tuple = reordered.get_tuple(0).unwrap();
assert_eq!(tuple[0], &IndexLabel::Utf8("x".into()));
assert_eq!(tuple[1], &IndexLabel::Utf8("a".into()));
assert_eq!(tuple[2], &IndexLabel::Int64(1));
}
#[test]
fn multi_index_reorder_levels_identity() {
let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
// Identity reorder [0, 1] should be a no-op.
let same = mi.reorder_levels(&[0, 1]).unwrap();
assert_eq!(same, mi);
}
#[test]
fn multi_index_reorder_levels_wrong_length_errors() {
let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
assert!(mi.reorder_levels(&[0]).is_err());
assert!(mi.reorder_levels(&[0, 1, 2]).is_err());
}
#[test]
fn multi_index_reorder_levels_duplicate_index_errors() {
let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
assert!(mi.reorder_levels(&[0, 0]).is_err());
}
#[test]
fn multi_index_reorder_levels_out_of_bounds_errors() {
let mi = MultiIndex::from_tuples(vec![vec!["a".into(), 1_i64.into()]]).unwrap();
assert!(mi.reorder_levels(&[0, 5]).is_err());
}
// ── is_monotonic / is_lexsorted tests (br-frankenpandas-w4uu) ───────
#[test]
fn multi_index_is_monotonic_increasing_on_sorted() {
// Rows: [(A,1), (A,2), (B,1)] — strictly increasing lexicographic.
let mi = MultiIndex::from_tuples(vec![
vec!["A".into(), 1_i64.into()],
vec!["A".into(), 2_i64.into()],
vec!["B".into(), 1_i64.into()],
])
.unwrap();
assert!(mi.is_monotonic_increasing());
assert!(mi.is_lexsorted());
assert!(!mi.is_monotonic_decreasing());
}
#[test]
fn multi_index_is_monotonic_decreasing_on_reverse_sorted() {
// Rows: [(B,2), (B,1), (A,1)].
let mi = MultiIndex::from_tuples(vec![
vec!["B".into(), 2_i64.into()],
vec!["B".into(), 1_i64.into()],
vec!["A".into(), 1_i64.into()],
])
.unwrap();
assert!(mi.is_monotonic_decreasing());
assert!(!mi.is_monotonic_increasing());
}
#[test]
fn multi_index_is_monotonic_both_directions_on_constant_inner() {
// Equal-level-value rows: [(A,1), (A,1)] — both monotonic trivially.
let mi = MultiIndex::from_tuples(vec![
vec!["A".into(), 1_i64.into()],
vec!["A".into(), 1_i64.into()],
])
.unwrap();
assert!(mi.is_monotonic_increasing());
assert!(mi.is_monotonic_decreasing());
}
#[test]
fn multi_index_empty_is_monotonic() {
let mi = MultiIndex::from_tuples(Vec::new()).unwrap();
assert!(mi.is_monotonic_increasing());
assert!(mi.is_monotonic_decreasing());
assert!(mi.is_lexsorted());
}
#[test]
fn multi_index_single_row_is_monotonic() {
let mi = MultiIndex::from_tuples(vec![vec!["A".into(), 1_i64.into()]]).unwrap();
assert!(mi.is_monotonic_increasing());
assert!(mi.is_monotonic_decreasing());
assert!(mi.is_lexsorted());
}
#[test]
fn multi_index_unsorted_is_neither() {
// Rows: [(B,1), (A,2), (B,2)] — unsorted at the outer level.
let mi = MultiIndex::from_tuples(vec![
vec!["B".into(), 1_i64.into()],
vec!["A".into(), 2_i64.into()],
vec!["B".into(), 2_i64.into()],
])
.unwrap();
assert!(!mi.is_monotonic_increasing());
assert!(!mi.is_monotonic_decreasing());
assert!(!mi.is_lexsorted());
}
#[test]
fn multi_index_outer_ascending_inner_descending_is_not_monotonic() {
// Rows: [(A,5), (A,1), (B,3)] — outer ascending, inner within A descends.
let mi = MultiIndex::from_tuples(vec![
vec!["A".into(), 5_i64.into()],
vec!["A".into(), 1_i64.into()],
vec!["B".into(), 3_i64.into()],
])
.unwrap();
// Lexicographically (A,5) > (A,1) so the "increasing" check fails.
assert!(!mi.is_monotonic_increasing());
// (A,5) > (A,1) but (A,1) < (B,3) so decreasing also fails.
assert!(!mi.is_monotonic_decreasing());
}
#[test]
fn index_lookup_methods_match_pandas() {
use super::{Index, IndexLabel};
let i = Index::new(vec![
IndexLabel::Int64(1),
IndexLabel::Int64(3),
IndexLabel::Int64(5),
IndexLabel::Int64(7),
]);
// get_indexer (exact): -1/None for labels not present (verified vs
// pandas Index([1,3,5,7]).get_indexer([2,3,6,7]) == [-1,1,-1,3]).
let target = Index::new(vec![
IndexLabel::Int64(2),
IndexLabel::Int64(3),
IndexLabel::Int64(6),
IndexLabel::Int64(7),
]);
assert_eq!(
i.get_indexer(&target),
vec![None, Some(1), None, Some(3)],
"get_indexer exact"
);
// searchsorted left/right (pandas: 3->1/2, 4->2, 8->4, 0->0).
assert_eq!(i.searchsorted(&IndexLabel::Int64(3), "left").unwrap(), 1);
assert_eq!(i.searchsorted(&IndexLabel::Int64(3), "right").unwrap(), 2);
assert_eq!(i.searchsorted(&IndexLabel::Int64(4), "left").unwrap(), 2);
assert_eq!(i.searchsorted(&IndexLabel::Int64(8), "left").unwrap(), 4);
assert_eq!(i.searchsorted(&IndexLabel::Int64(0), "left").unwrap(), 0);
// asof: last label <= key (pandas: 4->3, 0->NaN, 7->7, 10->7).
assert_eq!(
i.asof(&IndexLabel::Int64(4)),
Some(IndexLabel::Int64(3)),
"asof 4"
);
assert_eq!(i.asof(&IndexLabel::Int64(0)), None, "asof before all");
assert_eq!(
i.asof(&IndexLabel::Int64(7)),
Some(IndexLabel::Int64(7)),
"asof exact"
);
assert_eq!(
i.asof(&IndexLabel::Int64(10)),
Some(IndexLabel::Int64(7)),
"asof after all"
);
// factorize: first-appearance order (pandas: ['b','a','b','c'] ->
// codes [0,1,0,2], uniques ['b','a','c']).
let f = Index::new(vec![
IndexLabel::Utf8("b".into()),
IndexLabel::Utf8("a".into()),
IndexLabel::Utf8("b".into()),
IndexLabel::Utf8("c".into()),
]);
let (codes, uniques) = f.factorize();
assert_eq!(codes, vec![0_isize, 1, 0, 2], "factorize codes");
assert_eq!(
uniques.labels(),
&[
IndexLabel::Utf8("b".into()),
IndexLabel::Utf8("a".into()),
IndexLabel::Utf8("c".into())
],
"factorize uniques"
);
}
}
/// Single-binary, single-invocation A/B for the `to_flat_index` `core::fmt`
/// removal (cc_fp). Both arms are compiled into THIS binary and alternate inside
/// ONE test run, so worker identity and time-varying load cancel: `rch exec` has
/// no `--worker` flag and picks workers non-deterministically, which makes any
/// ratio split across two invocations invalid. The run also asserts the two arms
/// produce identical labels, so parity and perf are proven by the same execution.
///
/// Run: `rch exec -- cargo test -p fp-index --profile release-perf \
/// -- --ignored --nocapture ab_to_flat_index`
#[cfg(test)]
mod ab_to_flat_index_ccfp {
use std::{fmt::Write as _, time::Instant};
use sha2::{Digest, Sha256};
use super::{IndexLabel, MultiIndex};
const BLOCKS: usize = 25;
const BOOTSTRAP_RESAMPLES: usize = 10_000;
const DECIDABILITY_MARGIN: f64 = 2.0;
fn build_mi(n: usize) -> MultiIndex {
// Two levels of the shape wide_to_long / set_index_multi actually produce:
// a Utf8 key level and an Int64 level. Both hit `Display` in the ORIG arm.
let lvl0: Vec<IndexLabel> = (0..n)
.map(|i| IndexLabel::Utf8(format!("r{:06}", i % 100_000)))
.collect();
let lvl1: Vec<IndexLabel> = (0..n)
.map(|i| IndexLabel::Int64((i as i64) % 9_973))
.collect();
MultiIndex::from_arrays(vec![lvl0, lvl1]).expect("multiindex")
}
fn median(xs: &[f64]) -> f64 {
let mut sorted = xs.to_vec();
sorted.sort_by(f64::total_cmp);
sorted[sorted.len() / 2]
}
fn stats(xs: &[f64]) -> (f64, f64) {
let mean = xs.iter().sum::<f64>() / xs.len() as f64;
let var = xs.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / xs.len() as f64;
(mean, 100.0 * var.sqrt() / mean)
}
fn bootstrap_median_ci(values: &[f64]) -> (f64, f64) {
let mut state = 0xf2a2_0260_725d_1ce5_u64;
let mut medians = Vec::with_capacity(BOOTSTRAP_RESAMPLES);
let mut sample = vec![0.0; values.len()];
for _ in 0..BOOTSTRAP_RESAMPLES {
for slot in &mut sample {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
*slot = values[(state as usize) % values.len()];
}
medians.push(median(&sample));
}
medians.sort_by(f64::total_cmp);
(
medians[BOOTSTRAP_RESAMPLES / 40],
medians[(BOOTSTRAP_RESAMPLES * 39 / 40).min(BOOTSTRAP_RESAMPLES - 1)],
)
}
fn binary_sha256() -> String {
let path = std::env::current_exe().expect("current test binary");
let bytes = std::fs::read(path).expect("read current test binary");
let digest = Sha256::digest(&bytes);
let mut hex = String::with_capacity(64);
for byte in digest {
write!(&mut hex, "{byte:02x}").expect("writing to String cannot fail");
}
hex
}
fn time_orig(mi: &MultiIndex, reps: usize) -> f64 {
let mut best = f64::INFINITY;
for _ in 0..reps {
let started = Instant::now();
std::hint::black_box(mi.to_flat_index_ref_write_fmt("_"));
best = best.min(started.elapsed().as_secs_f64() * 1e3);
}
best
}
fn time_candidate(mi: &MultiIndex, reps: usize) -> f64 {
let mut best = f64::INFINITY;
for _ in 0..reps {
let started = Instant::now();
std::hint::black_box(mi.to_flat_index("_"));
best = best.min(started.elapsed().as_secs_f64() * 1e3);
}
best
}
fn ab_regime(label: &str, n: usize, reps: usize) {
let mi = build_mi(n);
// Parity in this same binary: the arms must be bit-identical.
assert_eq!(
mi.to_flat_index_ref_write_fmt("_").labels(),
mi.to_flat_index("_").labels(),
"{label}: CAND diverged from the ORIG write! formatter"
);
for _ in 0..2 {
std::hint::black_box(mi.to_flat_index_ref_write_fmt("_"));
std::hint::black_box(mi.to_flat_index_ref_write_fmt("_"));
std::hint::black_box(mi.to_flat_index("_"));
}
let mut orig_ms = Vec::with_capacity(BLOCKS);
let mut null_ms = Vec::with_capacity(BLOCKS);
let mut candidate_ms = Vec::with_capacity(BLOCKS);
for block in 0..BLOCKS {
if block % 2 == 0 {
orig_ms.push(time_orig(&mi, reps));
null_ms.push(time_orig(&mi, reps));
candidate_ms.push(time_candidate(&mi, reps));
} else {
candidate_ms.push(time_candidate(&mi, reps));
null_ms.push(time_orig(&mi, reps));
orig_ms.push(time_orig(&mi, reps));
}
}
let null_ratios: Vec<f64> = orig_ms
.iter()
.zip(&null_ms)
.map(|(arm_a, arm_b)| arm_a / arm_b)
.collect();
let candidate_ratios: Vec<f64> = orig_ms
.iter()
.zip(&candidate_ms)
.map(|(arm_a, arm_b)| arm_a / arm_b)
.collect();
let (orig_mean, orig_cv) = stats(&orig_ms);
let (candidate_mean, candidate_cv) = stats(&candidate_ms);
let null_median = median(&null_ratios);
let (ci_low, ci_high) = bootstrap_median_ci(&null_ratios);
let ratio = median(&candidate_ratios);
let required_log_effect = DECIDABILITY_MARGIN * ci_low.ln().abs().max(ci_high.ln().abs());
let decidable = ratio.ln().abs() >= required_log_effect;
let verdict = if !decidable {
"NULL_UNDECIDABLE"
} else if ratio > 1.0 {
"KEEP"
} else {
"REJECT"
};
println!("[{label}] n={n} blocks={BLOCKS} reps={reps}");
println!(" ORIG_MS {orig_ms:?}");
println!(" NULL_MS {null_ms:?}");
println!(" CANDIDATE_MS {candidate_ms:?}");
println!(" NULL_RATIOS {null_ratios:?}");
println!(" CANDIDATE_RATIOS {candidate_ratios:?}");
println!(" ORIG mean={orig_mean:9.4} ms cv={orig_cv:5.2}%");
println!(" CAND variant-fmt mean={candidate_mean:9.4} ms cv={candidate_cv:5.2}%");
println!(" NULL_MEDIAN_CI median={null_median:.6} low={ci_low:.6} high={ci_high:.6}");
println!(
" MEDIAN_CI_GATE ratio={ratio:.6} required_log_effect={required_log_effect:.8} \
cv_is_provenance_only=true verdict={verdict}"
);
}
#[test]
#[ignore = "perf A/B; run with --ignored --nocapture"]
fn ab_to_flat_index_core_fmt() {
println!("AB to_flat_index (ONE binary, ONE rch invocation; arms alternate in-block)");
println!("BINARY_SHA256 {}", binary_sha256());
// SERIAL regime: n below FLATIDX_PAR_MIN_ROWS (50_000) so neither arm spawns
// threads. Isolates the per-row formatting cost with no scheduler noise.
ab_regime("serial", 49_000, 60);
// PARALLEL regime: the shipped path at reshape scale.
ab_regime("parallel", 1_000_000, 5);
}
}
#[cfg(test)]
mod cached_parallelism_tests {
use super::cached_available_parallelism;
/// br-frankenpandas-q1evw. THE NEGATIVE CASE, mirrored from `fp-columnar`'s
/// `cached_parallelism_reports_the_real_machine_not_a_constant_kko5z`: the
/// cheap way to make the cgroup walk disappear is to stop asking the OS at
/// all and return a constant. That passes every timing test and silently
/// serialises — or over-subscribes — the parallel `to_flat_index` path, and
/// no benchmark here would catch it, because they all report the thread
/// count the kernel CHOSE rather than the one it should have had.
///
/// `fp-index` carries its own six-line copy of the helper (it deliberately
/// has no `fp-columnar` dependency), so it needs its own pin: the copy can
/// rot independently of the original.
#[test]
fn cached_parallelism_reports_the_real_machine_not_a_constant_q1evw() {
let cached = cached_available_parallelism();
let live = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
assert_eq!(
cached, live,
"cached parallelism must equal what the OS reports, not a hardcoded value"
);
assert!(
cached >= 1,
"worker counts are sized from this; 0 would divide"
);
}
/// The cache must be a cache: one answer per process, so the two call sites
/// that split `to_flat_index` cannot size their work from two different
/// worker counts.
#[test]
fn cached_parallelism_is_stable_across_calls_q1evw() {
let first = cached_available_parallelism();
for _ in 0..64 {
assert_eq!(cached_available_parallelism(), first);
}
}
}
#[cfg(test)]
mod index_slice_tests {
use super::{IndexLabel, IndexSlice};
#[test]
fn test_index_slice_constructors() {
let s_all: IndexSlice = IndexSlice::all();
assert_eq!(s_all.start, None);
assert_eq!(s_all.stop, None);
assert_eq!(s_all.step, None);
let s_bounds =
IndexSlice::from_bounds(Some(IndexLabel::Int64(0)), Some(IndexLabel::Int64(10)));
assert_eq!(s_bounds.start, Some(IndexLabel::Int64(0)));
assert_eq!(s_bounds.stop, Some(IndexLabel::Int64(10)));
assert_eq!(s_bounds.step, None);
let s_start = IndexSlice::from_start(IndexLabel::Utf8("a".into()));
assert_eq!(s_start.start, Some(IndexLabel::Utf8("a".into())));
assert_eq!(s_start.stop, None);
let s_stop = IndexSlice::from_stop(IndexLabel::Utf8("z".into()));
assert_eq!(s_stop.start, None);
assert_eq!(s_stop.stop, Some(IndexLabel::Utf8("z".into())));
let s_step = IndexSlice::new(Some(0_i64), Some(20_i64), Some(2));
assert_eq!(s_step.step, Some(2));
}
}
#[cfg(test)]
mod interval_index_tests {
use fp_types::{Interval, IntervalClosed};
use super::{Index, IndexLabel, IntervalIndex, OrderedF64};
#[test]
fn test_interval_index_constructors() {
// from_breaks
let ii = IntervalIndex::from_breaks(&[0.0, 1.0, 2.0, 3.0], IntervalClosed::Right)
.expect("from_breaks");
assert_eq!(ii.len(), 3);
assert_eq!(ii.closed(), IntervalClosed::Right);
assert!(!ii.is_empty());
assert_eq!(ii.shape(), (3,));
assert_eq!(ii.dtype(), "interval[float64, right]");
// Invalid breaks (< 2)
assert!(IntervalIndex::from_breaks(&[0.0], IntervalClosed::Right).is_err());
// from_tuples
let ii_tuples = IntervalIndex::from_tuples(&[(0.0, 1.0), (1.0, 2.0)], IntervalClosed::Both);
assert_eq!(ii_tuples.len(), 2);
assert_eq!(ii_tuples.closed(), IntervalClosed::Both);
// from_arrays
let ii_arrays = IntervalIndex::from_arrays(&[0.0, 5.0], &[5.0, 10.0], IntervalClosed::Left)
.expect("from_arrays");
assert_eq!(ii_arrays.len(), 2);
assert_eq!(ii_arrays.closed(), IntervalClosed::Left);
// Mismatched arrays length
assert!(IntervalIndex::from_arrays(&[0.0], &[1.0, 2.0], IntervalClosed::Right).is_err());
// from_range
let ii_range = IntervalIndex::from_range(
Some(0.0),
Some(10.0),
Some(5),
None,
Some(IntervalClosed::Right),
)
.expect("from_range");
assert_eq!(ii_range.len(), 5);
assert_eq!(ii_range.values()[0].left, 0.0);
assert_eq!(ii_range.values()[0].right, 2.0);
}
#[test]
fn test_interval_index_accessors_and_properties() {
let ii = IntervalIndex::from_breaks(&[0.0, 2.0, 5.0], IntervalClosed::Right)
.expect("from_breaks")
.set_name("my_intervals");
assert_eq!(ii.name().map(|n| n.as_str()), Some("my_intervals"));
assert_eq!(ii.names(), vec![Some("my_intervals".to_string())]);
let left_idx = ii.left();
assert_eq!(left_idx.len(), 2);
assert_eq!(left_idx.labels()[0], IndexLabel::Float64(OrderedF64(0.0)));
assert_eq!(left_idx.labels()[1], IndexLabel::Float64(OrderedF64(2.0)));
let right_idx = ii.right();
assert_eq!(right_idx.labels()[0], IndexLabel::Float64(OrderedF64(2.0)));
assert_eq!(right_idx.labels()[1], IndexLabel::Float64(OrderedF64(5.0)));
let mid_idx = ii.mid();
assert_eq!(mid_idx.labels()[0], IndexLabel::Float64(OrderedF64(1.0)));
assert_eq!(mid_idx.labels()[1], IndexLabel::Float64(OrderedF64(3.5)));
let len_idx = ii.length();
assert_eq!(len_idx.labels()[0], IndexLabel::Float64(OrderedF64(2.0)));
assert_eq!(len_idx.labels()[1], IndexLabel::Float64(OrderedF64(3.0)));
// Monotonicity and uniqueness
assert!(ii.is_unique());
assert!(ii.is_monotonic_increasing());
assert!(!ii.is_monotonic_decreasing());
assert!(!ii.is_overlapping());
// Null masks
assert!(!ii.hasnans());
assert_eq!(ii.isna(), vec![false, false]);
assert_eq!(ii.isnull(), vec![false, false]);
assert_eq!(ii.notna(), vec![true, true]);
assert_eq!(ii.notnull(), vec![true, true]);
assert_eq!(ii.dropna(), ii);
// Rename
let renamed = ii.rename_index(Some("new_name"));
assert_eq!(renamed.name().map(|n| n.as_str()), Some("new_name"));
}
#[test]
fn test_interval_index_loc_and_contains() {
let ii = IntervalIndex::from_breaks(&[0.0, 10.0, 20.0], IntervalClosed::Right)
.expect("from_breaks");
// contains point
assert_eq!(ii.contains(5.0), vec![true, false]);
assert_eq!(ii.contains(15.0), vec![false, true]);
assert_eq!(ii.contains(0.0), vec![false, false]); // right closed: (0, 10]
assert_eq!(ii.contains(10.0), vec![true, false]);
// get_loc
assert_eq!(ii.get_loc(5.0).unwrap(), 0);
assert_eq!(ii.get_loc(15.0).unwrap(), 1);
assert!(ii.get_loc(25.0).is_err());
// get_indexer
let idxs = ii.get_indexer(&[5.0, 15.0, 25.0]);
assert_eq!(idxs, vec![Some(0), Some(1), None]);
// get_loc_interval
let target = Interval::new(0.0, 10.0, IntervalClosed::Right);
assert_eq!(ii.get_loc_interval(&target).unwrap(), 0);
let missing_target = Interval::new(0.0, 10.0, IntervalClosed::Left);
assert!(ii.get_loc_interval(&missing_target).is_err());
// Overlapping detection
let overlapping_ii = IntervalIndex::new(vec![
Interval::new(0.0, 10.0, IntervalClosed::Both),
Interval::new(5.0, 15.0, IntervalClosed::Both),
]);
assert!(overlapping_ii.is_overlapping());
// get_loc on overlapping point 7.0 should return error
assert!(overlapping_ii.get_loc(7.0).is_err());
}
#[test]
fn test_interval_index_slicing_and_conversion() {
let ii = IntervalIndex::from_breaks(&[0.0, 1.0, 2.0, 3.0, 4.0], IntervalClosed::Right)
.expect("from_breaks")
.set_name("sample");
assert_eq!(
ii.get_item(0).unwrap(),
Interval::new(0.0, 1.0, IntervalClosed::Right)
);
assert_eq!(
ii.get_item(-1).unwrap(),
Interval::new(3.0, 4.0, IntervalClosed::Right)
);
assert!(ii.get_item(10).is_err());
let h = ii.head(2);
assert_eq!(h.len(), 2);
assert_eq!(
h.get_item(1).unwrap(),
Interval::new(1.0, 2.0, IntervalClosed::Right)
);
let t = ii.tail(2);
assert_eq!(t.len(), 2);
assert_eq!(
t.get_item(0).unwrap(),
Interval::new(2.0, 3.0, IntervalClosed::Right)
);
let taken = ii.take(&[0, 2]).expect("take");
assert_eq!(taken.len(), 2);
assert_eq!(
taken.get_item(0).unwrap(),
Interval::new(0.0, 1.0, IntervalClosed::Right)
);
assert_eq!(
taken.get_item(1).unwrap(),
Interval::new(2.0, 3.0, IntervalClosed::Right)
);
// set_closed
let both = ii.set_closed(IntervalClosed::Both);
assert_eq!(both.closed(), IntervalClosed::Both);
assert_eq!(both.get_item(0).unwrap().closed, IntervalClosed::Both);
// to_index
let idx = ii.to_index();
assert_eq!(idx.len(), 4);
assert_eq!(idx.name().map(|n| n.as_str()), Some("sample"));
// From<IntervalIndex> for Index
let idx_from: Index = ii.into();
assert_eq!(idx_from.len(), 4);
}
#[test]
fn test_interval_index_closed_and_tuples() {
let ii_right = IntervalIndex::from_breaks(&[0.0, 1.5, 3.0], IntervalClosed::Right)
.expect("from_breaks");
assert!(!ii_right.closed_left());
assert!(ii_right.closed_right());
assert!(ii_right.open_left());
assert!(!ii_right.open_right());
assert!(ii_right.is_non_overlapping_monotonic());
assert_eq!(ii_right.to_tuples(), vec![(0.0, 1.5), (1.5, 3.0)]);
assert_eq!(ii_right.to_list().len(), 2);
assert_eq!(ii_right.tolist().len(), 2);
let ii_both = IntervalIndex::from_breaks(&[0.0, 1.5, 3.0], IntervalClosed::Both)
.expect("from_breaks");
assert!(ii_both.closed_left());
assert!(ii_both.closed_right());
assert!(!ii_both.open_left());
assert!(!ii_both.open_right());
// Touching endpoints with Both are overlapping at 1.5
assert!(ii_both.is_overlapping());
assert!(!ii_both.is_non_overlapping_monotonic());
let ii_left =
IntervalIndex::from_breaks(&[0.0, 1.0], IntervalClosed::Left).expect("from_breaks");
assert!(ii_left.closed_left());
assert!(!ii_left.closed_right());
assert!(!ii_left.open_left());
assert!(ii_left.open_right());
let ii_neither =
IntervalIndex::from_breaks(&[0.0, 1.0], IntervalClosed::Neither).expect("from_breaks");
assert!(!ii_neither.closed_left());
assert!(!ii_neither.closed_right());
assert!(ii_neither.open_left());
assert!(ii_neither.open_right());
// Decreasing non-overlapping
let ii_dec =
IntervalIndex::from_tuples(&[(3.0, 5.0), (1.0, 3.0), (0.0, 1.0)], IntervalClosed::Left);
assert!(ii_dec.is_monotonic_decreasing());
assert!(!ii_dec.is_monotonic_increasing());
assert!(!ii_dec.is_overlapping());
assert!(ii_dec.is_non_overlapping_monotonic());
}
/// pandas 2.2.3 (numpy `around`, halves to even):
/// Index([1.25, 2.5, 3.5, -0.5, 0.125]).round(0) -> [1.0, 2.0, 4.0, -0.0, 0.0],
/// Index([1.25, 2.5, 0.125]).round(1) -> [1.2, 2.5, 0.1],
/// Index([15, 25, 14]).round(-1) -> [20, 20, 10]; the name is kept.
/// `round` used to return the index unchanged (fvsao.5).
#[test]
fn round_halves_to_even_like_numpy_fvsao5() {
let floats = |xs: &[f64]| {
Index::new(
xs.iter()
.map(|&x| IndexLabel::Float64(OrderedF64(x)))
.collect(),
)
};
let values = |idx: &Index| -> Vec<IndexLabel> { idx.labels().to_vec() };
let named = floats(&[1.25, 2.5, 3.5, -0.5, 0.125]).rename_index(Some("n"));
let rounded = named.round(0);
assert_eq!(
values(&rounded),
values(&floats(&[1.0, 2.0, 4.0, -0.0, 0.0]))
);
assert_eq!(rounded.name().map(|n| n.as_str()), Some("n"));
assert_eq!(
values(&floats(&[1.25, 2.5, 0.125]).round(1)),
values(&floats(&[1.2, 2.5, 0.1]))
);
let ints = Index::new(vec![
IndexLabel::Int64(15),
IndexLabel::Int64(25),
IndexLabel::Int64(14),
]);
assert_eq!(
values(&ints.round(-1)),
vec![
IndexLabel::Int64(20),
IndexLabel::Int64(20),
IndexLabel::Int64(10)
]
);
// Integers are untouched by a non-negative decimals, and so is a
// string label.
assert_eq!(values(&ints.round(2)), values(&ints));
let text = Index::new(vec![IndexLabel::Utf8("1.25".to_owned())]);
assert_eq!(values(&text.round(0)), values(&text));
}
}
/// infer_freq as pandas' `_FrequencyInferer` (acelo): month / quarter / year
/// starts and ends with their anchors, weeks, business days, weeks of the
/// month, signed steps. Each row is pandas 2.2.3's `date_range` of that
/// family and its `infer_freq`.
#[cfg(test)]
mod infer_freq_like_pandas_acelo {
use super::infer_freq_from_timestamps;
#[test]
fn every_family_as_pandas_infers_it() {
// Each row: the stamps, then pandas' answer after "->".
let cases = [
"2024-01-01 2024-02-01 2024-03-01 2024-04-01 -> MS",
"2024-01-31 2024-02-29 2024-03-31 2024-04-30 -> ME",
// pandas anchors QS on the month sharing its first month's
// remainder by 3: January -> QS-OCT.
"2024-01-01 2024-04-01 2024-07-01 2024-10-01 -> QS-OCT",
"2024-02-29 2024-05-31 2024-08-31 2024-11-30 -> QE-NOV",
"2024-01-01 2025-01-01 2026-01-01 2027-01-01 -> YS-JAN",
"2024-06-30 2025-06-30 2026-06-30 2027-06-30 -> YE-JUN",
"2024-01-07 2024-01-14 2024-01-21 2024-01-28 -> W-SUN",
"2024-01-05 2024-01-19 2024-02-02 2024-02-16 -> 2W-FRI",
"2024-01-04 2024-01-05 2024-01-08 2024-01-09 -> B",
"2024-01-01 2024-01-03 2024-01-05 2024-01-07 -> 2D",
"2024-01-01T00:00:00 2024-01-01T03:00:00 2024-01-01T06:00:00 -> 3h",
"2024-01-01T00:00:00 2024-01-01T00:15:00 2024-01-01T00:30:00 -> 15min",
"2024-01-31 2024-02-29 2024-03-29 2024-04-30 -> BME",
"2024-03-29 2024-06-28 2024-09-30 2024-12-31 -> BQE-DEC",
"2024-01-31 2024-07-31 2025-01-31 2025-07-31 -> 2QE-OCT",
"2024-01-19 2024-02-16 2024-03-15 2024-04-19 -> WOM-3FRI",
"2024-01-04 2024-01-03 2024-01-02 2024-01-01 -> -1D",
// NEGATIVE: irregular steps, one day of the month that is neither
// start nor end, and year starts with a two-year gap stay None.
"2024-01-01 2024-01-02 2024-01-05 -> None",
"2024-03-15 2024-04-15 2024-05-15 -> None",
"2024-01-01 2025-01-01 2026-01-01 2028-01-03 -> None",
];
for case in cases {
let (stamps, want) = case.split_once(" -> ").unwrap();
let stamps: Vec<&str> = stamps.split_whitespace().collect();
let got = infer_freq_from_timestamps(&stamps).unwrap();
assert_eq!(got.as_deref().unwrap_or("None"), want, "{case}");
}
}
}