one-indexed-vec 0.2.0

A one-based (1-indexed) wrapper around Vec<T>: element at position N is accessed via vec[N].
Documentation
//! Core numeric operations kept on `Vec1` for convenience.
//!
//! These methods are so fundamental that every user is expected to need
//! them. More specialized algorithms live in the disciplinary modules
//! (`numerical`, `signal`, `stats`, ...).

use core::ops::{Add, Div, Mul, Sub};

use crate::vec1_core::Vec1;
use crate::vec1_core::index1::Index1;

// ============================================================================
// Sum / product / prefix
// ============================================================================

impl<T> Vec1<T>
where
    T: Copy + Add<Output = T> + Default,
{
    /// Sum of all elements.
    ///
    /// ```rust
    /// use one_indexed_vec::vec1;
    /// let v = vec1![1, 2, 3, 4];
    /// assert_eq!(v.sum(), 10);
    /// ```
    #[inline]
    pub fn sum(&self) -> T {
        let mut acc = T::default();
        for &x in self.iter() {
            acc = acc + x;
        }
        acc
    }

    /// Sum with an explicit initial value.
    #[inline]
    pub fn sum_with(&self, identity: T) -> T {
        let mut acc = identity;
        for &x in self.iter() {
            acc = acc + x;
        }
        acc
    }

    /// Prefix sum: `out[i] = v[1] + v[2] + ... + v[i]`.
    ///
    /// ```rust
    /// use one_indexed_vec::vec1;
    /// let v = vec1![1, 2, 3, 4];
    /// let ps = v.prefix_sum();
    /// assert_eq!(ps.as_slice(), &[1, 3, 6, 10]);
    /// ```
    #[inline]
    pub fn prefix_sum(&self) -> Vec1<T> {
        self.prefix_sum_with(T::default())
    }

    /// Prefix sum with an explicit initial accumulator.
    #[inline]
    pub fn prefix_sum_with(&self, identity: T) -> Vec1<T> {
        let mut out = Vec1::with_capacity(self.len());
        let mut acc = identity;
        for &x in self.iter() {
            acc = acc + x;
            out.push(acc);
        }
        out
    }
}

impl<T> Vec1<T>
where
    T: Copy + Mul<Output = T> + From<u8>,
{
    /// Product of all elements (identity = 1).
    ///
    /// ```rust
    /// use one_indexed_vec::vec1;
    /// let v = vec1![2, 3, 4];
    /// assert_eq!(v.product(), 24);
    /// ```
    #[inline]
    pub fn product(&self) -> T {
        let mut acc = T::from(1);
        for &x in self.iter() {
            acc = acc * x;
        }
        acc
    }
}

// ============================================================================
// Mean / variance / std_dev
// ============================================================================

impl<T> Vec1<T>
where
    T: Copy + Add<Output = T> + Default,
{
    /// Arithmetic mean.
    ///
    /// ```rust
    /// use one_indexed_vec::{vec1, Vec1};
    /// let v: Vec1<f64> = vec1![1.0, 2.0, 3.0, 4.0, 5.0];
    /// assert!((v.mean() - 3.0).abs() < 1e-10);
    /// ```
    #[inline]
    pub fn mean(&self) -> T
    where
        T: Div<Output = T> + From<u8>,
    {
        if self.is_empty() { T::default() } else { self.sum() / T::from(self.len() as u8) }
    }

    /// Population variance.
    #[inline]
    pub fn variance(&self) -> T
    where
        T: Div<Output = T> + From<u8> + Sub<Output = T> + Mul<Output = T>,
    {
        if self.len() < 2 {
            return T::default();
        }
        let m = self.mean();
        let mut acc = T::default();
        for &x in self.iter() {
            let d = x - m;
            acc = acc + d * d;
        }
        acc / T::from(self.len() as u8)
    }

    /// Population standard deviation.
    #[inline]
    pub fn std_dev(&self) -> T
    where
        T: Div<Output = T> + From<u8> + Sub<Output = T> + Mul<Output = T>,
        f64: From<T>,
        T: From<f64>,
    {
        if self.len() < 2 {
            return T::default();
        }
        let v = self.variance();
        let vf: f64 = v.into();
        T::from(libm::sqrt(vf))
    }
}

// ============================================================================
// Dot product
// ============================================================================

