1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
mod d;
mod p;
mod q;
mod r;

use strafe_type::{
    FloatConstraint, LogProbability64, Positive64, Probability64, Rational64, Real64,
};

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

/// # The Exponential Distribution
///
/// ## Description:
///
/// Density, distribution function, quantile function and random
/// generation for the exponential distribution with rate ‘rate’
/// (i.e., mean ‘1/rate’).
///
/// ## Arguments:
///
/// * rate.
/// * scale: 1 / rate
///
/// ## Details:
///
/// If ‘rate’ is not specified, it assumes the default value of ‘1’.
///
/// The exponential distribution with rate lambda has density
///
/// $ f(x) = lambda {e}^{- lambda x} $
///
/// for $x >= 0$.
///
/// ## Density Plot
///
/// ```rust
/// # use r2rs_base::traits::StatisticalSlice;
/// # use r2rs_nmath::{distribution::ExponentialBuilder, traits::Distribution};
/// # use strafe_plot::prelude::{IntoDrawingArea, Line, Plot, PlotOptions, SVGBackend, BLACK};
/// # use strafe_type::FloatConstraint;
/// let exp = ExponentialBuilder::new().build();
/// let x = <[f64]>::sequence(-0.5, 4.0, 1000);
/// let y = x
///     .iter()
///     .map(|x| exp.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/exp/doctest_out/density.svg"),
/// #     )
/// #     .unwrap();
/// ```
#[cfg_attr(feature = "doc_outputs", cfg_attr(all(), doc = embed_doc_image::embed_image!("density", "src/distribution/exp/doctest_out/density.svg")))]
#[cfg_attr(feature = "doc_outputs", cfg_attr(all(), doc = "![Density][density]"))]
///
/// ## Note:
///
/// The cumulative hazard $H(t) = - \text{log}(1 - F(t))$ is ‘-pexp(t, r, lower
/// = FALSE, log = TRUE)’.
///
/// ## Source:
///
/// ‘dexp’, ‘pexp’ and ‘qexp’ are all calculated from numerically
/// stable versions of the definitions.
///
/// ‘rexp’ uses
///
/// Ahrens, J. H. and Dieter, U. (1972).  Computer methods for
/// sampling from the exponential and normal distributions.
/// _Communications of the ACM_, *15*, 873-882.
///
/// ## References:
///
/// Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) _The New S
/// Language_.  Wadsworth & Brooks/Cole.
///
/// Johnson, N. L., Kotz, S. and Balakrishnan, N. (1995) _Continuous
/// Univariate Distributions_, volume 1, chapter 19.  Wiley, New York.
///
/// ## See Also:
///
/// ‘exp’ for the exponential function.
///
/// Distributions for other standard distributions, including ‘dgamma’
/// for the gamma distribution and ‘dweibull’ for the Weibull
/// distribution, both of which generalize the exponential.
///
/// ## Examples:
///
/// ```rust
/// # use r2rs_nmath::distribution::ExponentialBuilder;
/// # use r2rs_nmath::traits::Distribution;
/// # let exp = ExponentialBuilder::new().build();
/// println!("{}", (-1.0_f64).exp());
/// println!("{}", exp.density(1));
/// # use std::{fs::File, io::Write};
/// # let mut f = File::create("src/distribution/exp/doctest_out/dens_1.md").unwrap();
/// # writeln!(f, "```output").unwrap();
/// # writeln!(f, "{}", (-1.0_f64).exp()).unwrap();
/// # writeln!(f, "{}", exp.density(1)).unwrap();
/// # writeln!(f, "```").unwrap();
/// ```
#[cfg_attr(feature = "doc_outputs", cfg_attr(all(), doc = include_str!("doctest_out/dens_1.md")))]
///
/// A fast way to generate *sorted*  U\[0,1\]  random numbers
/// ```rust
/// # use r2rs_nmath::{
/// #     distribution::ExponentialBuilder,
/// #     rng::MersenneTwister,
/// #     traits::{Distribution, RNG},
/// # };
/// # use r2rs_stats::traits::StatArray;
/// # use strafe_plot::prelude::{
/// #     full_palette::GREY_500, IntoDrawingArea, Line, Plot, PlotOptions, Points, SVGBackend, BLACK,
/// # };
/// # use strafe_type::FloatConstraint;
/// let rsunif = |n| {
///     let mut rng = MersenneTwister::new();
///     rng.set_seed(1);
///     let exp = ExponentialBuilder::new().build();
///     let ce = (0..n)
///         .map(|_| exp.random_sample(&mut rng).unwrap())
///         .collect::<Vec<_>>()
///         .cumsum();
///     let ce_max = ce[n - 1];
///     ce.into_iter().map(|ce| ce / ce_max).collect::<Vec<_>>()
/// };
///
/// let x = (0..1000).map(|x| x as f64).collect::<Vec<_>>();
/// let y = rsunif(1000);
///
/// let root = SVGBackend::new("rsunif.svg", (1024, 768)).into_drawing_area();
/// Plot::new()
///     .with_options(PlotOptions {
///         x_axis_label: "index".to_string(),
///         y_axis_label: "rsunif".to_string(),
///         ..Default::default()
///     })
///     .with_plottable(Line {
///         x: vec![0.0, 1000.0],
///         y: vec![0.0, 1.0],
///         color: GREY_500,
///         ..Default::default()
///     })
///     .with_plottable(Points {
///         x,
///         y,
///         color: BLACK,
///         ..Default::default()
///     })
///     .plot(&root)
///     .unwrap();
/// # use std::fs::rename;
/// #     drop(root);
/// #     rename(
/// #             format!("rsunif.svg"),
/// #             format!("src/distribution/exp/doctest_out/rsunif.svg"),
/// #     )
/// #     .unwrap();
/// ```
#[cfg_attr(feature = "doc_outputs", cfg_attr(all(), doc = embed_doc_image::embed_image!("rsunif", "src/distribution/exp/doctest_out/rsunif.svg")))]
#[cfg_attr(feature = "doc_outputs", cfg_attr(all(), doc = "![Density][rsunif]"))]
pub struct Exponential {
    scale: Positive64,
}

impl Distribution for Exponential {
    fn density<R: Into<Real64>>(&self, x: R) -> Real64 {
        dexp(x, self.scale, false)
    }

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

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

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

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

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

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

pub struct ExponentialBuilder {
    scale: Option<Positive64>,
}

impl ExponentialBuilder {
    pub fn new() -> Self {
        Self { scale: None }
    }

    pub fn with_rate<R: Into<Rational64>>(&mut self, rate: R) -> &mut Self {
        self.scale = Some((1.0 / rate.into().unwrap()).into());
        self
    }

    pub fn with_scale<P: Into<Positive64>>(&mut self, scale: P) -> &mut Self {
        self.scale = Some(scale.into());
        self
    }

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

        Exponential { scale }
    }
}

#[cfg(test)]
mod tests;

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

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