qmc 2.20.0

Quantum Monte Carlo simulations in Rust
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
use crate::sse::fast_ops::FastOps;
use crate::sse::parallel_tempering::tempering_traits::*;
use crate::sse::qmc_ising::QmcIsingGraph;
use crate::sse::qmc_traits::*;
use itertools::Itertools;
use rand::prelude::ThreadRng;
use rand::Rng;
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::cmp::min;

/// A tempering container using FastOps and FastOpNodes.
pub type DefaultTemperingContainer<R1, R2> = TemperingContainer<R1, QmcIsingGraph<R2, FastOps>>;

/// A container to perform parallel tempering.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct TemperingContainer<R, Q>
where
    R: Rng,
    Q: QmcStepper + GraphWeights + SwapManagers,
{
    // Graph and beta
    graphs: Vec<(Q, f64)>,
    rng: Option<R>,

    // Pairwise equality comparisons
    graph_ham_eq_a: Option<Vec<bool>>,
    graph_ham_eq_b: Option<Vec<bool>>,

    // Sort of a debug parameter to see how well swaps are going.
    total_swaps: u64,
}

/// Make a new parallel tempering container.
pub fn new_with_rng<R2: Rng, R: Rng>(rng: R) -> DefaultTemperingContainer<R, R2> {
    TemperingContainer::new(rng)
}

/// Make a new parallel tempering container.
pub fn new_thread_rng() -> DefaultTemperingContainer<ThreadRng, ThreadRng> {
    new_with_rng(rand::thread_rng())
}

