diffusionx 0.12.0

A multi-threaded crate for random number generation and stochastic process simulation, with optional GPU acceleration.
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Random walk simulation

use crate::{
    RealExt, SimulationError, XResult,
    random::stable::{StableConstants, sample_standard_alpha_with_constants},
    random::{PAR_THRESHOLD, exponential},
    simulation::prelude::*,
    utils::cumsum,
};
use rand::{RngExt, SeedableRng};
use rand_distr::{Distribution, Exp1, uniform::SampleUniform};
use rand_xoshiro::Xoshiro256PlusPlus;
use rayon::prelude::*;

/// Lattice random walk.
///
/// # Mathematical Formulation
///
/// A lattice random walk is a stochastic process whose path consists of fixed-size
/// steps on a one-dimensional lattice:
///
/// $$X_n = X_0 + a\sum_{i=1}^{n}\xi_i,$$
///
/// where \(a\) is the step size and each direction \(\xi_i\) is either \(+1\)
/// with probability \(p\) or \(-1\) with probability \(1-p\).
#[derive(Clone, Debug)]
pub struct LatticeRandomWalk<T: RealExt = f64> {
    /// The step size
    step_size: T,
    /// The probability of the step in the positive direction
    probability: T,
    /// The starting position
    start_position: T,
}

impl<T: RealExt> Default for LatticeRandomWalk<T> {
    fn default() -> Self {
        Self {
            step_size: T::one(),
            probability: T::from(0.5).unwrap(),
            start_position: T::zero(),
        }
    }
}

impl<T: RealExt> LatticeRandomWalk<T> {
    /// Create a new `LatticeRandomWalk`
    ///
    /// # Arguments
    ///
    /// * `step_size` - The step size
    /// * `probability` - The probability of the step in the positive direction
    /// * `start_position` - The starting position
    ///
    /// # Example
    ///
    /// ```rust
    /// use diffusionx::simulation::discrete::LatticeRandomWalk;
    ///
    /// let rw = LatticeRandomWalk::new(1.0, 0.5, 0.0).unwrap();
    /// ```
    pub fn new(step_size: T, probability: T, start_position: T) -> XResult<Self> {
        if probability <= T::zero() || probability > T::one() {
            return Err(SimulationError::InvalidParameters(format!(
                "The `probability` must be between 0 and 1, got {probability:?}"
            ))
            .into());
        }
        if step_size <= T::zero() {
            return Err(SimulationError::InvalidParameters(format!(
                "The `step_size` must be greater than 0, got {step_size:?}"
            ))
            .into());
        }
        Ok(Self {
            step_size,
            probability,
            start_position,
        })
    }

    /// Get the step size
    pub fn step_size(&self) -> T {
        self.step_size
    }

    /// Get the probability of the step in the positive direction
    pub fn probability(&self) -> T {
        self.probability
    }

    /// Get the starting position
    pub fn start_position(&self) -> T {
        self.start_position
    }
}

impl<N: IntExt, X: RealExt + std::ops::Neg<Output = X>> DiscreteProcess<N, X>
    for LatticeRandomWalk<X>
where
    std::ops::Range<N>: rayon::iter::IntoParallelIterator,
    std::ops::Range<N>: std::iter::IntoIterator,
{
    fn start(&self) -> X {
        self.start_position
    }

    fn simulate(&self, num_step: N) -> XResult<Vec<X>> {
        simulate_lattice_random_walk(
            self.step_size,
            self.probability,
            self.start_position,
            num_step,
        )
    }

    fn displacement(&self, num_step: N) -> XResult<X> {
        let prob = self.probability.to_f64().unwrap();
        let delta_x = if num_step.to_usize().unwrap() <= PAR_THRESHOLD {
            let mut rng = Xoshiro256PlusPlus::from_rng(&mut rand::rng());
            (N::zero()..num_step)
                .into_iter()
                .map(|_| rng.random_bool(prob))
                .map(|x| if x { self.step_size } else { -self.step_size })
                .sum()
        } else {
            (N::zero()..num_step)
                .into_par_iter()
                .map_init(
                    || Xoshiro256PlusPlus::from_rng(&mut rand::rng()),
                    |r, _| r.random_bool(prob),
                )
                .map(|x| if x { self.step_size } else { -self.step_size })
                .sum()
        };
        Ok(delta_x)
    }
}

