scirs2-integrate 0.4.2

Numerical integration module for SciRS2 (scirs2-integrate)
Documentation
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! Jump-diffusion processes
//!
//! This module provides simulation of processes that combine a continuous diffusion
//! component with a discrete jump component driven by a Poisson process.
//!
//! ## Processes
//!
//! | Function/Struct | Model |
//! |-----------------|-------|
//! | [`merton_jump_diffusion`] | Merton (1976) log-normal jumps |
//! | [`compound_poisson_process`] | General compound Poisson process |
//! | [`kou_double_exponential`] | Kou (2002) double-exponential jumps |
//! | [`JumpDiffusionProblem`] | Generic jump-diffusion solver |

use crate::error::{IntegrateError, IntegrateResult};
use scirs2_core::random::prelude::*;
use scirs2_core::random::{Normal, Uniform};
use scirs2_core::Distribution;

// ─────────────────────────────────────────────────────────────────────────────
// Merton Jump-Diffusion
// ─────────────────────────────────────────────────────────────────────────────

/// Simulate the Merton (1976) jump-diffusion model.
///
/// ```text
/// dS = (μ - λ·k̄) S dt + σ S dW + J·S dN
/// ```
///
/// where:
/// - `N` is a Poisson process with intensity `λ`
/// - Jump size `J = exp(μ_j + σ_j·Z) - 1`, `Z ~ N(0,1)`
/// - `k̄ = exp(μ_j + σ_j²/2) - 1` (mean jump)
///
/// # Arguments
///
/// * `mu` — drift rate
/// * `sigma` — diffusion volatility (σ > 0)
/// * `lambda` — Poisson jump intensity (λ ≥ 0)
/// * `mu_j` — mean of log-jump size
/// * `sigma_j` — std of log-jump size (σ_j ≥ 0)
/// * `s0` — initial price (S₀ > 0)
/// * `t_span` — simulation interval `(t0, t1)`
/// * `dt` — time step (> 0)
/// * `rng` — random number generator
///
/// # Returns
///
/// A vector of `(t, S(t))` pairs.
///
/// # Errors
///
/// Returns an error if any parameter is invalid.
///
/// # Examples
///
/// ```
/// use scirs2_integrate::sde::jump_diffusion::merton_jump_diffusion;
/// use scirs2_core::random::prelude::*;
///
/// let mut rng = seeded_rng(42);
/// let path = merton_jump_diffusion(0.05, 0.2, 1.0, -0.1, 0.2, 100.0, (0.0, 1.0), 0.01, &mut rng).unwrap();
/// assert!(path.iter().all(|&(_, s)| s > 0.0), "Merton S must stay positive");
/// ```
pub fn merton_jump_diffusion(
    mu: f64,
    sigma: f64,
    lambda: f64,
    mu_j: f64,
    sigma_j: f64,
    s0: f64,
    t_span: (f64, f64),
    dt: f64,
    rng: &mut StdRng,
) -> IntegrateResult<Vec<(f64, f64)>> {
    if sigma <= 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "sigma must be > 0, got {sigma}"
        )));
    }
    if lambda < 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "lambda must be >= 0, got {lambda}"
        )));
    }
    if sigma_j < 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "sigma_j must be >= 0, got {sigma_j}"
        )));
    }
    if s0 <= 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "s0 must be > 0, got {s0}"
        )));
    }
    validate_t_span(t_span)?;
    validate_dt(dt)?;

    // Mean jump size: k_bar = E[J] = exp(mu_j + sigma_j^2/2) - 1
    let k_bar = (mu_j + 0.5 * sigma_j * sigma_j).exp() - 1.0;
    // Compensated drift
    let mu_comp = mu - lambda * k_bar;

    let normal = Normal::new(0.0, 1.0).map_err(|e| IntegrateError::InvalidInput(e.to_string()))?;
    let uniform =
        Uniform::new(0.0_f64, 1.0_f64).map_err(|e| IntegrateError::InvalidInput(e.to_string()))?;

    let n_steps = ((t_span.1 - t_span.0) / dt).ceil() as usize;
    let mut path = Vec::with_capacity(n_steps + 1);
    path.push((t_span.0, s0));
    let mut s = s0;
    let mut t = t_span.0;

    for _ in 0..n_steps {
        let step = (t_span.1 - t).min(dt);
        let sqrt_step = step.sqrt();
        let z: f64 = normal.sample(rng);
        let dw = z * sqrt_step;

        // Continuous component (Euler-Maruyama)
        let ds_cont = mu_comp * s * step + sigma * s * dw;

        // Jump component: number of jumps in [t, t+step] ~ Poisson(lambda*step)
        let n_jumps = poisson_sample(lambda * step, rng, &uniform)?;
        let mut jump_factor = 1.0;
        for _ in 0..n_jumps {
            let z_j: f64 = normal.sample(rng);
            let log_jump = mu_j + sigma_j * z_j;
            jump_factor *= log_jump.exp(); // multiplicative: J + 1 = exp(log-jump)
        }
        // S_{t+dt} = S_t * jump_factor + continuous component
        s = ((s + ds_cont) * jump_factor).max(1e-10);
        t += step;
        path.push((t, s));
    }
    Ok(path)
}