impl<R, Q> TemperingContainer<R, Q>
where
    R: Rng,
    Q: QmcStepper + GraphWeights + SwapManagers,
{
    /// Make a new tempering container. All graphs will share this set of edges
    /// and start with this cutoff.
    pub fn new(rng: R) -> Self {
        Self {
            rng: Some(rng),
            graph_ham_eq_a: None,
            graph_ham_eq_b: None,
            graphs: vec![],
            total_swaps: 0,
        }
    }

    /// Add a QMC instance to the tempering container. Returns an Err if the added QMCStepper
    /// cannot be swapped with the existing steppers.
    pub fn add_qmc_stepper(&mut self, q: Q, beta: f64) -> Result<(), String> {
        self.graphs
            .last()
            .map(|(g, _)| g.can_swap_graphs(&q))
            .unwrap_or(Ok(()))?;
        self.graph_ham_eq_a = None;
        self.graph_ham_eq_b = None;
        self.graphs.push((q, beta));
        Ok(())
    }

    /// Perform a series of qmc timesteps on each graph.
    pub fn timesteps(&mut self, t: usize) {
        self.graphs.iter_mut().for_each(|(g, beta)| {
            g.timesteps(t, *beta);
        })
    }

    fn make_first_subgraphs(&mut self) -> &mut [(Q, f64)] {
        if self.graphs.len() % 2 == 0 {
            self.graphs.as_mut_slice()
        } else {
            let n = self.graphs.len();
            &mut self.graphs[0..n - 1]
        }
    }

    fn make_second_subgraphs(&mut self) -> &mut [(Q, f64)] {
        if self.graphs.len() % 2 == 1 {
            &mut self.graphs[1..]
        } else {
            let n = self.graphs.len();
            &mut self.graphs[1..n - 1]
        }
    }

    fn make_ham_equalities(&mut self) {
        let graphs = self.make_first_subgraphs();
        self.graph_ham_eq_a = Some(Self::make_eqs_from_graphs(graphs));

        let graphs = self.make_second_subgraphs();
        self.graph_ham_eq_b = Some(Self::make_eqs_from_graphs(graphs));
    }

    fn make_eqs_from_graphs(graphs: &[(Q, f64)]) -> Vec<bool> {
        graphs
            .iter()
            .map(|(g, _)| g)
            .chunks(2)
            .into_iter()
            .map(unwrap_chunk)
            .map(|(ga, gb)| ga.ham_eq(gb))
            .collect()
    }

    /// Perform a tempering step.
    pub fn tempering_step(&mut self) {
        if self.graphs.len() <= 1 {
            return;
        }
        if self.graph_ham_eq_a.is_none() || self.graph_ham_eq_b.is_none() {
            self.make_ham_equalities()
        }

        let max_cutoff = self
            .graphs
            .iter()
            .map(|(g, _)| g.get_op_cutoff())
            .max()
            .unwrap();
        self.graphs
            .iter_mut()
            .for_each(|(g, _)| g.set_op_cutoff(max_cutoff));
        let mut rng = self.rng.take().unwrap();

        if rng.gen_bool(0.5) {
            self.tempering_a(&mut rng);
            self.tempering_b(&mut rng);
        } else {
            self.tempering_b(&mut rng);
            self.tempering_a(&mut rng);
        }

        self.rng = Some(rng);
    }

    fn tempering_a<R1: Rng>(&mut self, rng: R1) {
        let hameqs = self.graph_ham_eq_a.take().unwrap();
        let graphs = self.make_first_subgraphs();
        self.total_swaps += perform_swaps(rng, graphs, &hameqs);
        self.graph_ham_eq_a = Some(hameqs);
    }

    fn tempering_b<R1: Rng>(&mut self, rng: R1) {
        let hameqs = self.graph_ham_eq_b.take().unwrap();
        let graphs = self.make_second_subgraphs();
        self.total_swaps += perform_swaps(rng, graphs, &hameqs);
        self.graph_ham_eq_b = Some(hameqs);
    }

    /// Perform timesteps and sample spins. Return average energy for each graph.
    pub fn timesteps_sample(
        &mut self,
        timesteps: usize,
        replica_swap_freq: usize,
        sampling_freq: usize,
    ) -> Vec<(Vec<Vec<bool>>, f64)> {
        let mut states = (0..self.num_graphs())
            .map(|_| Vec::<Vec<bool>>::with_capacity(timesteps / sampling_freq))
            .collect::<Vec<_>>();
        let mut energy_acc = vec![0.0; self.num_graphs()];

        let mut remaining_timesteps = timesteps;
        let mut time_to_swap = replica_swap_freq;
        let mut time_to_sample = sampling_freq;

        while remaining_timesteps > 0 {
            let t = min(min(time_to_sample, time_to_swap), remaining_timesteps);
            self.graphs
                .iter_mut()
                .map(|(g, beta)| g.timesteps(t, *beta))
                .zip(energy_acc.iter_mut())
                .for_each(|(te, e)| {
                    *e += te * t as f64;
                });
            time_to_sample -= t;
            time_to_swap -= t;
            remaining_timesteps -= t;

            if time_to_swap == 0 {
                self.tempering_step();
                time_to_swap = replica_swap_freq;
            }
            if time_to_sample == 0 {
                let graphs = self.graphs.iter().map(|(g, _)| g);
                states
                    .iter_mut()
                    .zip(graphs)
                    .for_each(|(s, g)| s.push(g.state_ref().to_vec()));
                time_to_sample = sampling_freq;
            }
        }
        states.into_iter().zip(energy_acc.into_iter()).collect()
    }

    /// Apply f to each graph's state.
    pub fn iter_over_states<F>(&self, f: F)
    where
        F: Fn(&[bool]),
    {
        self.graphs.iter().for_each(|(g, _)| f(g.state_ref()))
    }

    /// Return a reference to the list of graphs and their temperatures.
    pub fn graph_ref(&self) -> &[(Q, f64)] {
        &self.graphs
    }
    /// Return a mutable reference to the list of graphs and their temperatures.
    pub fn graph_mut(&mut self) -> &mut [(Q, f64)] {
        &mut self.graphs
    }
    /// Get the number of graphs in the container.
    pub fn num_graphs(&self) -> usize {
        self.graphs.len()
    }
    /// Get the total number of successful tempering swaps which have occurred.
    pub fn get_total_swaps(&self) -> u64 {
        self.total_swaps
    }

    /// Get mutable access to internal rng for doing associated tasks.
    pub fn rng_mut(&mut self) -> &mut R {
        self.rng.as_mut().unwrap()
    }
}