/// Simulate the lattice random walk
///
/// # Arguments
///
/// * `step_size` - The step size
/// * `probability` - The probability of the step in the positive direction
/// * `start_position` - The starting position
/// * `num_step` - The number of steps
///
/// # Example
///
/// ```rust
/// use diffusionx::simulation::discrete::random_walk::simulate_lattice_random_walk;
///
/// let x = simulate_lattice_random_walk(0.5, 0.5, 0.0, 1000).unwrap();
/// ```
pub fn simulate_lattice_random_walk<N: IntExt, X: RealExt + std::ops::Neg<Output = X>>(
    step_size: X,
    probability: X,
    start_position: X,
    num_step: N,
) -> XResult<Vec<X>>
where
    std::ops::Range<N>: rayon::iter::IntoParallelIterator,
    std::ops::Range<N>: std::iter::IntoIterator,
{
    if probability <= X::zero() || probability > X::one() {
        return Err(SimulationError::InvalidParameters(format!(
            "The `probability` must be between 0 and 1, got {probability:?}"
        ))
        .into());
    }
    if step_size <= X::zero() {
        return Err(SimulationError::InvalidParameters(format!(
            "The `step_size` must be greater than 0, got {step_size:?}"
        ))
        .into());
    }

    let prob = probability.to_f64().unwrap();
    let delta_x: Vec<X> = if num_step.to_usize().unwrap() <= PAR_THRESHOLD {
        let mut rng = Xoshiro256PlusPlus::from_rng(&mut rand::rng());
        (N::zero()..num_step)
            .into_iter()
            .map(|_| rng.random_bool(prob))
            .map(|x| if x { step_size } else { -step_size })
            .collect()
    } else {
        (N::zero()..num_step)
            .into_par_iter()
            .map_init(
                || Xoshiro256PlusPlus::from_rng(&mut rand::rng()),
                |r, _| r.random_bool(prob),
            )
            .map(|x| if x { step_size } else { -step_size })
            .collect()
    };

    let x = cumsum(start_position, &delta_x);
    Ok(x)
}

/// Random walk with heavy-tailed jump lengths.
///
/// # Mathematical Formulation
///
/// The path is represented by
///
/// $$X_n = X_0 + \sum_{i=1}^{n} A_i,$$
///
/// where the jump lengths \(A_i\) are sampled from an alpha-stable law and then
/// assigned a sign according to `probability`.
#[derive(Clone, Debug)]
pub struct RandomWalk<T: FloatExt = f64> {
    /// The probability of the step in the positive direction
    probability: T,
    /// The alpha parameter of the stable distribution
    alpha: T,
    /// The starting position
    start_position: T,
}

impl<T: FloatExt> Default for RandomWalk<T> {
    fn default() -> Self {
        Self {
            probability: T::from(0.5).unwrap(),
            alpha: T::from(2).unwrap(),
            start_position: T::zero(),
        }
    }
}

impl<T: FloatExt> RandomWalk<T> {
    /// Create a new `RandomWalk`
    ///
    /// # Arguments
    ///
    /// * `probability` - The probability of the step in the positive direction
    /// * `alpha` - The alpha parameter of the stable distribution
    /// * `start_position` - The starting position
    ///
    /// # Example
    ///
    /// ```rust
    /// use diffusionx::simulation::discrete::RandomWalk;
    ///
    /// let rw = RandomWalk::new(0.5, 1.0, 0.0).unwrap();
    /// ```
    pub fn new(probability: T, alpha: T, start_position: T) -> XResult<Self> {
        if probability <= T::zero() || probability > T::one() {
            return Err(SimulationError::InvalidParameters(format!(
                "The `probability` must be between 0 and 1, got {probability:?}"
            ))
            .into());
        }
        if alpha <= T::zero() || alpha > T::from(2).unwrap() {
            return Err(SimulationError::InvalidParameters(format!(
                "The `alpha` must be between 0 and 2, got {alpha:?}"
            ))
            .into());
        }
        Ok(Self {
            probability,
            alpha,
            start_position,
        })
    }

