th_rust/simulator/
plot.rs1use plotters::prelude::*;
3
4pub struct Plotter {
5 data: Vec<u32>,
6 buckets: usize,
7}
8
9impl Plotter {
10 pub fn new(buckets: usize) -> Plotter {
11 Plotter {
12 data: Vec::new(),
13 buckets
14 }
15 }
16
17 pub fn add_sample(&mut self, config: &Vec<i32>) {
18 let number = self.config_to_num(config);
20 self.data.push(number);
21 }
22
23 pub fn plot(&self, name: &str) -> Result<(), Box<dyn std::error::Error>> {
24 let path = String::from("out/") + &name;
26 let root = BitMapBackend::new(&path, (1024, 768)).into_drawing_area();
27 root.fill(&WHITE)?;
28
29 let mut chart = ChartBuilder::on(&root)
30 .x_label_area_size(35)
31 .y_label_area_size(40)
32 .margin(5)
33 .caption("MCMC Sweep", ("sans-serif", 50.0))
34 .build_cartesian_2d((0u32..(self.buckets - 1) as u32).into_segmented(), 0u32..3000u32)?;
35
36 chart
37 .configure_mesh()
38 .disable_x_mesh()
39 .bold_line_style(&WHITE.mix(0.3))
40 .y_desc("Frequency")
41 .x_desc("Spin State")
42 .axis_desc_style(("sans-serif", 15))
43 .draw()?;
44
45 chart.draw_series(
46 Histogram::vertical(&chart)
47 .style(BLUE.mix(0.5).filled())
48 .data(self.data.iter().map(|x: &u32| (*x, 1))),
49 ).unwrap();
50
51 root.present().expect("Unable to write result to file, please make sure 'plotters-doc-data' dir exists under current dir");
52 Ok(())
53 }
54
55 fn spin_to_bit(&self, spin: i32) -> u32 {
56 if spin == 1 {
57 1
58 } else {
59 0
60 }
61 }
62
63 fn config_to_num(&self, c: &Vec<i32>) -> u32 {
64 let mut power = 1;
65 let mut number = 0;
66
67 for val in c.iter().rev() {
68 number += self.spin_to_bit(*val) * power;
69 power <<= 1;
70 }
71
72 number
73 }
74}