fn perform_swaps<R, Q>(mut rng: R, graphs: &mut [(Q, f64)], hameqs: &[bool]) -> u64
where
    R: Rng,
    Q: QmcStepper + GraphWeights + SwapManagers,
{
    assert_eq!(graphs.len() % 2, 0);
    if graphs.is_empty() {
        0
    } else {
        graphs
            .iter_mut()
            .chunks(2)
            .into_iter()
            .map(unwrap_chunk)
            .map(|x| (x, rng.gen_range(0. ..1.0)))
            .zip(hameqs.iter())
            .map(|(((ga, gb), p), eq)| if swap_on_chunks(ga, gb, p, !eq) { 1 } else { 0 })
            .sum()
    }
}

fn unwrap_chunk<T, It>(it: It) -> (T, T)
where
    It: IntoIterator<Item = T>,
{
    let mut graphs: SmallVec<[T; 2]> = it.into_iter().collect();
    assert_eq!(graphs.len(), 2);
    let gb: T = graphs.pop().unwrap();
    let ga: T = graphs.pop().unwrap();
    (ga, gb)
}

/// Returns true if a swap occurs.
fn swap_on_chunks<'a, Q>(
    graph_beta_a: &'a mut (Q, f64),
    graph_beta_b: &'a mut (Q, f64),
    p: f64,
    evaluate_hamiltonians: bool,
) -> bool
where
    Q: QmcStepper + GraphWeights + SwapManagers,
{
    let (ga, ba) = graph_beta_a;
    let (gb, bb) = graph_beta_b;

    let rel_h_weight = if !evaluate_hamiltonians {
        1.0
    } else {
        let rel_bstate = ga.relative_weight(gb);
        let rel_astate = gb.relative_weight(ga);
        rel_bstate * rel_astate
    };

    let temp_swap = (*ba / *bb).powi(gb.get_n() as i32 - ga.get_n() as i32);
    let p_swap = temp_swap * rel_h_weight;
    if p_swap > p {
        ga.swap_graphs(gb);
        true
    } else {
        false
    }
}

impl<R, Q> Verify for TemperingContainer<R, Q>
where
    R: Rng,
    Q: QmcStepper + GraphWeights + SwapManagers + Verify,
{
    fn verify(&self) -> bool {
        self.graphs.iter().all(|(q, _)| q.verify())
    }
}

/// Tempering using parallelization and threads.
#[cfg(feature = "parallel-tempering")]
pub mod rayon_tempering {
    use super::*;
    use rayon::prelude::*;

    /// Parallel tempering steps.
    pub trait ParallelQmcTimeSteps {
        /// Perform qmc steps.
        fn parallel_timesteps(&mut self, t: usize);

        /// Perform a tempering step in parallel.
        fn parallel_tempering_step(&mut self);

        /// Perform qmc steps and apply f to the states.
        fn parallel_iter_over_states<F>(&self, f: F)
        where
            F: Fn(&[bool]) + Sync;

        /// Perform qmc steps and return states and energies.
        fn parallel_timesteps_sample(
            &mut self,
            timesteps: usize,
            replica_swap_freq: usize,
            sampling_freq: usize,
        ) -> Vec<(Vec<Vec<bool>>, f64)>;
    }

    fn parallel_tempering_a<R: Rng, Q, R1: Rng>(tc: &mut TemperingContainer<R, Q>, rng: R1)
    where
        Q: QmcStepper + GraphWeights + SwapManagers + Send + Sync,
    {
        let hameqs = tc.graph_ham_eq_a.take().unwrap();
        let graphs = tc.make_first_subgraphs();
        tc.total_swaps += parallel_perform_swaps(rng, graphs, &hameqs);
        tc.graph_ham_eq_a = Some(hameqs);
    }

    fn parallel_tempering_b<R: Rng, Q, R1: Rng>(tc: &mut TemperingContainer<R, Q>, rng: R1)
    where
        Q: QmcStepper + GraphWeights + SwapManagers + Send + Sync,
    {
        let hameqs = tc.graph_ham_eq_b.take().unwrap();
        let graphs = tc.make_second_subgraphs();
        tc.total_swaps += perform_swaps(rng, graphs, &hameqs);
        tc.graph_ham_eq_b = Some(hameqs);
    }