    /// Get the probability of the step in the positive direction
    pub fn probability(&self) -> T {
        self.probability
    }

    /// Get the alpha parameter of the stable distribution
    pub fn alpha(&self) -> T {
        self.alpha
    }

    /// Get the starting position
    pub fn start_position(&self) -> T {
        self.start_position
    }
}

impl<N: IntExt, X: FloatExt + SampleUniform> DiscreteProcess<N, X> for RandomWalk<X>
where
    Exp1: Distribution<X>,
    std::ops::Range<N>: rayon::iter::IntoParallelIterator,
    std::ops::Range<N>: std::iter::IntoIterator,
{
    fn start(&self) -> X {
        self.start_position
    }

    fn simulate(&self, num_step: N) -> XResult<Vec<X>> {
        simulate_random_walk(self.probability, self.alpha, self.start_position, num_step)
    }

    fn displacement(&self, num_step: N) -> XResult<X> {
        let prob = self.probability.to_f64().unwrap();

        let delta_x = if num_step.to_usize().unwrap() <= PAR_THRESHOLD {
            let mut r = Xoshiro256PlusPlus::from_rng(&mut rand::rng());
            if self.alpha == X::one() {
                (N::zero()..num_step)
                    .into_iter()
                    .map(|_| {
                        let dir = r.random_bool(prob);
                        if dir {
                            exponential::standard_rand_with_rng(&mut r).abs()
                        } else {
                            -exponential::standard_rand_with_rng(&mut r).abs()
                        }
                    })
                    .sum()
            } else {
                let constants = StableConstants::new(self.alpha, X::one());
                (N::zero()..num_step)
                    .into_iter()
                    .map(|_| {
                        let dir = r.random_bool(prob);
                        let jump =
                            sample_standard_alpha_with_constants(&constants, self.alpha, &mut r)
                                .abs();
                        if dir { jump } else { -jump }
                    })
                    .sum()
            }
        } else if self.alpha == X::one() {
            (N::zero()..num_step)
                .into_par_iter()
                .map_init(
                    || Xoshiro256PlusPlus::from_rng(&mut rand::rng()),
                    |r, _| {
                        let jump = exponential::standard_rand_with_rng(r).abs();
                        if r.random_bool(prob) { jump } else { -jump }
                    },
                )
                .sum()
        } else {
            let constants = StableConstants::new(self.alpha, X::one());
            (N::zero()..num_step)
                .into_par_iter()
                .map_init(
                    || Xoshiro256PlusPlus::from_rng(&mut rand::rng()),
                    |r, _| {
                        let jump =
                            sample_standard_alpha_with_constants(&constants, self.alpha, r).abs();
                        if r.random_bool(prob) { jump } else { -jump }
                    },
                )
                .sum()
        };
        Ok(delta_x)
    }
}