// ─────────────────────────────────────────────────────────────────────────────
// Compound Poisson Process
// ─────────────────────────────────────────────────────────────────────────────

/// Simulate a compound Poisson process.
///
/// At each Poisson event (with intensity `lambda`) the process jumps by a random
/// amount drawn from `jump_dist`.
///
/// Uses the thinning (Lewis-Shedler) algorithm to place Poisson events exactly:
/// inter-arrival times are exponentially distributed with rate `lambda`.
///
/// # Arguments
///
/// * `lambda` — Poisson intensity (λ > 0)
/// * `jump_dist` — callable returning a jump size given a mutable `StdRng`
/// * `t_span` — simulation interval `(t0, t1)`
/// * `rng` — random number generator
///
/// # Returns
///
/// A vector of `(t, X(t))` pairs at all jump times plus `t0` and `t1`.
///
/// # Errors
///
/// Returns an error if `lambda <= 0` or `t_span` is invalid.
///
/// # Examples
///
/// ```
/// use scirs2_integrate::sde::jump_diffusion::compound_poisson_process;
/// use scirs2_core::random::prelude::*;
/// use scirs2_core::random::{Normal, Distribution};
///
/// let mut rng = seeded_rng(7);
/// // Jumps ~ N(0, 1)
/// let normal = Normal::new(0.0, 1.0).unwrap();
/// let path = compound_poisson_process(
///     2.0,
///     |rng| normal.sample(rng),
///     (0.0, 5.0),
///     &mut rng,
/// ).unwrap();
/// // At least start and end points
/// assert!(path.len() >= 2);
/// ```
pub fn compound_poisson_process<F>(
    lambda: f64,
    jump_dist: F,
    t_span: (f64, f64),
    rng: &mut StdRng,
) -> IntegrateResult<Vec<(f64, f64)>>
where
    F: Fn(&mut StdRng) -> f64,
{
    if lambda <= 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "lambda must be > 0, got {lambda}"
        )));
    }
    validate_t_span(t_span)?;

    // Inter-arrival times: Exp(lambda)
    let uniform =
        Uniform::new(0.0_f64, 1.0_f64).map_err(|e| IntegrateError::InvalidInput(e.to_string()))?;

    let mut path = Vec::new();
    path.push((t_span.0, 0.0));
    let mut x = 0.0_f64;
    let mut t = t_span.0;

    loop {
        // Sample next inter-arrival time: -ln(U)/lambda
        let u: f64 = uniform.sample(rng);
        let inter = -u.ln() / lambda;
        t += inter;
        if t >= t_span.1 {
            break;
        }
        let jump = jump_dist(rng);
        x += jump;
        path.push((t, x));
    }
    path.push((t_span.1, x));
    Ok(path)
}