    impl<R, Q> ParallelQmcTimeSteps for TemperingContainer<R, Q>
    where
        R: Rng,
        Q: QmcStepper + GraphWeights + SwapManagers + Send + Sync,
    {
        fn parallel_timesteps(&mut self, t: usize) {
            self.graphs.par_iter_mut().for_each(|(g, beta)| {
                g.timesteps(t, *beta);
            });
        }

        fn parallel_tempering_step(&mut self) {
            if self.graphs.is_empty() {
                return;
            }
            if self.graph_ham_eq_a.is_none() || self.graph_ham_eq_b.is_none() {
                self.make_ham_equalities()
            }

            let max_cutoff = self
                .graphs
                .par_iter()
                .map(|(g, _)| g.get_op_cutoff())
                .max()
                .unwrap();
            self.graphs
                .par_iter_mut()
                .for_each(|(g, _)| g.set_op_cutoff(max_cutoff));

            let mut rng = self.rng.take().unwrap();

            if rng.gen_bool(0.5) {
                parallel_tempering_a(self, &mut rng);
                parallel_tempering_b(self, &mut rng);
            } else {
                parallel_tempering_b(self, &mut rng);
                parallel_tempering_a(self, &mut rng);
            }

            self.rng = Some(rng);
        }

        fn parallel_iter_over_states<F>(&self, f: F)
        where
            F: Fn(&[bool]) + Sync,
        {
            self.graphs.par_iter().for_each(|(g, _)| f(g.state_ref()))
        }

        fn parallel_timesteps_sample(
            &mut self,
            timesteps: usize,
            replica_swap_freq: usize,
            sampling_freq: usize,
        ) -> Vec<(Vec<Vec<bool>>, f64)> {
            let mut states = (0..self.num_graphs())
                .map(|_| Vec::<Vec<bool>>::with_capacity(timesteps / sampling_freq))
                .collect::<Vec<_>>();
            let mut energy_acc = vec![0.0; self.num_graphs()];

            let mut remaining_timesteps = timesteps;
            let mut time_to_swap = replica_swap_freq;
            let mut time_to_sample = sampling_freq;

            while remaining_timesteps > 0 {
                let t = min(min(time_to_sample, time_to_swap), remaining_timesteps);
                self.graphs
                    .par_iter_mut()
                    .map(|(g, beta)| g.timesteps(t, *beta))
                    .zip(energy_acc.par_iter_mut())
                    .for_each(|(te, e)| {
                        *e += te * t as f64;
                    });
                time_to_sample -= t;
                time_to_swap -= t;
                remaining_timesteps -= t;

                if time_to_swap == 0 {
                    self.parallel_tempering_step();
                    time_to_swap = replica_swap_freq;
                }
                if time_to_sample == 0 {
                    let graphs = self.graphs.par_iter().map(|(g, _)| g);
                    states
                        .par_iter_mut()
                        .zip(graphs)
                        .for_each(|(s, g)| s.push(g.state_ref().to_vec()));
                    time_to_sample = sampling_freq;
                }
            }
            states.into_iter().zip(energy_acc.into_iter()).collect()
        }
    }

    fn parallel_perform_swaps<R, Q>(mut rng: R, graphs: &mut [(Q, f64)], hameqs: &[bool]) -> u64
    where
        R: Rng,
        Q: QmcStepper + GraphWeights + SwapManagers + Send + Sync,
    {
        assert_eq!(graphs.len() % 2, 0);
        if graphs.is_empty() {
            0
        } else {
            // Generate probs for bools ahead of time, this way we can parallelize.
            let probs = (0..graphs.len() / 2)
                .map(|_| rng.gen_range(0. ..1.0))
                .collect::<Vec<_>>();
            graphs
                .par_iter_mut()
                .chunks(2)
                .map(|g| unwrap_chunk(g.into_iter()))
                .zip(probs.into_par_iter())
                .zip(hameqs.into_par_iter())
                .map(|(((ga, gb), p), eq)| if swap_on_chunks(ga, gb, p, !eq) { 1 } else { 0 })
                .sum()
        }
    }

    /// Autocorrelation calculations for states.
    #[cfg(feature = "autocorrelations")]
    pub mod autocorrelations {
        use super::*;
        use crate::sse::autocorrelations::fft_autocorrelation;
        use crate::sse::QmcBondAutoCorrelations;

        /// A collection of functions to calculate autocorrelations.
        pub trait ParallelTemperingAutocorrelations<Q> {
            /// Calculate autocorrelations on spin variables.
            fn calculate_variable_autocorrelation(
                &mut self,
                timesteps: usize,
                replica_swap_freq: Option<usize>,
                sampling_freq: Option<usize>,
            ) -> Vec<Vec<f64>>;

