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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
//! Monte-Carlo resampling numerics: simulation-based expectation estimates and
//! the Phipson–Smyth add-one Monte-Carlo p-value, for the
//! [`MonteCarloResampling`] scheme.
//!
//! Both estimators draw from the deterministic [`SplitMix64`]
//! PRNG, so a fixed seed reproduces a result bit-for-bit within a given build
//! and target. Reproducing it bit-for-bit *across* targets additionally needs a
//! portable simulation closure: [`SplitMix64::next_f64`] qualifies, whereas
//! [`SplitMix64::standard_normal`] inherits the platform math library's last ulp
//! and so must be compared with a tolerance. The
//! p-value uses the `(b + 1) / (n + 1)` correction of Phipson &
//! Smyth (2010), which keeps the estimate strictly positive and never reports an
//! impossible zero p-value.
//!
//! # Examples
//!
//! ```
//! use stats_claw::resampling::monte_carlo_estimate;
//! use stats_claw::rng::SplitMix64;
//!
//! // Estimate E[U] for U ~ Uniform[0, 1); the true mean is 0.5.
//! let est = monte_carlo_estimate(10_000, &mut SplitMix64::new(1), |r| r.next_f64())?;
//! assert!((est.mean() - 0.5).abs() < 4.0 * est.std_error(), "mean was {}", est.mean());
//! # Ok::<(), stats_claw::error::Error>(())
//! ```
use crate;
use cratecount_to_f64;
use crateMonteCarloResampling;
use crateSplitMix64;
use crateAlternative;
/// The outcome of a Monte-Carlo expectation estimate.
///
/// Bundles the sample mean of the simulated draws with its standard error and the
/// number of simulations that produced it, so a caller can build a confidence
/// band (`mean ± z · std_error`) without re-deriving the sample size. The fields
/// are private; read them through the [`mean`](Self::mean),
/// [`std_error`](Self::std_error), and [`n_simulations`](Self::n_simulations)
/// accessors, matching the `CvScores` / `JackknifeEstimate` style.
/// Estimates `E[f]` by Monte-Carlo simulation.
///
/// Runs `sim` `n_sims` times against `rng`, then returns the sample mean of the
/// draws together with its standard error `sd(sims, ddof=1) / sqrt(n_sims)`. The
/// draws share one deterministic generator, so a fixed seed reproduces the
/// estimate bit-for-bit within a given build and target — and on every target
/// too, provided `sim` is itself portable (see the module header).
///
/// # Arguments
///
/// * `n_sims` — number of simulation replicates; must be `>= 2` so the
/// `ddof = 1` variance is defined.
/// * `rng` — the deterministic generator threaded through every replicate.
/// * `sim` — the simulation closure; each call may advance `rng` and returns one
/// realised value of `f`.
///
/// # Returns
///
/// A [`MonteCarloEstimate`] holding the mean, its standard error, and `n_sims`.
///
/// # Errors
///
/// Returns [`Error::InsufficientData`] when `n_sims < 2` (the sample standard
/// error is undefined for fewer than two draws).
///
/// # Examples
///
/// ```
/// use stats_claw::resampling::monte_carlo_estimate;
/// use stats_claw::rng::SplitMix64;
///
/// let est = monte_carlo_estimate(50_000, &mut SplitMix64::new(3), |r| r.standard_normal())?;
/// assert!(est.mean().abs() < 4.0 * est.std_error(), "standard-normal mean was {}", est.mean());
/// # Ok::<(), stats_claw::error::Error>(())
/// ```
/// Computes a Monte-Carlo p-value with the Phipson–Smyth add-one correction.
///
/// Draws `n_sims` statistics from the null distribution via `null_sim`, counts how
/// many `b` are at least as extreme as `observed` under `alternative`, and returns
/// `(b + 1) / (n_sims + 1)`. The `+1` in both terms is the Phipson & Smyth (2010)
/// correction: it treats `observed` itself as one draw of the null, so the p-value
/// is never an impossible zero and stays in `(0, 1]`.
///
/// The extremeness rule per `alternative` is:
/// * [`Alternative::Greater`] — `sim >= observed` (upper tail).
/// * [`Alternative::Less`] — `sim <= observed` (lower tail).
/// * [`Alternative::TwoSided`] — `sim.abs() >= observed.abs()`. This plain
/// magnitude rule assumes the null statistic is already centred on zero; any
/// centring of `observed`/`sim` is the caller's responsibility.
///
/// # Arguments
///
/// * `observed` — the statistic actually observed on the real data.
/// * `n_sims` — number of null replicates to simulate; must be `>= 1`.
/// * `rng` — the deterministic generator threaded through every replicate.
/// * `null_sim` — draws one statistic from the null distribution.
/// * `alternative` — which tail(s) define "at least as extreme".
///
/// # Returns
///
/// The corrected p-value in `(0, 1]`.
///
/// # Errors
///
/// Returns [`Error::InsufficientData`] when `n_sims == 0` (no null draws).
///
/// # Examples
///
/// ```
/// use stats_claw::resampling::monte_carlo_p_value;
/// use stats_claw::rng::SplitMix64;
/// use stats_claw::tests_stat::Alternative;
///
/// // An observation past every plausible standard-normal draw hits the floor.
/// let p = monte_carlo_p_value(
/// 10.0,
/// 1_000,
/// &mut SplitMix64::new(1),
/// |r| r.standard_normal(),
/// Alternative::Greater,
/// )?;
/// assert!((p - 1.0 / 1_001.0).abs() < 1e-12, "p was {p}");
/// # Ok::<(), stats_claw::error::Error>(())
/// ```
/// Kani formal-verification harnesses for the Monte-Carlo estimators.
///
/// These prove the input-validation paths (over symbolic replicate counts) and the
/// Phipson–Smyth p-value bound (over a symbolic observed statistic and symbolic
/// finite null draws), rather than the sampled runs the `#[cfg(test)]` suite uses.
/// The simulation/null closures are supplied by the caller, so the transcendental
/// kernels a real caller might use never enter these proofs — the harnesses verify
/// the layer's own control flow and arithmetic. Compiled only under `cargo kani`
/// (behind `#[cfg(kani)]`); invisible to normal build/test/clippy. Run e.g. with
/// `cargo kani -Z stubbing -p stats-claw --harness resampling_mc_p_value_bounded`.