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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use ;
pub use ;
use crate;
/// # The Poisson Distribution
///
/// ## Description
///
/// Density, distribution function, quantile function and random generation for the Poisson
/// distribution with parameter lambda.
///
/// ## Arguments
///
/// * lambda: (non-negative) means.
///
/// ## Details
///
/// The Poisson distribution has density
///
/// $ p(x) = \lambda^x \frac{exp(-\lambda)}{x!} $
///
/// for x = 0, 1, 2, … . The mean and variance are $ E(X) = Var(X) = \lambda $.
///
/// Note that $ \lambda = 0 $ is really a limit case (setting 0^0 = 1) resulting in a point mass at
/// 0, see also the example.
///
/// If an element of x is not integer, the result of dpois is zero, with a warning. p(x) is
/// computed using Loader's algorithm, see the reference in dbinom.
///
/// The quantile is right continuous: qpois(p, lambda) is the smallest integer x such that
/// $P(X ≤ x) ≥ p$.
///
/// Setting lower.tail = FALSE allows to get much more precise results when the default,
/// lower.tail = TRUE would return 1, see the example below.
///
/// ## Density Plot
///
/// ```rust
/// # use r2rs_base::traits::StatisticalSlice;
/// # use r2rs_nmath::{distribution::PoissonBuilder, traits::Distribution};
/// # use strafe_plot::prelude::{IntoDrawingArea, Line, Plot, PlotOptions, SVGBackend, BLACK};
/// # use strafe_type::FloatConstraint;
/// let pois = PoissonBuilder::new().build();
/// let x = <[f64]>::sequence_by(-1.0, 7.0, 0.001);
/// let y = x
/// .iter()
/// .map(|x| pois.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/pois/doctest_out/density.svg"),
/// # )
/// # .unwrap();
/// ```
///
/// ## Source
///
/// dpois uses C code contributed by Catherine Loader (see dbinom).
///
/// ppois uses pgamma.
///
/// qpois uses the Cornish–Fisher Expansion to include a skewness correction to a normal
/// approximation, followed by a search.
///
/// rpois uses
///
/// Ahrens, J. H. and Dieter, U. (1982). Computer generation of Poisson deviates from modified
/// normal distributions. ACM Transactions on Mathematical Software, 8, 163–179.
///
/// ## See Also
/// Distributions for other standard distributions, including dbinom for the binomial and dnbinom
/// for the negative binomial distribution.
///
/// poisson.test.
///
/// ## Examples
///
/// // Should be 1
/// ```rust
/// # use r2rs_nmath::{
/// # distribution::PoissonBuilder, func::gamma, traits::Distribution,
/// # };
/// # use strafe_type::FloatConstraint;
/// let x = (0..=7).collect::<Vec<_>>();
/// let pois = PoissonBuilder::new().with_lambda(1).build();
/// let r = x
/// .iter()
/// .map(|x| -(pois.density(x).unwrap() * gamma(1 + x).unwrap().unwrap()).ln())
/// .collect::<Vec<_>>();
/// println!("{r:?}");
/// # use std::{fs::File, io::Write};
/// # let mut f = File::create("src/distribution/pois/doctest_out/dens.md").unwrap();
/// # writeln!(f, "```output").unwrap();
/// # writeln!(f, "{r:?}").unwrap();
/// # writeln!(f, "```").unwrap();
/// ```
///
/// ```rust
/// # use std::collections::HashMap;
/// #
/// # use r2rs_nmath::{
/// # distribution::PoissonBuilder,
/// # rng::MersenneTwister,
/// # traits::{Distribution, RNG},
/// # };
/// # use strafe_type::FloatConstraint;
/// let pois = PoissonBuilder::new().with_lambda(4).build();
/// let mut rng = MersenneTwister::new();
/// rng.set_seed(1);
/// let mut r = (0..50)
/// .map(|_| pois.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/pois/doctest_out/table.md").unwrap();
/// # writeln!(f, "```output").unwrap();
/// # for (key, index) in &r {
/// # writeln!(f, "{key:2}: {index}").unwrap();
/// # }
/// # writeln!(f, "```").unwrap();
/// ```
///
/// Using lower tail directly fixes the cancellation (values becoming 0)
/// ```rust
/// # use r2rs_nmath::{distribution::PoissonBuilder, traits::Distribution};
/// # use strafe_type::FloatConstraint;
/// let x = (15..=25).collect::<Vec<_>>();
/// let pois = PoissonBuilder::new().with_lambda(100).build();
/// let r1 = x
/// .iter()
/// .map(|x| 1.0 - pois.probability(x * 10, true).unwrap())
/// .collect::<Vec<_>>();
/// println!("{r1:?}");
/// let r2 = x
/// .iter()
/// .map(|x| pois.probability(x * 10, false).unwrap())
/// .collect::<Vec<_>>();
/// println!("{r2:?}");
/// # use std::{fs::File, io::Write};
/// # let mut f = File::create("src/distribution/pois/doctest_out/prob.md").unwrap();
/// # writeln!(f, "```output").unwrap();
/// # writeln!(f, "{r1:?}").unwrap();
/// # writeln!(f, "{r2:?}").unwrap();
/// # writeln!(f, "```").unwrap();
/// ```
///
/// ```rust
/// # use r2rs_base::traits::StatisticalSlice;
/// # use r2rs_nmath::{
/// # distribution::{BinomialBuilder, PoissonBuilder},
/// # traits::Distribution,
/// # };
/// # use strafe_plot::prelude::{IntoDrawingArea, Line, Plot, PlotOptions, SVGBackend, BLACK};
/// # use strafe_type::FloatConstraint;
/// let x = <[f64]>::sequence_by(-0.01, 5.0, 0.01);
///
/// let pois = PoissonBuilder::new().with_lambda(1).build();
/// let y1 = x
/// .iter()
/// .map(|x| pois.probability(x, true).unwrap())
/// .collect::<Vec<_>>();
///
/// let binom = BinomialBuilder::new()
/// .with_size(100)
/// .with_success_probability(0.01)
/// .build();
/// let y2 = x
/// .iter()
/// .map(|x| binom.probability(x, true).unwrap())
/// .collect::<Vec<_>>();
///
/// let root = SVGBackend::new("prob_plots.svg", (1024, 768)).into_drawing_area();
///
/// Plot::new()
/// .with_options(PlotOptions {
/// x_axis_label: "x".to_string(),
/// y_axis_label: "F(x)".to_string(),
/// plot_bottom: 0.5,
/// title: "Poisson(1) CDF".to_string(),
/// ..Default::default()
/// })
/// .with_plottable(Line {
/// x: x.clone(),
/// y: y1,
/// color: BLACK,
/// ..Default::default()
/// })
/// .plot(&root)
/// .unwrap();
///
/// Plot::new()
/// .with_options(PlotOptions {
/// x_axis_label: "x".to_string(),
/// y_axis_label: "F(x)".to_string(),
/// plot_top: 0.5,
/// title: "Binomial(100, 0.01) CDF".to_string(),
/// ..Default::default()
/// })
/// .with_plottable(Line {
/// x,
/// y: y2,
/// color: BLACK,
/// ..Default::default()
/// })
/// .plot(&root)
/// .unwrap();
/// # use std::fs::rename;
/// # drop(root);
/// # rename(
/// # format!("prob_plots.svg"),
/// # format!("src/distribution/pois/doctest_out/prob_plots.svg"),
/// # )
/// # .unwrap();
/// ```
///
/// ```rust
/// # use r2rs_nmath::{distribution::PoissonBuilder, traits::Distribution};
/// # use strafe_type::FloatConstraint;
/// assert_eq!(
/// PoissonBuilder::new()
/// .with_lambda(0)
/// .build()
/// .density(0)
/// .unwrap(),
/// 1.0
/// );
/// assert_eq!(
/// PoissonBuilder::new()
/// .with_lambda(0)
/// .build()
/// .probability(0, true)
/// .unwrap(),
/// 1.0
/// );
/// assert_eq!(
/// PoissonBuilder::new()
/// .with_lambda(0)
/// .build()
/// .quantile(1, true)
/// .unwrap(),
/// 0.0
/// );
/// ```