            /// Calculate autocorrelations on the output of f applied to states.
            fn calculate_autocorrelation<F>(
                &mut self,
                timesteps: usize,
                replica_swap_freq: Option<usize>,
                sampling_freq: Option<usize>,
                sample_mapper: F,
            ) -> Vec<Vec<f64>>
            where
                F: Fn(&[bool], &Q) -> Vec<f64> + Copy + Send + Sync;

            /// Take autocorrelations of products of spins.
            fn calculate_spin_product_autocorrelation(
                &mut self,
                timesteps: usize,
                replica_swap_freq: Option<usize>,
                var_products: &[&[usize]],
                sampling_freq: Option<usize>,
            ) -> Vec<Vec<f64>>;
        }

        /// Allows parallel computation of bond variables.
        pub trait ParallelTemperingBondAutoCorrelations<Q>:
            ParallelTemperingAutocorrelations<Q>
        {
            /// Calculate autocorrelations on bonds.
            fn calculate_bond_autocorrelation(
                &mut self,
                timesteps: usize,
                replica_swap_freq: Option<usize>,
                sampling_freq: Option<usize>,
            ) -> Vec<Vec<f64>>;
        }

        impl<R, Q> ParallelTemperingAutocorrelations<Q> for TemperingContainer<R, Q>
        where
            R: Rng,
            Q: QmcStepper + GraphWeights + SwapManagers + Send + Sync,
        {
            fn calculate_variable_autocorrelation(
                &mut self,
                timesteps: usize,
                replica_swap_freq: Option<usize>,
                sampling_freq: Option<usize>,
            ) -> Vec<Vec<f64>> {
                self.calculate_autocorrelation(
                    timesteps,
                    replica_swap_freq,
                    sampling_freq,
                    |sample, _| {
                        sample
                            .iter()
                            .cloned()
                            .map(|b| if b { 1.0 } else { -1.0 })
                            .collect()
                    },
                )
            }

            fn calculate_spin_product_autocorrelation(
                &mut self,
                timesteps: usize,
                replica_swap_freq: Option<usize>,
                var_products: &[&[usize]],
                sampling_freq: Option<usize>,
            ) -> Vec<Vec<f64>> {
                self.calculate_autocorrelation(
                    timesteps,
                    replica_swap_freq,
                    sampling_freq,
                    |sample, _| {
                        var_products
                            .iter()
                            .map(|vs| {
                                vs.iter()
                                    .map(|v| if sample[*v] { 1.0 } else { -1.0 })
                                    .product()
                            })
                            .collect()
                    },
                )
            }

            fn calculate_autocorrelation<F>(
                &mut self,
                timesteps: usize,
                replica_swap_freq: Option<usize>,
                sampling_freq: Option<usize>,
                sample_mapper: F,
            ) -> Vec<Vec<f64>>
            where
                F: Fn(&[bool], &Q) -> Vec<f64> + Copy + Send + Sync,
            {
                let replica_swap_freq = replica_swap_freq.unwrap_or(1);
                let sampling_freq = sampling_freq.unwrap_or(1);
                let states_and_energies =
                    self.parallel_timesteps_sample(timesteps, replica_swap_freq, sampling_freq);

                states_and_energies
                    .iter()
                    .zip(self.graphs.iter())
                    .map(|((samples, _), (q, _))| {
                        let samples = samples
                            .iter()
                            .map(|s| sample_mapper(s, q))
                            .collect::<Vec<_>>();
                        fft_autocorrelation(&samples)
                    })
                    .collect::<Vec<_>>()
            }
        }

        impl<R, Q> ParallelTemperingBondAutoCorrelations<Q> for TemperingContainer<R, Q>
        where
            R: Rng,
            Q: QmcStepper + GraphWeights + QmcBondAutoCorrelations + SwapManagers + Send + Sync,
        {
            fn calculate_bond_autocorrelation(
                &mut self,
                timesteps: usize,
                replica_swap_freq: Option<usize>,
                sampling_freq: Option<usize>,
            ) -> Vec<Vec<f64>> {
                self.calculate_autocorrelation(
                    timesteps,
                    replica_swap_freq,
                    sampling_freq,
                    |sample, q| {
                        let nbonds = q.n_bonds();
                        (0..nbonds)
                            .map(|bond| q.value_for_bond(bond, sample))
                            .collect()
                    },
                )
            }
        }
    }

