r2rs-nmath 0.1.1

Statistics programming for Rust based on R's nmath package
Documentation
mod d;
mod p;
mod q;
mod r;

use strafe_type::{LogProbability64, Probability64, Real64};

pub(crate) use self::{d::*, p::*, q::*, r::*};
use crate::traits::{Distribution, RNG};

/// # The Geometric Distribution
///
/// ## Description
///
/// Density, distribution function, quantile function and random generation for the geometric
/// distribution with parameter prob.
///
/// ## Arguments
///
/// * x, q: quantiles representing the number of failures in a sequence of Bernoulli
/// trials before success occurs.
/// * prob: probability of success in each trial. 0 < prob <= 1.
///
/// ## Details
///
/// The geometric distribution with prob = p has density
///
/// $ p(x) = p (1-p)^x $
///
/// for x = 0, 1, 2, …, 0 < p ≤ 1.
///
/// If an element of x is not integer, the result of dgeom is zero, with a warning.
///
/// The quantile is defined as the smallest value x such that $ F(x) ≥ p $, where F is the
/// distribution function.
///
/// ## Density Plot
///
/// ```rust
/// # use r2rs_base::traits::StatisticalSlice;
/// # use r2rs_nmath::{distribution::GeometricBuilder, traits::Distribution};
/// # use strafe_plot::prelude::{IntoDrawingArea, Line, Plot, PlotOptions, SVGBackend, BLACK};
/// # use strafe_type::FloatConstraint;
/// let geom = GeometricBuilder::new().build();
/// let x = <[f64]>::sequence_by(-1.0, 1.0, 0.001);
/// let y = x
///     .iter()
///     .map(|x| geom.density(x).unwrap())
///     .collect::<Vec<_>>();
///
/// let root = SVGBackend::new("density.svg", (1024, 768)).into_drawing_area();
/// Plot::new()
///     .with_options(PlotOptions {
///         x_axis_label: "x".to_string(),
///         y_axis_label: "density".to_string(),
///         ..Default::default()
///     })
///     .with_plottable(Line {
///         x,
///         y,
///         color: BLACK,
///         ..Default::default()
///     })
///     .plot(&root)
///     .unwrap();
/// # use std::fs::rename;
/// #     drop(root);
/// #     rename(
/// #             format!("density.svg"),
/// #             format!("src/distribution/geom/doctest_out/density.svg"),
/// #     )
/// #     .unwrap();
/// ```
#[cfg_attr(feature = "doc_outputs", cfg_attr(all(), doc = embed_doc_image::embed_image!("density", "src/distribution/geom/doctest_out/density.svg")))]
#[cfg_attr(feature = "doc_outputs", cfg_attr(all(), doc = "![Density][density]"))]
///
/// ## Source
///
/// dgeom computes via dbinom, using code contributed by Catherine Loader (see dbinom).
///
/// pgeom and qgeom are based on the closed-form formulae.
///
/// rgeom uses the derivation as an exponential mixture of Poissons, see
///
/// Devroye, L. (1986) Non-Uniform Random Variate Generation. Springer-Verlag, New York. Page 480.
///
/// ## See Also
/// Distributions for other standard distributions, including dnbinom for the negative
/// binomial which generalizes the geometric distribution.
///
/// ## Examples
///
/// ```rust
/// # use r2rs_base::traits::StatisticalSlice;
/// # use r2rs_nmath::{distribution::GeometricBuilder, traits::Distribution};
/// # use strafe_type::FloatConstraint;
/// let x = (1..=9).map(|i| i as f64 / 10.0).collect::<Vec<_>>();
///
/// let geom = GeometricBuilder::new()
///     .with_success_probability(0.2)
///     .build();
/// let r = x
///     .iter()
///     .map(|x| geom.quantile(x, true).unwrap())
///     .collect::<Vec<_>>();
/// println!("{r:?}");
/// # use std::{fs::File, io::Write};
/// # let mut f = File::create("src/distribution/geom/doctest_out/quan.md").unwrap();
/// # writeln!(f, "```output").unwrap();
/// # writeln!(f, "{r:?}").unwrap();
/// # writeln!(f, "```").unwrap();
/// ```
#[cfg_attr(feature = "doc_outputs", cfg_attr(all(), doc = include_str!("doctest_out/quan.md")))]
///
/// ```rust
/// # use std::collections::HashMap;
/// # use r2rs_nmath::{
/// #     distribution::GeometricBuilder,
/// #     rng::MersenneTwister,
/// #     traits::{Distribution, RNG},
/// # };
/// # use strafe_type::FloatConstraint;
/// let mut rng = MersenneTwister::new();
/// rng.set_seed(1);
///
/// let geom = GeometricBuilder::new()
///     .with_success_probability(0.25)
///     .build();
/// let mut r = (0..20)
///     .map(|_| geom.random_sample(&mut rng).unwrap() as usize)
///     .fold(HashMap::new(), |mut acc, r| {
///         *acc.entry(r).or_insert(0) += 1;
///         acc
///     })
///     .into_iter()
///     .collect::<Vec<_>>();
/// r.sort_by(|(i1, _), (i2, _)| i1.cmp(i2));
///
/// for (key, index) in &r {
///     println!("{key:2}: {index}");
/// }
/// # use std::{fs::File, io::Write};
/// # let mut f = File::create("src/distribution/geom/doctest_out/rand.md").unwrap();
/// # writeln!(f, "```output").unwrap();
/// # for (key, index) in &r {
/// #     writeln!(f, "{key:2}: {index}").unwrap();
/// # }
/// # writeln!(f, "```").unwrap();
/// ```
#[cfg_attr(feature = "doc_outputs", cfg_attr(all(), doc = include_str!("doctest_out/rand.md")))]
pub struct Geometric {
    success_probability: Probability64,
}

impl Distribution for Geometric {
    fn density<R: Into<Real64>>(&self, x: R) -> Real64 {
        dgeom(x, self.success_probability, false)
    }

    fn log_density<R: Into<Real64>>(&self, x: R) -> Real64 {
        dgeom(x, self.success_probability, true)
    }

    fn probability<R: Into<Real64>>(&self, q: R, lower_tail: bool) -> Probability64 {
        pgeom(q, self.success_probability, lower_tail)
    }

    fn log_probability<R: Into<Real64>>(&self, q: R, lower_tail: bool) -> LogProbability64 {
        log_pgeom(q, self.success_probability, lower_tail)
    }

    fn quantile<P: Into<Probability64>>(&self, p: P, lower_tail: bool) -> Real64 {
        qgeom(p, self.success_probability, lower_tail)
    }

    fn log_quantile<LP: Into<LogProbability64>>(&self, p: LP, lower_tail: bool) -> Real64 {
        log_qgeom(p, self.success_probability, lower_tail)
    }

    fn random_sample<R: RNG>(&self, rng: &mut R) -> Real64 {
        rgeom(self.success_probability, rng)
    }
}

pub struct GeometricBuilder {
    success_probability: Option<Probability64>,
}

impl GeometricBuilder {
    pub fn new() -> Self {
        Self {
            success_probability: None,
        }
    }

    pub fn with_success_probability<P: Into<Probability64>>(
        &mut self,
        success_probability: P,
    ) -> &mut Self {
        self.success_probability = Some(success_probability.into());
        self
    }

    pub fn build(&self) -> Geometric {
        let success_probability = self.success_probability.unwrap_or(1.0.into());

        Geometric {
            success_probability,
        }
    }
}

#[cfg(test)]
mod tests;

#[cfg(all(test, feature = "enable_proptest"))]
mod proptests;

#[cfg(all(test, feature = "enable_covtest"))]
mod covtests;