statrs

repository·main·Indexed 21 days ago

https://github.com/statrs-dev/statrs

A statistical computing library for Rust scientific computing. Version 0.19.0 provides common probability distributions—including Bernoulli, Binomial, Cauchy, ChiSquared, and Dirac—alongside statistical functions such as gamma, beta, and error functions. It includes traits for calculating PMF, PDF, CDF, and survival functions, as well as descriptive properties like mean, variance, entropy, and skewness.

Tokens
12.3K
Snippets
64
Records
75
Agent score
73%

What's inside statrs

  1. Install statrs via Cargo

    main

    To use statrs in your Rust project, add it to your Cargo.toml dependencies. It is recommended to use the latest version available on crates.io.

    [dependencies]
    statrs = "*" # replace * by the latest version of the crate.
  2. Use the OrderStatistics trait for statistical ordering

    main

    The OrderStatistics<T> trait provides utilities for calculating statistics based on the ordering of data.

    Important Note: All algorithms implemented by this trait are in-place, meaning they require a mutable borrow (&mut self) and will modify the underlying data structure (e.g., by partially or fully sorting it) to perform the calculation. If you need to preserve the original order of your data, you must clone the data before calling these methods.

    Common methods include:

    • order_statistic(order: usize): Returns the 1-based order statistic.
    • median(): Returns the median value.
    • quantile(tau: f64): Returns the value at the $\tau$-th quantile ($0 \le \tau \le 1$).
    • percentile(p: usize): Returns the $p$-th percentile ($0 \le p \le 100$).
    • lower_quartile() / upper_quartile(): Returns the first and third quartiles.
    • interquartile_range(): Returns the difference between the upper and lower quartiles.
    • ranks(tie_breaker: RankTieBreaker): Returns the ranks of each entry (requires std feature).
    use statrs::statistics::OrderStatistics;
    use statrs::statistics::Data;
    
    let y = [0.0, 3.0, -2.0];
    let mut y = Data::new(y);
    assert_eq!(y.median(), 0.0);
    // Note: y may now be modified due to in-place operations
  3. Introspect distribution properties and moments

    main

    You can inspect the properties of a distribution using utility traits.

    • Use statrs::distribution::{Continuous, ContinuousCDF} to access probability density functions (pdf) and cumulative distribution functions (cdf).
    • Use statrs::statistics::Distribution to access statistical moments such as mean(), variance(), entropy(), and skewness().
    use statrs::distribution::{Exp, Continuous, ContinuousCDF};
    use statrs::statistics::Distribution;
    
    let n = Exp::new(1.0).unwrap();
    assert_eq!(n.mean(), Some(1.0));
    assert_eq!(n.variance(), Some(1.0));
    assert_eq!(n.entropy(), Some(1.0));
    assert_eq!(n.skewness(), Some(2.0));
    assert_eq!(n.cdf(1.0), 0.6321205588285576784045);
    assert_eq!(n.pdf(1.0), 0.3678794411714423215955);
  4. Sample from a Pareto distribution

    main

    If the rand feature is enabled, you can sample from the Pareto distribution using the rand::distr::Distribution trait. This uses inverse transform sampling.

    // Requires feature "rand"
    use statrs::distribution::Pareto;
    use rand::Rng;
    
    let p = Pareto::new(1.0, 2.0).unwrap();
    let mut rng = rand::thread_rng();
    let sample = p.sample(&mut rng);
  5. Sample from a statistical distribution

    main

    To sample from a distribution, use the statrs::distribution module in conjunction with the rand crate. You must have the rand feature enabled in statrs. You can create a distribution instance (e.g., Exp) and call .sample(&mut rng) using a random number generator from the rand crate.

    use statrs::distribution::Exp;
    use rand::distr::Distribution;
    use rand::SeedableRng;
    
    let mut r = rand::rngs::StdRng::seed_from_u64(0);
    let n = Exp::new(0.5).unwrap();
    print!("{}", n.sample(&mut r));
  6. Use the ChiSquared distribution

    main

    The ChiSquared struct implements the Chi-squared distribution, which is a special case of the Gamma distribution. You can create a new distribution by specifying the degrees of freedom.

    Common operations include calculating the Probability Density Function (pdf), Cumulative Distribution Function (cdf), and statistical properties like mean, variance, and median.

    use statrs::distribution::{ChiSquared, Continuous};
    use statrs::statistics::Distribution;
    use approx::assert_abs_diff_eq;
    
    let n = ChiSquared::new(3.0).unwrap();
    assert_eq!(n.mean().unwrap(), 3.0);
    assert_abs_diff_eq!(n.pdf(4.0), 0.107981933026376103901, epsilon = 1e-15);
  7. Access Binomial parameters `p` and `n`

    main

    Once a Binomial distribution is created, you can retrieve its parameters using the following methods:

    • p(): Returns the probability of success as an f64.
    • n(): Returns the number of trials as a u64.
    use statrs::distribution::Binomial;
    
    let n = Binomial::new(0.5, 5).unwrap();
    assert_eq!(n.p(), 0.5);
    assert_eq!(n.n(), 5);
  8. Compute Bernoulli statistical properties

    main

    The Bernoulli distribution implements several statistical traits to compute descriptive properties:

    • mean(): Returns p.
    • variance(): Returns p * (1 - p).
    • entropy(): Returns the Shannon entropy.
    • skewness(): Returns the skewness.
    • median(): Returns 0 if p < 0.5, 1 if p > 0.5, and 0.5 if p == 0.5.
    • mode(): Returns Some(0) if p < 0.5, Some(1) if p > 0.5, and None (or implementation-specific) if p == 0.5.
    use statrs::distribution::Bernoulli;
    use statrs::statistics::{Distribution, Median, Mode};
    
    let n = Bernoulli::new(0.5).unwrap();
    let mean = n.mean().unwrap();
    let var = n.variance().unwrap();
    let med = n.median();
  9. Use the Erlang distribution

    main

    The Erlang struct implements the Erlang distribution, which is a special case of the Gamma distribution. It can be used to calculate probability density functions (PDF), cumulative distribution functions (CDF), and various statistical properties like mean, variance, and entropy.

    To use it, construct an instance using Erlang::new(shape, rate).

    Parameters

    • shape (k): A u64 representing the shape parameter.
    • rate (λ): An f64 representing the rate parameter.

    Errors

    Erlang::new returns a GammaError if:

    • shape or rate are NaN.
    • shape is 0.
    • rate is <= 0.0.
    use statrs::distribution::{Erlang, Continuous};
    use statrs::statistics::Distribution;
    use approx::assert_abs_diff_eq;
    
    let n = Erlang::new(3, 1.0).unwrap();
    assert_eq!(n.mean().unwrap(), 3.0);
    assert_abs_diff_eq!(n.pdf(2.0), 0.270670566473225383788, epsilon = 1e-15);
  10. Calculate Binomial CDF and Survival Function

    main

    To find cumulative probabilities for a Binomial distribution:

    • cdf(x): The cumulative distribution function (probability that the outcome is $\le x$).
    • sf(x): The survival function (probability that the outcome is $> x$).

    If x >= n, cdf returns 1.0 and sf returns 0.0.

    use statrs::distribution::{Binomial, DiscreteCDF};
    
    let n = Binomial::new(0.5, 5).unwrap();
    let cumulative_prob = n.cdf(3);
    let survival_prob = n.sf(3);
  11. Create a Gumbel distribution

    main

    Use Gumbel::new(location, scale) to construct a new Gumbel distribution.

    Parameters:

    • location (f64): The location parameter (μ).
    • scale (f64): The scale parameter (β). Must be greater than zero.

    Errors: Returns a GumbelError if:

    • location is NaN (GumbelError::LocationInvalid).
    • scale is NaN, zero, or negative (GumbelError::ScaleInvalid).
    use statrs::distribution::Gumbel;
    
    let mut result = Gumbel::new(0.0, 1.0);
    assert!(result.is_ok());
    
    // This will return an error because scale <= 0
    result = Gumbel::new(0.0, -1.0);
    assert!(result.is_err());