    #[cfg(test)]
    mod parallel_swap_test {
        use super::*;
        use crate::sse::*;
        use rand::prelude::SmallRng;
        use rand::SeedableRng;

        #[test]
        fn test_basic() -> Result<(), String> {
            let rng1 = SmallRng::seed_from_u64(0u64);

            let edges = vec![((0, 1), 1.0), ((1, 2), 1.0), ((2, 3), 1.0), ((3, 4), 1.0)];
            let mut temper = new_with_rng::<SmallRng, _>(rng1);
            for _ in 0..2 {
                let rng = SmallRng::seed_from_u64(0u64);
                let qmc = DefaultQmcIsingGraph::<SmallRng>::new_with_rng(
                    edges.clone(),
                    0.1,
                    0.,
                    10,
                    rng,
                    None,
                );
                temper.add_qmc_stepper(qmc, 10.0)?;
            }
            temper.timesteps(100);
            assert!(temper.verify());

            temper.parallel_tempering_step();
            assert!(temper.verify());
            Ok(())
        }
    }
}

/// Add serialization helpers which drop rng to only store graph states.
#[cfg(feature = "serialize")]
pub mod serialization {
    use super::*;
    use crate::sse::qmc_ising::serialization::*;
    use crate::sse::qmc_ising::*;
    use rand::SeedableRng;

    /// Default serializable tempering container.
    pub type DefaultSerializeTemperingContainer = SerializeTemperingContainer<FastOps>;
    type SerializeGraphBeta<M> = (SerializeQmcGraph<M>, f64);

    /// A tempering container with no rng. Just for serialization.
    #[derive(Debug, Serialize, Deserialize)]
    pub struct SerializeTemperingContainer<M: IsingManager> {
        graphs: Vec<SerializeGraphBeta<M>>,
        total_swaps: u64,
    }

    impl<R1, R2, M> From<TemperingContainer<R1, QmcIsingGraph<R2, M>>>
        for (SerializeTemperingContainer<M>, R1, Vec<R2>)
    where
        R1: Rng,
        R2: Rng,
        M: IsingManager,
    {
        fn from(
            tc: TemperingContainer<R1, QmcIsingGraph<R2, M>>,
        ) -> (SerializeTemperingContainer<M>, R1, Vec<R2>) {
            let (graphs, rngs) = tc
                .graphs
                .into_iter()
                .map(|(g, beta)| {
                    let (sg, rng) = g.into();
                    ((sg, beta), rng)
                })
                .unzip();

            let sg = SerializeTemperingContainer {
                graphs,
                total_swaps: tc.total_swaps,
            };
            (sg, tc.rng.unwrap(), rngs)
        }
    }

    impl<R1, R2, M> From<TemperingContainer<R1, QmcIsingGraph<R2, M>>>
        for SerializeTemperingContainer<M>
    where
        R1: Rng,
        R2: Rng,
        M: IsingManager,
    {
        fn from(
            tc: TemperingContainer<R1, QmcIsingGraph<R2, M>>,
        ) -> SerializeTemperingContainer<M> {
            SerializeTemperingContainer {
                graphs: tc
                    .graphs
                    .into_iter()
                    .map(|(g, beta)| (g.into(), beta))
                    .collect(),
                total_swaps: tc.total_swaps,
            }
        }
    }