// ─────────────────────────────────────────────────────────────────────────────
// Kou Double-Exponential Jump-Diffusion
// ─────────────────────────────────────────────────────────────────────────────

/// Simulate the Kou (2002) double-exponential jump-diffusion model.
///
/// Jump sizes follow an asymmetric double-exponential distribution:
/// - Upward jumps: Exp(η₁) with probability p
/// - Downward jumps: -Exp(η₂) with probability (1-p)
///
/// # Arguments
///
/// * `mu` — drift (μ)
/// * `sigma` — volatility (σ > 0)
/// * `lambda` — jump intensity (λ ≥ 0)
/// * `p` — probability of an upward jump (0 < p < 1)
/// * `eta1` — rate of upward exponential jumps (η₁ > 1, for finite expectation)
/// * `eta2` — rate of downward exponential jumps (η₂ > 0)
/// * `s0` — initial price (S₀ > 0)
/// * `t_span` — simulation interval
/// * `dt` — time step
/// * `rng` — random number generator
///
/// # Returns
///
/// A vector of `(t, S(t))` pairs.
///
/// # Errors
///
/// Returns an error if parameter constraints are violated.
pub fn kou_double_exponential(
    mu: f64,
    sigma: f64,
    lambda: f64,
    p: f64,
    eta1: f64,
    eta2: f64,
    s0: f64,
    t_span: (f64, f64),
    dt: f64,
    rng: &mut StdRng,
) -> IntegrateResult<Vec<(f64, f64)>> {
    if sigma <= 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "sigma must be > 0, got {sigma}"
        )));
    }
    if lambda < 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "lambda must be >= 0, got {lambda}"
        )));
    }
    if !(0.0 < p && p < 1.0) {
        return Err(IntegrateError::InvalidInput(format!(
            "p must be in (0,1), got {p}"
        )));
    }
    if eta1 <= 1.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "eta1 must be > 1, got {eta1}"
        )));
    }
    if eta2 <= 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "eta2 must be > 0, got {eta2}"
        )));
    }
    if s0 <= 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "s0 must be > 0, got {s0}"
        )));
    }
    validate_t_span(t_span)?;
    validate_dt(dt)?;

    // Mean jump E[J] = p/(eta1-1) - (1-p)/eta2  (log-price jump)
    // k_bar = E[exp(Y) - 1] where Y is the jump size in log-price
    let k_bar = p * eta1 / (eta1 - 1.0) + (1.0 - p) * eta2 / (eta2 + 1.0) - 1.0;
    let mu_comp = mu - lambda * k_bar;

    let normal = Normal::new(0.0, 1.0).map_err(|e| IntegrateError::InvalidInput(e.to_string()))?;
    let uniform =
        Uniform::new(0.0_f64, 1.0_f64).map_err(|e| IntegrateError::InvalidInput(e.to_string()))?;

    let n_steps = ((t_span.1 - t_span.0) / dt).ceil() as usize;
    let mut path = Vec::with_capacity(n_steps + 1);
    path.push((t_span.0, s0));
    let mut s = s0;
    let mut t = t_span.0;

    for _ in 0..n_steps {
        let step = (t_span.1 - t).min(dt);
        let sqrt_step = step.sqrt();
        let z: f64 = normal.sample(rng);
        let dw = z * sqrt_step;

        let ds_cont = mu_comp * s * step + sigma * s * dw;
        let n_jumps = poisson_sample(lambda * step, rng, &uniform)?;
        let mut log_jump_sum: f64 = 0.0;
        for _ in 0..n_jumps {
            let u_type: f64 = uniform.sample(rng);
            let u_mag: f64 = uniform.sample(rng);
            if u_type < p {
                // Upward: exponential with rate eta1
                log_jump_sum += -u_mag.ln() / eta1;
            } else {
                // Downward: exponential with rate eta2
                log_jump_sum -= -u_mag.ln() / eta2;
            }
        }
        let jump_mult = log_jump_sum.exp();
        s = ((s + ds_cont) * jump_mult).max(1e-10);
        t += step;
        path.push((t, s));
    }
    Ok(path)
}