impl<T> Vec1<T>
where
    T: Copy + Add<Output = T> + Mul<Output = T> + Default,
{
    /// Dot product `Σ v[i] · w[i]`.
    ///
    /// ```rust
    /// use one_indexed_vec::vec1;
    /// let a = vec1![1, 2, 3];
    /// let b = vec1![4, 5, 6];
    /// assert_eq!(a.dot_product(&b), 32);
    /// ```
    #[inline]
    pub fn dot_product(&self, other: &Vec1<T>) -> T {
        assert_eq!(
            self.len(),
            other.len(),
            "dot_product: length mismatch (self {}, other {})",
            self.len(),
            other.len()
        );
        let mut acc = T::default();
        for (&x, &y) in self.iter().zip(other.iter()) {
            acc = acc + x * y;
        }
        acc
    }

    /// Dot product up to 1-based index `i`.
    #[inline]
    pub fn dot_product_upto(&self, other: &Vec1<T>, i: usize) -> T {
        assert!(i >= 1, "dot_product_upto: index must be >= 1 (got {})", i);
        assert!(i <= self.len(), "dot_product_upto: i ({}) > self.len() ({})", i, self.len());
        assert!(i <= other.len(), "dot_product_upto: i ({}) > other.len() ({})", i, other.len());
        let mut acc = T::default();
        for idx in 1..=i {
            acc = acc + self[idx] * other[idx];
        }
        acc
    }

    /// Type-safe variant of [`Self::dot_product_upto`].
    #[inline]
    pub fn dot_product_upto_index1(&self, other: &Vec1<T>, i: Index1) -> T {
        self.dot_product_upto(other, i.get())
    }

    /// Dot product over `[start, end]` (1-based inclusive).
    #[inline]
    pub fn dot_product_range(&self, other: &Vec1<T>, start: usize, end: usize) -> T {
        assert!(start >= 1, "dot_product_range: start must be >= 1 (got {})", start);
        assert!(end >= 1, "dot_product_range: end must be >= 1 (got {})", end);
        assert!(start <= end, "dot_product_range: start ({}) > end ({})", start, end);
        assert!(
            end <= self.len(),
            "dot_product_range: end ({}) > self.len() ({})",
            end,
            self.len()
        );
        assert!(
            end <= other.len(),
            "dot_product_range: end ({}) > other.len() ({})",
            end,
            other.len()
        );
        let mut acc = T::default();
        for idx in start..=end {
            acc = acc + self[idx] * other[idx];
        }
        acc
    }

    /// Type-safe variant of [`Self::dot_product_range`].
    #[inline]
    pub fn dot_product_range_index1(&self, other: &Vec1<T>, start: Index1, end: Index1) -> T {
        self.dot_product_range(other, start.get(), end.get())
    }
}

// ============================================================================
// Non-positive checks
// ============================================================================

impl<T> Vec1<T>
where
    T: Copy + PartialOrd + Default,
{
    /// Whether any element is `<= T::default()`.
    #[inline]
    pub fn any_non_positive(&self) -> bool {
        let zero = T::default();
        self.iter().any(|&x| x <= zero)
    }

    /// Whether all elements are `<= T::default()`.
    #[inline]
    pub fn all_non_positive(&self) -> bool {
        let zero = T::default();
        self.iter().all(|&x| x <= zero)
    }

    /// Alias for [`Self::any_non_positive`].
    #[inline]
    pub fn has_non_positive(&self) -> bool {
        self.any_non_positive()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vec1;

    #[test]
    fn sum_basic() {
        assert_eq!(vec1![1, 2, 3, 4].sum(), 10);
        assert_eq!(vec1![1, 2, 3].sum_with(100), 106);
    }

    #[test]
    fn sum_empty() {
        let v: Vec1<i32> = Vec1::new();
        assert_eq!(v.sum(), 0);
    }

    #[test]
    fn prefix_sum_basic() {
        let v = vec1![1, 2, 3, 4];
        assert_eq!(v.prefix_sum().as_slice(), &[1, 3, 6, 10]);
        assert_eq!(v.prefix_sum_with(100).as_slice(), &[101, 103, 106, 110]);
    }

    #[test]
    fn prefix_sum_empty() {
        let v: Vec1<i32> = Vec1::new();
        assert!(v.prefix_sum().is_empty());
    }

    #[test]
    fn product_basic() {
        assert_eq!(vec1![2, 3, 4].product(), 24);
    }

    #[test]
    fn product_empty() {
        let v: Vec1<i32> = Vec1::new();
        assert_eq!(v.product(), 1);
    }

    #[test]
    fn mean_variance_std() {
        let v: Vec1<f64> = vec1![1.0, 2.0, 3.0, 4.0, 5.0];
        assert!((v.mean() - 3.0).abs() < 1e-10);
        assert!((v.variance() - 2.0).abs() < 1e-10);
        assert!((v.std_dev() - 2.0_f64.sqrt()).abs() < 1e-10);
    }

    #[test]
    fn mean_empty() {
        let v: Vec1<f64> = Vec1::new();
        assert_eq!(v.mean(), 0.0);
    }

    #[test]
    fn variance_single() {
        let v: Vec1<f64> = vec1![5.0];
        assert_eq!(v.variance(), 0.0);
    }

    #[test]
    fn dot_product_basic() {
        let a = vec1![1, 2, 3];
        let b = vec1![4, 5, 6];
        assert_eq!(a.dot_product(&b), 32);
    }

    #[test]
    #[should_panic(expected = "length mismatch")]
    fn dot_product_mismatch_panics() {
        let a = vec1![1, 2];
        let b = vec1![1, 2, 3];
        let _ = a.dot_product(&b);
    }

    #[test]
    fn dot_product_upto_basic() {
        let a = vec1![1, 2, 3, 4];
        let b = vec1![5, 6, 7, 8];
        assert_eq!(a.dot_product_upto(&b, 1), 5);
        assert_eq!(a.dot_product_upto(&b, 3), 38);
        assert_eq!(a.dot_product_upto(&b, 4), a.dot_product(&b));
    }

    #[test]
    #[should_panic(expected = "index must be >= 1")]
    fn dot_product_upto_zero_panics() {
        let a = vec1![1, 2, 3];
        let b = vec1![4, 5, 6];
        let _ = a.dot_product_upto(&b, 0);
    }

    #[test]
    fn dot_product_range_basic() {
        let a = vec1![1, 2, 3, 4, 5];
        let b = vec1![6, 7, 8, 9, 10];
        assert_eq!(a.dot_product_range(&b, 2, 4), 74);
    }

    #[test]
    fn non_positive_checks() {
        assert!(vec1![-1, -2].all_non_positive());
        assert!(vec1![-1, 5].any_non_positive());
        assert!(!vec1![1, 2].any_non_positive());
    }
}