rebop 0.10.0

A fast stochastic simulator for chemical reaction networks
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
//! Function-based API to describe chemical reaction networks and
//! simulate them.

use rand::rngs::SmallRng;
use rand::{RngExt, SeedableRng};
use rand_distr::Exp1;

use crate::expr::Expr;

#[derive(Clone, Debug, PartialEq)]
/// Definition of a reaction rate
pub enum Rate {
    /// Reaction rate governed by the Law of Mass Action
    LMA(f64, Vec<u32>),
    /// Reaction rate governed by the Law of mass Action (sparsely represented)
    LMASparse(f64, Vec<(u32, u32)>),
    /// Arbitrary reaction rate
    Expr(Expr),
}

impl Rate {
    /// Build an LMA reaction rate from the coefficient and an array
    /// of stoechiometries (one coefficient for every species).
    pub fn lma<V: AsRef<[u32]>>(rate: f64, stoechiometries: V) -> Self {
        Rate::LMA(rate, stoechiometries.as_ref().to_vec())
    }
    /// Build a sparse LMA reaction rate from the coefficient and an array
    /// of stoechiometries `(species_index, coefficient)`.
    pub fn lma_sparse<V: AsRef<[(u32, u32)]>>(rate: f64, stoechiometries: V) -> Self {
        Rate::LMASparse(rate, stoechiometries.as_ref().to_vec())
    }
    /// Build an arbitrary reaction rate.
    pub fn expr(expr: Expr) -> Self {
        Rate::Expr(expr)
    }
    /// If it is a sparse reaction rate, convert it into a dense one.
    pub fn dense(self) -> Self {
        match self {
            Rate::LMASparse(rate, stoechiometries) => {
                let n = stoechiometries
                    .iter()
                    .map(|(i, _)| i + 1)
                    .max()
                    .unwrap_or(0);
                let mut dense = vec![0; n as usize];
                for (index, exponent) in stoechiometries {
                    dense[index as usize] += exponent;
                }
                Rate::LMA(rate, dense)
            }
            Rate::LMA(_, _) | Rate::Expr(_) => self,
        }
    }
    /// If it is a dense reaction rate, convert it into a sparse one.
    pub fn sparse(self) -> Self {
        match self {
            Rate::LMA(rate, stoechiometries) => {
                let sparse = stoechiometries
                    .iter()
                    .enumerate()
                    .filter_map(|(index, &exponent)| {
                        Some((index as u32, exponent)).filter(|&(_, exponent)| exponent > 0)
                    })
                    .collect();
                Rate::LMASparse(rate, sparse)
            }
            Rate::LMASparse(_, _) | Rate::Expr(_) => self,
        }
    }
    /// Compute the rate given the amount of species
    fn rate(&self, species: &[isize]) -> f64 {
        match self {
            Rate::LMA(rate, reactants) => species
                .iter()
                .zip(reactants.iter())
                .fold(*rate, |acc, (&n, &e)| {
                    (n + 1 - e as isize..=n).fold(acc, |acc, x| acc * x as f64)
                }),
            &Rate::LMASparse(mut rate, ref sparse) => {
                for &(index, exponent) in sparse.iter() {
                    let n = *unsafe { species.get_unchecked(index as usize) };
                    for i in (n + 1 - exponent as isize)..=n {
                        rate *= i as f64;
                    }
                }
                rate
            }
            Rate::Expr(expr) => expr.eval(species),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
/// Representation of the effect of a reaction.
pub enum Jump {
    /// Reaction jump represented as an array of differences
    Flat(Vec<isize>),
    /// Reaction jump represented as a sparse array of differences
    Sparse(Vec<(usize, isize)>),
}

impl Jump {
    /// Create a flat jump from an array of differences.
    pub fn new<V: AsRef<[isize]>>(differences: V) -> Self {
        Jump::Flat(differences.as_ref().to_vec())
    }
    /// Create a sparse jump from an array of `(species_index, difference)`.
    pub fn new_sparse<V: AsRef<[(usize, isize)]>>(sparse: V) -> Self {
        Jump::Sparse(sparse.as_ref().to_vec())
    }
    /// If it is a sparse jump, convert it into a flat one.
    pub fn dense(self) -> Self {
        match self {
            Jump::Sparse(sparse) => {
                let n = sparse.iter().map(|(i, _)| i + 1).max().unwrap_or(0);
                let mut dense = vec![0; n];
                for (index, diff) in sparse {
                    dense[index] += diff;
                }
                Jump::Flat(dense)
            }
            Jump::Flat(_) => self,
        }
    }
    /// If it is a flat jump, convert it into a sparse one.
    pub fn sparse(self) -> Self {
        match self {
            Jump::Flat(differences) => {
                let sparse = differences
                    .iter()
                    .enumerate()
                    .filter_map(|(index, &difference)| {
                        Some((index, difference)).filter(|&(_, difference)| difference != 0)
                    })
                    .collect();
                Jump::Sparse(sparse)
            }
            Jump::Sparse(_) => self,
        }
    }
    /// Perform the jump given the amount of species
    fn affect(&self, species: &mut [isize]) {
        match self {
            Jump::Flat(differences) => species
                .iter_mut()
                .zip(differences.iter())
                .for_each(|(s, d)| *s += d),
            Jump::Sparse(differences) => differences.iter().for_each(|&(index, difference)| {
                *unsafe { species.get_unchecked_mut(index) } += difference
            }),
        }
    }
}

/// Main structure, represents the problem and contains simulation methods.
#[derive(Clone, Debug)]
pub struct Gillespie {
    species: Vec<isize>,
    t: f64,
    reactions: Vec<(Rate, Jump)>,
    rng: SmallRng,
    sparse: bool,
}

impl Gillespie {
    /// Creates a new problem instance, with `N` different species of
    /// specified initial conditions.
    pub fn new<V: AsRef<[isize]>>(species: V, sparse: bool) -> Self {
        Gillespie {
            species: species.as_ref().to_vec(),
            t: 0.,
            reactions: Vec::new(),
            rng: rand::make_rng(),
            sparse,
        }
    }
    /// Creates a new problem instance, with `N` different species of
    /// specified initial conditions, and a fixed random seed `seed`.
    pub fn new_with_seed<V: AsRef<[isize]>>(species: V, sparse: bool, seed: u64) -> Self {
        Gillespie {
            species: species.as_ref().to_vec(),
            t: 0.,
            reactions: Vec::new(),
            rng: SmallRng::seed_from_u64(seed),
            sparse,
        }
    }
    /// Seeds the random number generator.
    pub fn seed(&mut self, seed: u64) {
        self.rng = SmallRng::seed_from_u64(seed);
    }
    /// Returns the number of species in the problem.
    ///
    /// ```
    /// use rebop::gillespie::Gillespie;
    /// let mut p: Gillespie = Gillespie::new([0, 1, 10, 100], false);
    /// assert_eq!(p.nb_species(), 4);
    /// ```
    pub fn nb_species(&self) -> usize {
        self.species.len()
    }
    /// Returns the number of reactions in the problem.
    ///
    /// ```
    /// use rebop::gillespie::Gillespie;
    /// let mut p: Gillespie = Gillespie::new([0, 1, 10, 100], false);
    /// assert_eq!(p.nb_reactions(), 0);
    /// ```
    pub fn nb_reactions(&self) -> usize {
        self.reactions.len()
    }
    /// Adds a reaction to the problem.
    ///
    /// `rate` is the reaction rate and `reaction` is an array
    /// describing the state change as a result of the reaction.
    /// ```
    /// use rebop::gillespie::{Gillespie, Rate};
    /// let mut sir = Gillespie::new([9999, 1, 0], false);
    /// //                           [   S, I, R]
    /// // S + I -> I + I with rate 1e-5
    /// sir.add_reaction(Rate::lma(1e-5, [1, 1, 0]), [-1, 1, 0]);
    /// // I -> R with rate 0.01
    /// sir.add_reaction(Rate::lma(0.01, [0, 1, 0]), [0, -1, 1]);
    /// ```
    pub fn add_reaction<V: AsRef<[isize]>>(&mut self, rate: Rate, differences: V) {
        // This assert ensures that the rate operates on existing species
        match &rate {
            Rate::LMA(_, stoechiometries) => assert_eq!(stoechiometries.len(), self.species.len()),
            Rate::LMASparse(_, stoechiometries) => assert!(
                stoechiometries
                    .iter()
                    .all(|(i, _)| (*i as usize) < self.species.len())
            ),
            Rate::Expr(_) => (),
        }
        // This assert ensures that the jump does not go out of bounds of the species
        assert_eq!(differences.as_ref().len(), self.species.len());
        let jump = Jump::new(differences);
        if self.sparse {
            self.reactions.push((rate.sparse(), jump.sparse()));
        } else {
            self.reactions.push((rate, jump));
        }
    }
    /// Returns the current time in the model.
    pub fn get_time(&self) -> f64 {
        self.t
    }
    /// Sets the current time in the model.
    pub fn set_time(&mut self, t: f64) {
        self.t = t;
    }
    /// Returns the current amount of a species.
    ///
    /// ```
    /// use rebop::gillespie::Gillespie;
    /// let p: Gillespie = Gillespie::new([0, 1, 10, 100], false);
    /// assert_eq!(p.get_species(2), 10);
    /// ```
    pub fn get_species(&self, s: usize) -> isize {
        self.species[s]
    }
    /// Sets the amount of species in the model.
    pub fn set_species<V: AsRef<[isize]>>(&mut self, species: V) {
        assert_eq!(species.as_ref().len(), self.species.len());
        self.species = species.as_ref().to_vec();
    }
    /// Simulates the problem until the next discrete reaction.
    pub fn advance_one_reaction(&mut self) {
        let mut rates = vec![f64::NAN; self.nb_reactions()];
        self._advance_one_reaction(&mut rates);
    }
    /// Simulates the problem for `nb_reactions` reactions.
    pub fn advance_n_reactions(&mut self, nb_reactions: usize) {
        let mut rates = vec![f64::NAN; self.nb_reactions()];
        for _ in 0..nb_reactions {
            self._advance_one_reaction(&mut rates);
        }
    }
    /// Simulates the problem until the next discrete reaction or until `tmax`:
    /// whichever happens first.
    /// If the current time is already larger than `tmax`, does nothing.
    pub fn advance_one_reaction_or_until(&mut self, tmax: f64) {
        if tmax <= self.t {
            return;
        }
        let mut rates = vec![f64::NAN; self.nb_reactions()];
        self._advance_one_reaction_or_until(&mut rates, tmax);
    }
    /// Simulates the problem for `nb_reactions` or until `tmax`:
    /// whichever happens first.
    /// If the current time is already larger than `tmax`, does nothing.
    pub fn advance_n_reactions_or_until(&mut self, nb_reactions: usize, tmax: f64) {
        if tmax <= self.t {
            return;
        }
        let mut rates = vec![f64::NAN; self.nb_reactions()];
        for _ in 0..nb_reactions {
            self._advance_one_reaction_or_until(&mut rates, tmax);
            if tmax <= self.t {
                return;
            }
        }
    }

    #[inline]
    pub(crate) fn _advance_one_reaction(&mut self, rates: &mut [f64]) {
        // let total_rate = make_rates(&self.reactions, &self.species, rates);
        let total_rate = make_cumrates(&self.reactions, &self.species, rates);

        // we don't want to use partial_cmp, for performance
        #[allow(clippy::neg_cmp_op_on_partial_ord)]
        if !(0. < total_rate) {
            self.t = f64::INFINITY;
            return;
        }
        self.t += self.rng.sample::<f64, _>(Exp1) / total_rate;
        let chosen_rate = total_rate * self.rng.random::<f64>();

        // let ireaction = choose_rate_sum(chosen_rate, rates);
        // let ireaction = choose_rate_for(chosen_rate, rates);
        let ireaction = choose_cumrate_sum(chosen_rate, rates);
        // let ireaction = choose_cumrate_for(chosen_rate, rates);
        // let ireaction = choose_cumrate_takewhile(chosen_rate, rates);
        // here we have ireaction < self.reactions.len() because chosen_rate < total_rate
        let reaction = unsafe { self.reactions.get_unchecked(ireaction) };

        reaction.1.affect(&mut self.species);
    }

    #[inline]
    fn _advance_one_reaction_or_until(&mut self, rates: &mut [f64], tmax: f64) {
        // let total_rate = make_rates(&self.reactions, &self.species, rates);
        let total_rate = make_cumrates(&self.reactions, &self.species, rates);

        // we don't want to use partial_cmp, for performance
        #[allow(clippy::neg_cmp_op_on_partial_ord)]
        if !(0. < total_rate) {
            self.t = tmax;
            return;
        }
        self.t += self.rng.sample::<f64, _>(Exp1) / total_rate;
        if self.t > tmax {
            self.t = tmax;
            return;
        }
        let chosen_rate = total_rate * self.rng.random::<f64>();

        // let ireaction = choose_rate_sum(chosen_rate, rates);
        // let ireaction = choose_rate_for(chosen_rate, rates);
        let ireaction = choose_cumrate_sum(chosen_rate, rates);
        // let ireaction = choose_cumrate_for(chosen_rate, rates);
        // let ireaction = choose_cumrate_takewhile(chosen_rate, rates);
        // here we have ireaction < self.reactions.len() because chosen_rate < total_rate
        let reaction = unsafe { self.reactions.get_unchecked(ireaction) };

        reaction.1.affect(&mut self.species);
    }
    /// Simulates the problem until `tmax`.
    ///
    /// If `tmax` is less than the current `t`, does nothing.
    ///
    /// ```
    /// use rebop::gillespie::{Gillespie, Rate};
    /// let mut dimers = Gillespie::new([1, 0, 0, 0], false);
    /// //                              [G, M, P, D]
    /// dimers.add_reaction(Rate::lma(25., [1, 0, 0, 0]), [0, 1, 0, 0]);
    /// dimers.add_reaction(Rate::lma(1000., [0, 1, 0, 0]), [0, 0, 1, 0]);
    /// dimers.add_reaction(Rate::lma(0.001, [0, 0, 2, 0]), [0, 0, -2, 1]);
    /// dimers.add_reaction(Rate::lma(0.1, [0, 1, 0, 0]), [0, -1, 0, 0]);
    /// dimers.add_reaction(Rate::lma(1., [0, 0, 1, 0]), [0, 0, -1, 0]);
    /// assert_eq!(dimers.get_time(), 0.);
    /// assert_eq!(dimers.get_species(3), 0);
    /// dimers.advance_until(1.);
    /// assert_eq!(dimers.get_time(), 1.);
    /// assert!(dimers.get_species(3) > 0);
    /// ```
    pub fn advance_until(&mut self, tmax: f64) {
        let mut rates = vec![f64::NAN; self.reactions.len()];
        if tmax < self.t {
            return;
        }
        loop {
            //let total_rate = make_rates(&self.reactions, &self.species, &mut rates);
            let total_rate = make_cumrates(&self.reactions, &self.species, &mut rates);

            // we don't want to use partial_cmp, for performance
            #[allow(clippy::neg_cmp_op_on_partial_ord)]
            if !(0. < total_rate) {
                self.t = tmax;
                return;
            }
            self.t += self.rng.sample::<f64, _>(Exp1) / total_rate;
            if self.t > tmax {
                self.t = tmax;
                return;
            }
            let chosen_rate = total_rate * self.rng.random::<f64>();

            //let ireaction = choose_rate_sum(chosen_rate, &rates);
            //let ireaction = choose_rate_for(chosen_rate, &rates);
            let ireaction = choose_cumrate_sum(chosen_rate, &rates);
            //let ireaction = choose_cumrate_for(chosen_rate, &rates);
            //let ireaction = choose_cumrate_takewhile(chosen_rate, &rates);
            // here we have ireaction < self.reactions.len() because chosen_rate < total_rate
            let reaction = unsafe { self.reactions.get_unchecked(ireaction) };

            reaction.1.affect(&mut self.species);
        }
    }
}

#[allow(dead_code)]
fn make_rates(reactions: &[(Rate, Jump)], species: &[isize], rates: &mut [f64]) -> f64 {
    let mut total_rate = 0.0;
    for ((rate, _), num_rate) in reactions.iter().zip(rates.iter_mut()) {
        *num_rate = rate.rate(species);
        total_rate += *num_rate;
    }
    total_rate
}

fn make_cumrates(reactions: &[(Rate, Jump)], species: &[isize], cum_rates: &mut [f64]) -> f64 {
    let mut total_rate = 0.0;
    for ((rate, _), cum_rate) in reactions.iter().zip(cum_rates.iter_mut()) {
        *cum_rate = total_rate + rate.rate(species);
        total_rate = *cum_rate;
    }
    total_rate
}

#[allow(dead_code)]
fn choose_rate_for(mut chosen_rate: f64, rates: &[f64]) -> usize {
    let mut ireaction = rates.len() - 1;
    for (ir, &rate) in rates.iter().enumerate() {
        chosen_rate -= rate;
        if chosen_rate < 0. {
            ireaction = ir;
            break;
        }
    }
    ireaction
}

#[allow(dead_code)]
fn choose_cumrate_for(chosen_rate: f64, cumrates: &[f64]) -> usize {
    let mut ireaction = cumrates.len() - 1;
    for (ir, &cumrate) in cumrates.iter().enumerate() {
        if chosen_rate < cumrate {
            ireaction = ir;
            break;
        }
    }
    ireaction
}

#[allow(dead_code)]
fn choose_rate_sum(chosen_rate: f64, rates: &[f64]) -> usize {
    rates
        .iter()
        .scan(0.0, |cum, &r| {
            *cum += r;
            Some(if *cum < chosen_rate { 1 } else { 0 })
        })
        .sum()
}

fn choose_cumrate_sum(chosen_rate: f64, cumrates: &[f64]) -> usize {
    cumrates
        .iter()
        .map(|&cum| if cum < chosen_rate { 1 } else { 0 })
        .sum()
}

#[allow(dead_code)]
fn choose_cumrate_takewhile(chosen_rate: f64, cumrates: &[f64]) -> usize {
    cumrates
        .iter()
        .take_while(|&&cum| cum < chosen_rate)
        .count()
}

#[cfg(test)]
mod tests {
    use crate::gillespie::{Expr, Gillespie, Jump, Rate};

    #[test]
    fn rate_conversion() {
        let rate = Rate::lma(2.0, [3]);
        assert_eq!(rate.clone().dense(), rate);
        assert_eq!(rate.clone().sparse(), Rate::lma_sparse(2.0, [(0, 3)]));
        assert_eq!(rate.clone().sparse().dense(), rate);
        let rate = Rate::lma_sparse(2.0, [(0, 1), (3, 2)]);
        assert_eq!(rate.clone().sparse(), rate);
        assert_eq!(rate.clone().dense(), Rate::lma(2.0, [1, 0, 0, 2]));
        assert_eq!(rate.clone().dense().sparse(), rate);
        let rate = Rate::expr(Expr::Constant(4.1));
        assert_eq!(rate.clone().dense(), rate);
        assert_eq!(rate.clone().sparse(), rate);
    }

    #[test]
    fn rate_sparse() {
        let rate = Rate::lma(2.0, [3]);
        assert_eq!(rate.sparse(), Rate::LMASparse(2.0, vec![(0, 3)]));
        let rate = Rate::lma(2.0, [0, 3]);
        assert_eq!(rate.sparse(), Rate::LMASparse(2.0, vec![(1, 3)]));
        let rate = Rate::lma(2.0, [0, 3, 0]);
        assert_eq!(rate.sparse(), Rate::LMASparse(2.0, vec![(1, 3)]));
        let rate = Rate::lma(2.0, [0, 3, 0, 1, 0, 0]);
        assert_eq!(rate.sparse(), Rate::LMASparse(2.0, vec![(1, 3), (3, 1)]));
    }

    #[test]
    fn rate_lma() {
        fn check_rate(rate: &Rate, species: &[isize], expected: f64) {
            assert_eq!(rate.clone().dense().rate(species), expected);
            assert_eq!(rate.clone().sparse().rate(species), expected);
        }

        let species = [5, 3];
        check_rate(&Rate::lma(2.0, [1, 0]), &species, 10.0);
        check_rate(&Rate::lma(2.0, [2, 0]), &species, 40.0);
        check_rate(&Rate::lma(2.0, [3, 0]), &species, 120.0);
        check_rate(&Rate::lma(2.0, [4, 0]), &species, 240.0);
        check_rate(&Rate::lma(2.0, [5, 0]), &species, 240.0);
        check_rate(&Rate::lma(2.0, [6, 0]), &species, 0.0);
        check_rate(&Rate::lma(2.0, [7, 0]), &species, 0.0);
        check_rate(&Rate::lma(2.0, [0, 1]), &species, 6.0);
        check_rate(&Rate::lma(2.0, [0, 2]), &species, 12.0);
        check_rate(&Rate::lma(2.0, [0, 3]), &species, 12.0);
        check_rate(&Rate::lma(2.0, [0, 4]), &species, 0.0);
        check_rate(&Rate::lma(2.0, [0, 5]), &species, 0.0);
        check_rate(&Rate::lma(2.0, [1, 1]), &species, 30.0);
        check_rate(&Rate::lma(2.0, [1, 2]), &species, 60.0);
        check_rate(&Rate::lma(2.0, [2, 1]), &species, 120.0);
        check_rate(&Rate::lma(2.0, [1, 20]), &species, 0.0);
    }

    #[test]
    fn jump_conversion() {
        let djump = Jump::new([-1, 0, 3, -2]);
        let sjump = Jump::new_sparse([(0, -1), (2, 3), (3, -2)]);
        assert_eq!(djump.clone().dense(), djump);
        assert_eq!(djump.clone().sparse(), sjump);
        assert_eq!(sjump.clone().sparse(), sjump);
        assert_eq!(sjump.clone().dense(), djump);
    }

    #[test]
    fn jump_affect() {
        let djump = Jump::new([-1, 0, 3, -2]);
        let mut species = vec![10; 4];
        djump.affect(&mut species);
        assert_eq!(species, vec![9, 10, 13, 8]);
        let sjump = Jump::new_sparse([(0, -1), (2, 3), (3, -2)]);
        let mut species = vec![10; 4];
        sjump.affect(&mut species);
        assert_eq!(species, vec![9, 10, 13, 8]);
    }

    #[test]
    fn advance_until() {
        let mut sir = Gillespie::new([9999, 1, 0], false);
        sir.add_reaction(Rate::lma(0.1 / 10000., [1, 1, 0]), [-1, 1, 0]);
        sir.add_reaction(Rate::lma(0.01, [0, 1, 0]), [0, -1, 1]);
        sir.advance_until(1.0);
        assert_eq!(sir.get_time(), 1.0);
        sir.advance_until(2.0);
        assert_eq!(sir.get_time(), 2.0);
        sir.advance_until(1.5);
        assert_eq!(sir.get_time(), 2.0);
    }

    #[test]
    fn n_reactions() {
        for n in 0..15 {
            let mut decay = Gillespie::new([10], false);
            decay.add_reaction(Rate::lma(1.0, [1]), [-1]);
            decay.advance_n_reactions(n);
            if n <= 10 {
                assert_eq!(decay.get_species(0), (10 - n) as isize);
                assert!(decay.get_time() < f64::INFINITY);
            } else {
                assert_eq!(decay.get_species(0), 0);
                assert_eq!(decay.get_time(), f64::INFINITY);
            }
        }
    }

    #[test]
    fn n_reactions_or_until() {
        let mut got_both = 0;
        let n_reactions = 5;
        let tmax = 0.6;
        for _ in 0..1000 {
            let mut decay = Gillespie::new([10, 0], false);
            decay.add_reaction(Rate::lma(1.0, [1, 0]), [-1, 1]);
            decay.advance_n_reactions_or_until(n_reactions, tmax);
            if decay.get_time() == tmax {
                got_both |= 1;
                assert!(decay.get_species(1) < n_reactions as isize);
            } else {
                got_both |= 2;
                assert!(decay.get_time() < tmax);
                assert_eq!(decay.get_species(1), n_reactions as isize);
            }
        }
        assert_eq!(got_both, 3);
    }

    #[test]
    fn n_reactions_or_until_too_much() {
        let n_reactions = 15;
        for tmax in [0.6, 6.0, 60.0, 600.0] {
            for _ in 0..1000 {
                let mut decay = Gillespie::new([10, 0], false);
                decay.add_reaction(Rate::lma(1.0, [1, 0]), [-1, 1]);
                decay.advance_n_reactions_or_until(n_reactions, tmax);
                assert_eq!(decay.get_time(), tmax);
                assert!(decay.get_species(1) < n_reactions as isize);
            }
        }
    }

    #[test]
    fn no_reactions() {
        let mut sir = Gillespie::new([10000, 0, 0], false);
        sir.add_reaction(Rate::lma(0.1 / 10000., [1, 1, 0]), [-1, 1, 0]);
        sir.add_reaction(Rate::lma(0.01, [0, 1, 0]), [0, -1, 1]);
        sir.advance_n_reactions(10);
        assert_eq!(sir.get_species(0), 10000);
        assert_eq!(sir.get_species(1), 0);
        assert_eq!(sir.get_species(2), 0);
        assert_eq!(sir.get_time(), f64::INFINITY);
        sir.set_time(0.0);
        sir.advance_until(1.0);
        assert_eq!(sir.get_species(0), 10000);
        assert_eq!(sir.get_species(1), 0);
        assert_eq!(sir.get_species(2), 0);
        assert_eq!(sir.get_time(), 1.0);
        sir.advance_one_reaction();
        assert_eq!(sir.get_species(0), 10000);
        assert_eq!(sir.get_species(1), 0);
        assert_eq!(sir.get_species(2), 0);
        assert_eq!(sir.get_time(), f64::INFINITY);
    }

    #[test]
    #[should_panic(expected = "assertion failed")]
    fn issue85_oob() {
        let mut sim = Gillespie::new([1], true);
        let rate = Rate::lma_sparse(1.0, [(10, 1)]);
        sim.add_reaction(rate, [0]);
    }

    #[test]
    fn gillespie_sir() {
        let mut sir = Gillespie::new([9999, 1, 0], false);
        sir.add_reaction(Rate::lma(0.1 / 10000., [1, 1, 0]), [-1, 1, 0]);
        sir.add_reaction(Rate::lma(0.01, [0, 1, 0]), [0, -1, 1]);
        for i in 1..=250 {
            sir.advance_until(i as f64);
            assert_eq!(
                sir.get_species(0) + sir.get_species(1) + sir.get_species(2),
                10000
            );
        }
    }

    #[test]
    fn gillespie_dimers() {
        let mut dimers = Gillespie::new([1, 0, 0, 0], false);
        dimers.add_reaction(Rate::lma(25., [1, 0, 0, 0]), [0, 1, 0, 0]);
        dimers.add_reaction(Rate::lma(1000., [0, 1, 0, 0]), [0, 0, 1, 0]);
        dimers.add_reaction(Rate::lma(0.001, [0, 0, 2, 0]), [0, 0, -2, 1]);
        dimers.add_reaction(Rate::lma(0.1, [0, 1, 0, 0]), [0, -1, 0, 0]);
        dimers.add_reaction(Rate::lma(1., [0, 0, 1, 0]), [0, 0, -1, 0]);
        dimers.advance_until(1.);
        assert_eq!(dimers.get_species(0), 1);
        assert!(1000 < dimers.get_species(2));
        assert!(dimers.get_species(3) < 10000);
    }
}