/// Simulate the random walk
///
/// # Arguments
///
/// * `probability` - The probability of the step in the positive direction
/// * `alpha` - The alpha parameter of the stable distribution
/// * `start_position` - The starting position
/// * `num_step` - The number of steps
///
/// # Example
///
/// ```rust
/// use diffusionx::simulation::discrete::random_walk::simulate_random_walk;
///
/// let x = simulate_random_walk(0.5, 1.0, 0.0, 1000).unwrap();
/// ```
pub fn simulate_random_walk<N: IntExt, X: FloatExt + SampleUniform>(
    probability: X,
    alpha: X,
    start_position: X,
    num_step: N,
) -> XResult<Vec<X>>
where
    Exp1: Distribution<X>,
    std::ops::Range<N>: rayon::iter::IntoParallelIterator,
    std::ops::Range<N>: std::iter::IntoIterator,
{
    if probability <= X::zero() || probability > X::one() {
        return Err(SimulationError::InvalidParameters(format!(
            "The `probability` must be between 0 and 1, got {probability:?}"
        ))
        .into());
    }
    if alpha <= X::zero() || alpha > X::from(2).unwrap() {
        return Err(SimulationError::InvalidParameters(format!(
            "The `alpha` must be between 0 and 2, got {alpha:?}"
        ))
        .into());
    }

    let prob = probability.to_f64().unwrap();
    let delta_x: Vec<_> = if num_step.to_usize().unwrap() <= PAR_THRESHOLD {
        let mut r = Xoshiro256PlusPlus::from_rng(&mut rand::rng());
        if alpha == X::one() {
            (N::zero()..num_step)
                .into_iter()
                .map(|_| {
                    let dir = r.random_bool(prob);
                    let jump = exponential::standard_rand_with_rng(&mut r).abs();
                    if dir { jump } else { -jump }
                })
                .collect()
        } else {
            let constants = StableConstants::new(alpha, X::one());
            (N::zero()..num_step)
                .into_iter()
                .map(|_| {
                    let dir = r.random_bool(prob);
                    let jump =
                        sample_standard_alpha_with_constants(&constants, alpha, &mut r).abs();
                    if dir { jump } else { -jump }
                })
                .collect()
        }
    } else if alpha == X::one() {
        (N::zero()..num_step)
            .into_par_iter()
            .map_init(
                || Xoshiro256PlusPlus::from_rng(&mut rand::rng()),
                |r, _| {
                    let jump = exponential::standard_rand_with_rng(r).abs();
                    if r.random_bool(prob) { jump } else { -jump }
                },
            )
            .collect()
    } else {
        let constants = StableConstants::new(alpha, X::one());
        (N::zero()..num_step)
            .into_par_iter()
            .map_init(
                || Xoshiro256PlusPlus::from_rng(&mut rand::rng()),
                |r, _| {
                    let jump = sample_standard_alpha_with_constants(&constants, alpha, r).abs();
                    if r.random_bool(prob) { jump } else { -jump }
                },
            )
            .collect()
    };
    let x = cumsum(start_position, &delta_x);
    Ok(x)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simulate_lattice_random_walk() {
        let rw: LatticeRandomWalk<f64> = LatticeRandomWalk::default();
        let x = rw.simulate(1000).unwrap();
        assert_eq!(x.len(), 1001);
    }

    #[test]
    fn test_lattice_random_walk_free_function_validates_parameters() {
        assert!(simulate_lattice_random_walk(-1.0, 0.5, 0.0, 10).is_err());

        let result = std::panic::catch_unwind(|| simulate_lattice_random_walk(1.0, 1.5, 0.0, 10));
        assert!(matches!(result, Ok(Err(_))));
    }

    #[test]
    fn test_random_walk_free_function_validates_parameters() {
        assert!(simulate_random_walk(0.5, 0.0, 0.0, 10).is_err());

        let result = std::panic::catch_unwind(|| simulate_random_walk(1.5, 1.0, 0.0, 10));
        assert!(matches!(result, Ok(Err(_))));
    }

    #[test]
    fn test_mean() {
        let rw: LatticeRandomWalk<f64> = LatticeRandomWalk::default();
        let _mean = rw.mean(1000, 1000).unwrap();
    }

    #[test]
    fn test_msd() {
        let rw: LatticeRandomWalk<f64> = LatticeRandomWalk::default();
        let _msd = rw.msd(1000, 1000).unwrap();
    }

    #[test]
    fn test_raw_moment() {
        let rw: LatticeRandomWalk<f64> = LatticeRandomWalk::default();
        let _moment = rw.raw_moment(1000, 1, 1000).unwrap();
    }

    #[test]
    fn test_central_moment() {
        let rw: LatticeRandomWalk<f64> = LatticeRandomWalk::default();
        let _moment = rw.central_moment(1000, 2, 1000).unwrap();
    }

    #[test]
    fn test_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<LatticeRandomWalk>();
        assert_send_sync::<RandomWalk>();
    }
}