// ─────────────────────────────────────────────────────────────────────────────
// Generic Jump-Diffusion Problem
// ─────────────────────────────────────────────────────────────────────────────

/// Generic jump-diffusion problem specification.
///
/// ```text
/// dX = f(X,t) dt + g(X,t) dW + dJ
/// ```
///
/// where `dJ` is a compound Poisson process with intensity `jump_intensity`
/// and jumps sampled from `jump_sampler`.
pub struct JumpDiffusionProblem<Drift, Diffusion, JumpSampler>
where
    Drift: Fn(f64, f64) -> f64,
    Diffusion: Fn(f64, f64) -> f64,
    JumpSampler: Fn(&mut StdRng) -> f64,
{
    /// Drift coefficient f(x, t)
    pub drift: Drift,
    /// Diffusion coefficient g(x, t)
    pub diffusion: Diffusion,
    /// Poisson jump intensity (λ ≥ 0)
    pub jump_intensity: f64,
    /// Callable returning a jump size: `fn(&mut StdRng) -> f64`
    pub jump_sampler: JumpSampler,
    /// Initial value X(t0)
    pub x0: f64,
    /// Time span (t0, t1)
    pub t_span: (f64, f64),
}

impl<Drift, Diffusion, JumpSampler> JumpDiffusionProblem<Drift, Diffusion, JumpSampler>
where
    Drift: Fn(f64, f64) -> f64,
    Diffusion: Fn(f64, f64) -> f64,
    JumpSampler: Fn(&mut StdRng) -> f64,
{
    /// Create a new jump-diffusion problem.
    pub fn new(
        drift: Drift,
        diffusion: Diffusion,
        jump_intensity: f64,
        jump_sampler: JumpSampler,
        x0: f64,
        t_span: (f64, f64),
    ) -> IntegrateResult<Self> {
        if jump_intensity < 0.0 {
            return Err(IntegrateError::InvalidInput(format!(
                "jump_intensity must be >= 0, got {jump_intensity}"
            )));
        }
        validate_t_span(t_span)?;
        Ok(Self {
            drift,
            diffusion,
            jump_intensity,
            jump_sampler,
            x0,
            t_span,
        })
    }

    /// Solve using Euler-Maruyama with exact Poisson jump timing.
    ///
    /// Returns a vector of `(t, X(t))` pairs.
    pub fn solve(&self, dt: f64, rng: &mut StdRng) -> IntegrateResult<Vec<(f64, f64)>> {
        validate_dt(dt)?;
        let normal =
            Normal::new(0.0, 1.0).map_err(|e| IntegrateError::InvalidInput(e.to_string()))?;
        let uniform = Uniform::new(0.0_f64, 1.0_f64)
            .map_err(|e| IntegrateError::InvalidInput(e.to_string()))?;

        let n_steps = ((self.t_span.1 - self.t_span.0) / dt).ceil() as usize;
        let mut path = Vec::with_capacity(n_steps + 1);
        path.push((self.t_span.0, self.x0));
        let mut x = self.x0;
        let mut t = self.t_span.0;

        for _ in 0..n_steps {
            let step = (self.t_span.1 - t).min(dt);
            let sqrt_step = step.sqrt();
            let z: f64 = normal.sample(rng);
            let fx = (self.drift)(x, t);
            let gx = (self.diffusion)(x, t);
            let n_jumps = poisson_sample(self.jump_intensity * step, rng, &uniform)?;
            let jump_sum: f64 = (0..n_jumps).map(|_| (self.jump_sampler)(rng)).sum();
            x = x + fx * step + gx * z * sqrt_step + jump_sum;
            t += step;
            path.push((t, x));
        }
        Ok(path)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Internal helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Sample from a Poisson distribution with parameter `lambda` using the
/// Knuth algorithm (efficient for small lambda; for large lambda uses normal approx).
fn poisson_sample(lambda: f64, rng: &mut StdRng, uniform: &Uniform<f64>) -> IntegrateResult<usize> {
    if lambda < 0.0 {
        return Err(IntegrateError::InvalidInput(format!(
            "Poisson lambda must be >= 0, got {lambda}"
        )));
    }
    if lambda == 0.0 {
        return Ok(0);
    }
    // For large lambda, use Normal approximation
    if lambda > 30.0 {
        let normal = Normal::new(lambda, lambda.sqrt())
            .map_err(|e| IntegrateError::InvalidInput(e.to_string()))?;
        let sample: f64 = normal.sample(rng);
        return Ok(sample.round().max(0.0) as usize);
    }
    // Knuth algorithm: P(N=k) = exp(-lambda)*lambda^k/k!
    let threshold = (-lambda).exp();
    let mut count = 0usize;
    let mut product = uniform.sample(rng);
    while product > threshold {
        product *= uniform.sample(rng);
        count += 1;
    }
    Ok(count)
}

fn validate_t_span(t_span: (f64, f64)) -> IntegrateResult<()> {
    if t_span.0 >= t_span.1 {
        Err(IntegrateError::InvalidInput(format!(
            "t_span must satisfy t0 < t1, got {:?}",
            t_span
        )))
    } else {
        Ok(())
    }
}

fn validate_dt(dt: f64) -> IntegrateResult<()> {
    if dt <= 0.0 {
        Err(IntegrateError::InvalidInput(format!(
            "dt must be > 0, got {dt}"
        )))
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::random::prelude::seeded_rng;

    #[test]
    fn test_merton_positive_price() {
        let mut rng = seeded_rng(42);
        let path =
            merton_jump_diffusion(0.05, 0.2, 1.0, -0.1, 0.2, 100.0, (0.0, 1.0), 0.01, &mut rng)
                .expect("merton_jump_diffusion should succeed");
        assert!(!path.is_empty());
        assert!(
            path.iter().all(|&(_, s)| s > 0.0),
            "Merton S must stay positive"
        );
    }

    #[test]
    fn test_merton_no_jumps() {
        // When lambda = 0, Merton reduces to GBM
        let mut rng = seeded_rng(1);
        let path =
            merton_jump_diffusion(0.05, 0.2, 0.0, 0.0, 0.0, 100.0, (0.0, 1.0), 0.01, &mut rng)
                .expect("merton_jump_diffusion should succeed");
        assert!(path.iter().all(|&(_, s)| s > 0.0));
    }

    #[test]
    fn test_merton_invalid_sigma() {
        let mut rng = seeded_rng(0);
        assert!(merton_jump_diffusion(
            0.05,
            -0.2,
            1.0,
            0.0,
            0.1,
            100.0,
            (0.0, 1.0),
            0.01,
            &mut rng
        )
        .is_err());
    }

    #[test]
    fn test_merton_invalid_s0() {
        let mut rng = seeded_rng(0);
        assert!(
            merton_jump_diffusion(0.05, 0.2, 1.0, 0.0, 0.1, -1.0, (0.0, 1.0), 0.01, &mut rng)
                .is_err()
        );
    }

    #[test]
    fn test_compound_poisson_basic() {
        let mut rng = seeded_rng(7);
        let normal =
            Normal::new(0.0_f64, 1.0).expect("Normal::new should succeed with valid params");
        let path = compound_poisson_process(2.0, |r| normal.sample(r), (0.0, 5.0), &mut rng)
            .expect("compound_poisson_process should succeed");
        // At minimum: (0.0, 0.0) and (5.0, x_final)
        assert!(path.len() >= 2);
        assert!((path[0].0).abs() < 1e-12, "starts at t0");
        assert!((path[0].1).abs() < 1e-12, "starts at 0");
        assert!(
            (path.last().expect("path is non-empty").0 - 5.0).abs() < 1e-12,
            "ends at t1"
        );
    }

    #[test]
    fn test_compound_poisson_mean_jumps() {
        // E[N(T)] = lambda * T
        let lambda = 3.0;
        let t_end = 2.0;
        let n_paths = 500;
        let mut total_jumps = 0usize;
        for seed in 0..n_paths as u64 {
            let mut rng = seeded_rng(seed + 1000);
            let path = compound_poisson_process(
                lambda,
                |_r| 1.0, // unit jumps
                (0.0, t_end),
                &mut rng,
            )
            .expect("compound_poisson_process should succeed");
            // subtract 2 for start/end points
            total_jumps += path.len().saturating_sub(2);
        }
        let mean_jumps = total_jumps as f64 / n_paths as f64;
        let expected = lambda * t_end;
        assert!(
            (mean_jumps - expected).abs() / expected < 0.15,
            "mean jumps {mean_jumps:.3} vs expected {expected:.3}"
        );
    }

    #[test]
    fn test_compound_poisson_invalid_lambda() {
        let mut rng = seeded_rng(0);
        assert!(compound_poisson_process(0.0, |_| 1.0, (0.0, 1.0), &mut rng).is_err());
        assert!(compound_poisson_process(-1.0, |_| 1.0, (0.0, 1.0), &mut rng).is_err());
    }

    #[test]
    fn test_kou_positive_price() {
        let mut rng = seeded_rng(42);
        let path = kou_double_exponential(
            0.05,
            0.2,
            1.0,
            0.4,
            5.0,
            3.0,
            100.0,
            (0.0, 1.0),
            0.01,
            &mut rng,
        )
        .expect("kou_double_exponential should succeed");
        assert!(
            path.iter().all(|&(_, s)| s > 0.0),
            "Kou S must stay positive"
        );
    }

    #[test]
    fn test_kou_invalid_params() {
        let mut rng = seeded_rng(0);
        // eta1 must be > 1
        assert!(kou_double_exponential(
            0.05,
            0.2,
            1.0,
            0.4,
            0.5,
            3.0,
            100.0,
            (0.0, 1.0),
            0.01,
            &mut rng
        )
        .is_err());
        // p must be in (0,1)
        assert!(kou_double_exponential(
            0.05,
            0.2,
            1.0,
            0.0,
            5.0,
            3.0,
            100.0,
            (0.0, 1.0),
            0.01,
            &mut rng
        )
        .is_err());
    }

    #[test]
    fn test_jump_diffusion_problem() {
        let mut rng = seeded_rng(99);
        let normal =
            Normal::new(0.0_f64, 0.5).expect("Normal::new should succeed with valid params");
        let prob = JumpDiffusionProblem::new(
            |x, _t| 0.05 * x,
            |x, _t| 0.2 * x,
            1.0,
            move |r| normal.sample(r),
            100.0,
            (0.0, 1.0),
        )
        .expect("JumpDiffusionProblem::new should succeed");
        let path = prob
            .solve(0.01, &mut rng)
            .expect("prob.solve should succeed");
        assert!(!path.is_empty());
        assert!((path[0].0 - 0.0).abs() < 1e-12);
        assert!((path[0].1 - 100.0).abs() < 1e-12);
    }

    #[test]
    fn test_poisson_sample_zero_rate() {
        let uniform =
            Uniform::new(0.0_f64, 1.0).expect("Uniform::new should succeed with valid range");
        let mut rng = seeded_rng(0);
        let n = poisson_sample(0.0, &mut rng, &uniform).expect("poisson_sample should succeed");
        assert_eq!(n, 0);
    }

    #[test]
    fn test_validate_t_span() {
        assert!(validate_t_span((0.0, 1.0)).is_ok());
        assert!(validate_t_span((1.0, 0.0)).is_err());
        assert!(validate_t_span((1.0, 1.0)).is_err());
    }
}