    impl<M> SerializeTemperingContainer<M>
    where
        M: IsingManager,
    {
        /// Get the number of graphs.
        pub fn num_graphs(&self) -> usize {
            self.graphs.len()
        }

        /// Generate rngs from container rng.
        pub fn into_tempering_container_gen_rngs<R1, R2>(
            self,
            mut container_rng: R1,
        ) -> TemperingContainer<R1, QmcIsingGraph<R2, M>>
        where
            R1: Rng,
            R2: Rng + SeedableRng,
        {
            let seeds = (0..self.num_graphs()).map(|_| container_rng.gen());
            let graph_rngs = seeds.map(R2::seed_from_u64).collect();
            self.into_tempering_container_from_vec(container_rng, graph_rngs)
        }

        /// Convert into a tempering container using the set of rngs.
        pub fn into_tempering_container_from_vec<R1: Rng, R2: Rng>(
            self,
            container_rng: R1,
            graph_rngs: Vec<R2>,
        ) -> TemperingContainer<R1, QmcIsingGraph<R2, M>> {
            assert_eq!(self.graphs.len(), graph_rngs.len());
            self.into_tempering_container(container_rng, graph_rngs.into_iter())
        }

        /// Convert into a tempering container using the iterator of rngs.
        pub fn into_tempering_container<R1: Rng, R2: Rng, It>(
            self,
            container_rng: R1,
            graph_rngs: It,
        ) -> TemperingContainer<R1, QmcIsingGraph<R2, M>>
        where
            It: IntoIterator<Item = R2>,
        {
            TemperingContainer {
                graphs: self
                    .graphs
                    .into_iter()
                    .zip(graph_rngs.into_iter())
                    .map(|((g, beta), rng)| (g.into_qmc(rng), beta))
                    .collect(),
                rng: Some(container_rng),
                graph_ham_eq_a: None,
                graph_ham_eq_b: None,
                total_swaps: self.total_swaps,
            }
        }
    }
}

#[cfg(test)]
mod swap_test {
    use super::*;
    use crate::sse::*;
    use rand::prelude::SmallRng;
    use rand::SeedableRng;

    #[test]
    fn test_basic() -> Result<(), String> {
        let rng1 = SmallRng::seed_from_u64(0u64);

        let edges = vec![((0, 1), 1.0), ((1, 2), 1.0), ((2, 3), 1.0), ((3, 4), 1.0)];

        let mut temper = new_with_rng::<SmallRng, SmallRng>(rng1);
        for _ in 0..2 {
            let rng = SmallRng::seed_from_u64(0u64);
            let qmc = DefaultQmcIsingGraph::<SmallRng>::new_with_rng(
                edges.clone(),
                0.1,
                0.,
                10,
                rng,
                None,
            );
            temper.add_qmc_stepper(qmc, 10.0)?;
        }
        temper.timesteps(1);
        assert!(temper.verify());

        temper.tempering_step();
        assert!(temper.verify());
        Ok(())
    }

    #[test]
    fn test_bondstrength() -> Result<(), String> {
        let rng1 = SmallRng::seed_from_u64(0u64);

        let edges = vec![((0, 1), 1.0), ((1, 2), 1.0), ((2, 3), 1.0), ((3, 4), 1.0)];

        let mut temper = new_with_rng::<SmallRng, SmallRng>(rng1);
        for i in 1..10 {
            let rng = SmallRng::seed_from_u64(0u64);
            let qmc = DefaultQmcIsingGraph::<SmallRng>::new_with_rng(
                edges
                    .iter()
                    .cloned()
                    .map(|(e, j)| (e, j * i as f64 / 10.))
                    .collect(),
                0.1,
                0.,
                10,
                rng,
                None,
            );
            temper.add_qmc_stepper(qmc, 10.0)?;
        }
        temper.timesteps(1000);
        assert!(temper.verify());

        temper.tempering_step();
        assert!(temper.verify());
        Ok(())
    }

    #[test]
    fn test_convert() -> Result<(), String> {
        let rng1 = SmallRng::seed_from_u64(0u64);

        let edges = vec![((0, 1), 1.0), ((1, 2), 1.0), ((2, 3), 1.0), ((3, 4), 1.0)];

        let mut temper = new_with_rng::<SmallRng, SmallRng>(rng1);
        for _ in 0..2 {
            let rng = SmallRng::seed_from_u64(0u64);
            let qmc = DefaultQmcIsingGraph::<SmallRng>::new_with_rng(
                edges.clone(),
                0.1,
                0.,
                10,
                rng,
                None,
            );
            temper.add_qmc_stepper(qmc, 10.0)?;
        }

        let stemper: DefaultSerializeTemperingContainer = temper.into();

        let rng1 = SmallRng::seed_from_u64(0u64);
        let _temper =
            stemper.into_tempering_container(rng1, (0..2).map(|_| SmallRng::seed_from_u64(0u64)));
        Ok(())
    }
}