Skip to main content

qecp/
model_graph.rs

1//! build model graph from simulator and measurement results
2//!
3
4use super::either::Either;
5use super::float_cmp;
6use super::noise_model::*;
7use super::simulator::*;
8use super::types::*;
9use super::util_macros::*;
10use super::visualize::*;
11#[cfg(feature = "python_binding")]
12use pyo3::prelude::*;
13use serde::{Deserialize, Serialize};
14use std::collections::BTreeMap;
15use std::sync::{Arc, Mutex};
16
17/// edges connecting two nontrivial measurements generated by a single error
18#[derive(Debug, Clone, Serialize)]
19#[cfg_attr(feature = "python_binding", pyclass)]
20pub struct ModelGraph {
21    pub nodes: Vec<Vec<Vec<Option<Box<ModelGraphNode>>>>>,
22}
23
24impl QecpVisualizer for ModelGraph {
25    fn component_info(&self, abbrev: bool) -> (String, serde_json::Value) {
26        let name = "model_graph";
27        let info = json!({
28            "nodes": (0..self.nodes.len()).map(|t| {
29                (0..self.nodes[t].len()).map(|i| {
30                    (0..self.nodes[t][i].len()).map(|j| {
31                        let position = &pos!(t, i, j);
32                        if self.is_node_exist(position) {
33                            let node = self.get_node_unwrap(position);
34                            let mut edges = serde_json::Map::with_capacity(node.edges.len());
35                            for (peer_position, edge) in node.edges.iter() {
36                                edges.insert(peer_position.to_string(), edge.component_edge_info(abbrev));
37                            }
38                            let mut all_edges = serde_json::Map::with_capacity(node.all_edges.len());
39                            for (peer_position, all_edge) in node.all_edges.iter() {
40                                let (edges, _) = all_edge;
41                                let components: Vec<_> = edges.iter().map(|edge| edge.component_edge_info(abbrev)).collect();
42                                all_edges.insert(peer_position.to_string(), json!(components));
43                            }
44                            Some(json!({
45                                if abbrev { "p" } else { "position" }: position,  // for readability
46                                "all_edges": all_edges,
47                                "edges": edges,
48                                "all_boundaries": node.all_boundaries.iter().map(|boundary| boundary.component_edge_info(abbrev)).collect::<Vec<_>>(),
49                                "boundary": node.boundary.as_ref().map(|boundary| boundary.component_edge_info(abbrev)),
50                            }))
51                        } else {
52                            None
53                        }
54                    }).collect::<Vec<Option<serde_json::Value>>>()
55                }).collect::<Vec<Vec<Option<serde_json::Value>>>>()
56            }).collect::<Vec<Vec<Vec<Option<serde_json::Value>>>>>(),
57        });
58        (name.to_string(), info)
59    }
60}
61
62/// only defined for measurement nodes (including virtual measurement nodes)
63#[derive(Debug, Clone, Serialize)]
64pub struct ModelGraphNode {
65    /// used when building the graph, record all possible edges that connect the two measurement syndromes.
66    /// (this might be dropped to save memory usage after election)
67    pub all_edges: BTreeMap<Position, (Vec<ModelGraphEdge>, Vec<BriefModelGraphEdge>)>,
68    /// the elected edges, to make sure each pair of nodes only have one edge
69    pub edges: BTreeMap<Position, ModelGraphEdge>,
70    /// all boundary edges defined by a single qubit error generating only one nontrivial measurement.
71    pub all_boundaries: Vec<ModelGraphBoundary>,
72    /// the elected boundary out of all, note that `virtual_node` not necessarily present
73    pub boundary: Option<Box<ModelGraphBoundary>>,
74}
75
76/// without concrete correction, can be used to save memory but not all error pattern will be recorded
77#[derive(Debug, Clone, Serialize)]
78pub struct BriefModelGraphEdge {
79    /// the probability of this edge to happen
80    pub probability: f64,
81    /// the weight of this edge computed by the (combined) probability, e.g. ln((1-p)/p)
82    pub weight: f64,
83}
84
85#[derive(Debug, Clone, Serialize)]
86pub struct ModelGraphEdge {
87    /// the probability of this edge to happen
88    pub probability: f64,
89    /// the weight of this edge computed by the (combined) probability, e.g. ln((1-p)/p)
90    pub weight: f64,
91    /// the error that causes this edge
92    pub error_pattern: Arc<SparseErrorPattern>,
93    /// the correction pattern that can recover this error
94    pub correction: Arc<SparseCorrection>,
95}
96
97impl ModelGraphEdge {
98    fn component_edge_info(&self, abbrev: bool) -> serde_json::Value {
99        json!({
100            if abbrev { "p" } else { "probability" }: self.probability,
101            if abbrev { "w" } else { "weight" }: self.weight,
102            if abbrev { "e" } else { "error_pattern" }: self.error_pattern,
103            if abbrev { "c" } else { "correction" }: self.correction,
104        })
105    }
106}
107
108#[derive(Debug, Clone, Serialize)]
109pub struct ModelGraphBoundary {
110    /// the probability of this boundary edge to happen
111    pub probability: f64,
112    /// the weight of this edge computed by the (combined) probability, e.g. ln((1-p)/p)
113    pub weight: f64,
114    /// the error that causes this boundary edge
115    pub error_pattern: Arc<SparseErrorPattern>,
116    /// the correction pattern that can recover this error
117    pub correction: Arc<SparseCorrection>,
118    /// if virtual node presents, record it, otherwise the model graph is still constructed successfully
119    pub virtual_node: Option<Position>,
120}
121
122impl ModelGraphBoundary {
123    fn component_edge_info(&self, abbrev: bool) -> serde_json::Value {
124        json!({
125            if abbrev { "p" } else { "probability" }: self.probability,
126            if abbrev { "w" } else { "weight" }: self.weight,
127            if abbrev { "e" } else { "error_pattern" }: self.error_pattern,
128            if abbrev { "c" } else { "correction" }: self.correction,
129            if abbrev { "v" } else { "virtual_node" }: self.virtual_node,
130        })
131    }
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub enum WeightFunction {
136    /// Autotune: compute weight based on noise model
137    Autotune,
138    /// Autotune improved for large physical error rate p
139    AutotuneImproved,
140    /// Manhattan distance (not exactly because there is 12 neighbors instead of 8 in circuit-level noise model CSS surface code)
141    Unweighted,
142}
143
144pub mod weight_function {
145
146    pub fn autotune(p: f64) -> f64 {
147        if p > 0. {
148            -p.ln()
149        } else {
150            f64::from(f32::MAX)
151        } // use f32::MAX is enough, also this allows weights to be added without overflow
152    }
153
154    pub fn autotune_improved(p: f64) -> f64 {
155        if p > 0. {
156            (1. - p).ln() - p.ln()
157        } else {
158            f64::from(f32::MAX)
159        } // use f32::MAX is enough, also this allows weights to be added without overflow
160    }
161
162    pub fn unweighted(p: f64) -> f64 {
163        if p > 0. {
164            1.
165        } else {
166            f64::from(f32::MAX)
167        } // use f32::MAX is enough, also this allows weights to be added without overflow
168    }
169}
170
171impl ModelGraph {
172    /// initialize the structure corresponding to a `Simulator`
173    pub fn new(simulator: &Simulator) -> Self {
174        assert!(simulator.volume() > 0, "cannot build model graph out of zero-sized simulator");
175        Self {
176            nodes: (0..simulator.height)
177                .map(|t| {
178                    (0..simulator.vertical)
179                        .map(|i| {
180                            (0..simulator.horizontal)
181                                .map(|j| {
182                                    let position = &pos!(t, i, j);
183                                    // model graph only contains real node at measurement round
184                                    if t != 0 && t % simulator.measurement_cycles == 0 && simulator.is_node_real(position) {
185                                        let node = simulator.get_node_unwrap(position);
186                                        if node.gate_type.is_measurement() {
187                                            // only define model graph node for measurements
188                                            return Some(Box::new(ModelGraphNode {
189                                                all_edges: BTreeMap::new(),
190                                                edges: BTreeMap::new(),
191                                                all_boundaries: Vec::with_capacity(0), // only a few nodes have boundary, so no need to have initial capacity
192                                                boundary: None,
193                                            }));
194                                        }
195                                    }
196                                    None
197                                })
198                                .collect()
199                        })
200                        .collect()
201                })
202                .collect(),
203        }
204    }
205
206    /// any valid position of the simulator is a valid position in model graph, but only some of these positions corresponds a valid node in model graph
207    pub fn get_node(&'_ self, position: &Position) -> &'_ Option<Box<ModelGraphNode>> {
208        &self.nodes[position.t][position.i][position.j]
209    }
210
211    /// check if a position contains model graph node
212    pub fn is_node_exist(&self, position: &Position) -> bool {
213        self.get_node(position).is_some()
214    }
215
216    /// get reference `self.nodes[t][i][j]` and then unwrap
217    pub fn get_node_unwrap(&'_ self, position: &Position) -> &'_ ModelGraphNode {
218        self.get_node(position).as_ref().unwrap()
219    }
220
221    /// get mutable reference `self.nodes[t][i][j]` and unwrap
222    pub fn get_node_mut_unwrap(&'_ mut self, position: &Position) -> &'_ mut ModelGraphNode {
223        self.nodes[position.t][position.i][position.j].as_mut().unwrap()
224    }
225
226    /// build model graph given the simulator
227    pub fn build(
228        &mut self,
229        simulator: &mut Simulator,
230        noise_model: Arc<NoiseModel>,
231        weight_function: &WeightFunction,
232        parallel: usize,
233        use_combined_probability: bool,
234        use_brief_edge: bool,
235    ) {
236        match weight_function {
237            WeightFunction::Autotune => self.build_with_weight_function(
238                simulator,
239                noise_model,
240                weight_function::autotune,
241                parallel,
242                use_combined_probability,
243                use_brief_edge,
244            ),
245            WeightFunction::AutotuneImproved => self.build_with_weight_function(
246                simulator,
247                noise_model,
248                weight_function::autotune_improved,
249                parallel,
250                use_combined_probability,
251                use_brief_edge,
252            ),
253            WeightFunction::Unweighted => self.build_with_weight_function(
254                simulator,
255                noise_model,
256                weight_function::unweighted,
257                parallel,
258                use_combined_probability,
259                use_brief_edge,
260            ),
261        }
262    }
263
264    /// single-thread computation with region
265    fn build_with_weight_function_region<F>(
266        &mut self,
267        simulator: &mut Simulator,
268        noise_model: Arc<NoiseModel>,
269        weight_of: F,
270        t_start: usize,
271        t_end: usize,
272        use_brief_edge: bool,
273    ) where
274        F: Fn(f64) -> f64 + Copy,
275    {
276        // calculate all possible errors to be iterated
277        let mut all_possible_errors: Vec<Either<ErrorType, CorrelatedPauliErrorType>> = Vec::new();
278        for error_type in ErrorType::all_possible_errors().drain(..) {
279            all_possible_errors.push(Either::Left(error_type));
280        }
281        for correlated_error_type in CorrelatedPauliErrorType::all_possible_errors().drain(..) {
282            all_possible_errors.push(Either::Right(correlated_error_type));
283        }
284        // clear the states in simulator including pauli, erasure errors and propagated errors
285        simulator.clear_all_errors();
286        // iterate over all possible errors at all possible positions
287        simulator_iter!(simulator, position, {
288            if position.t < t_start || position.t >= t_end {
289                continue;
290            }
291            let noise_model_node = noise_model.get_node_unwrap(position);
292            // whether it's possible to have erasure error at this node
293            let possible_erasure_error =
294                noise_model_node.erasure_error_rate > 0. || noise_model_node.correlated_erasure_error_rates.is_some() || {
295                    let node = simulator.get_node_unwrap(position);
296                    if let Some(gate_peer) = node.gate_peer.as_ref() {
297                        let peer_noise_model_node = noise_model.get_node_unwrap(gate_peer);
298                        if let Some(correlated_erasure_error_rates) = &peer_noise_model_node.correlated_erasure_error_rates {
299                            correlated_erasure_error_rates.error_probability() > 0.
300                        } else {
301                            false
302                        }
303                    } else {
304                        false
305                    }
306                };
307            for error in all_possible_errors.iter() {
308                let p = match error {
309                    Either::Left(error_type) => noise_model_node.pauli_error_rates.error_rate(error_type),
310                    Either::Right(error_type) => match &noise_model_node.correlated_pauli_error_rates {
311                        Some(correlated_pauli_error_rates) => correlated_pauli_error_rates.error_rate(error_type),
312                        None => 0.,
313                    },
314                }; // probability of this error to occur
315                let is_erasure = possible_erasure_error && error.is_left();
316                if p > 0. || is_erasure {
317                    // use possible errors to build `all_edges`
318                    // simulate the error and measure it
319                    let mut sparse_errors = SparseErrorPattern::new();
320                    match error {
321                        Either::Left(error_type) => {
322                            sparse_errors.add(position.clone(), *error_type);
323                        }
324                        Either::Right(error_type) => {
325                            sparse_errors.add(position.clone(), error_type.my_error());
326                            let node = simulator.get_node_unwrap(position);
327                            let gate_peer = node
328                                .gate_peer
329                                .as_ref()
330                                .expect("correlated error must corresponds to a two-qubit gate");
331                            sparse_errors.add((**gate_peer).clone(), error_type.peer_error());
332                        }
333                    }
334                    let sparse_errors = Arc::new(sparse_errors); // make it immutable and shared
335                    let (sparse_correction, sparse_measurement_real, sparse_measurement_virtual) =
336                        simulator.fast_measurement_given_few_errors(&sparse_errors);
337                    let sparse_correction = Arc::new(sparse_correction); // make it immutable and shared
338                    let sparse_measurement_real = sparse_measurement_real.to_vec();
339                    let sparse_measurement_virtual = sparse_measurement_virtual.to_vec();
340                    if sparse_measurement_real.is_empty() {
341                        // no way to detect it, ignore
342                        continue;
343                    }
344                    // println!("{:?} at {} will cause measurement errors: real {:?} and virtual {:?}", error, position, sparse_measurement_real, sparse_measurement_virtual);
345                    if sparse_measurement_real.len() == 1 {
346                        // boundary edge
347                        let position = &sparse_measurement_real[0];
348                        if p > 0. || is_erasure {
349                            // add this boundary edge
350                            let model_graph_node = self.get_node_mut_unwrap(position);
351                            model_graph_node.all_boundaries.push(ModelGraphBoundary {
352                                probability: p,
353                                weight: weight_of(p),
354                                error_pattern: sparse_errors.clone(),
355                                correction: sparse_correction.clone(),
356                                virtual_node: if sparse_measurement_virtual.len() == 1 {
357                                    Some(sparse_measurement_virtual[0].clone())
358                                } else {
359                                    None
360                                },
361                            });
362                        }
363                    }
364                    if sparse_measurement_real.len() == 2 {
365                        // normal edge
366                        let position1 = &sparse_measurement_real[0];
367                        let position2 = &sparse_measurement_real[1];
368                        let node1 = simulator.get_node_unwrap(position1);
369                        let node2 = simulator.get_node_unwrap(position2);
370                        // edge only happen when qubit type is the same (to isolate X and Z decoding graph in CSS surface code)
371                        let is_same_type = if cfg!(feature = "include_different_type_edges") {
372                            true
373                        } else {
374                            node1.qubit_type == node2.qubit_type
375                        };
376                        if is_same_type && (p > 0. || is_erasure) {
377                            self.add_edge_between(
378                                (position1, position2),
379                                p,
380                                weight_of(p),
381                                sparse_errors.clone(),
382                                sparse_correction.clone(),
383                                use_brief_edge,
384                            );
385                        }
386                    }
387                }
388            }
389        });
390    }
391
392    /// build model graph given the simulator with customized weight function;
393    /// if `optimize_memory_usage` is set to True, then not all edges are recorded but only the optimal one
394    pub fn build_with_weight_function<F>(
395        &mut self,
396        simulator: &mut Simulator,
397        noise_model: Arc<NoiseModel>,
398        weight_of: F,
399        parallel: usize,
400        use_combined_probability: bool,
401        use_brief_edge: bool,
402    ) where
403        F: Fn(f64) -> f64 + Copy + Send + Sync + 'static,
404    {
405        debug_assert!({
406            let mut state_clean = true;
407            simulator_iter!(simulator, position, node, {
408                // here I omitted the condition `t % measurement_cycles == 0` for a stricter check
409                if position.t != 0 && node.gate_type.is_measurement() && simulator.is_node_real(position) {
410                    let model_graph_node = self.get_node_unwrap(position);
411                    if !model_graph_node.all_edges.is_empty() || !model_graph_node.edges.is_empty() {
412                        state_clean = false;
413                    }
414                }
415            });
416            if !state_clean {
417                println!("[warning] state must be clean before calling `build`, please make sure you don't call this function twice");
418            }
419            state_clean
420        });
421        if parallel <= 1 {
422            self.build_with_weight_function_region(simulator, noise_model, weight_of, 0, simulator.height, use_brief_edge);
423        } else {
424            // spawn `parallel` threads to compute in parallel
425            let mut handlers = Vec::new();
426            let mut instances = Vec::new();
427            let interval = simulator.height / parallel;
428            for parallel_idx in 0..parallel {
429                let instance = Arc::new(Mutex::new(self.clone()));
430                let mut simulator = simulator.clone();
431                instances.push(Arc::clone(&instance));
432                let t_start = parallel_idx * interval; // included
433                let mut t_end = (parallel_idx + 1) * interval; // excluded
434                if parallel_idx == parallel - 1 {
435                    t_end = simulator.height; // to make sure every part is included
436                }
437                let noise_model = Arc::clone(&noise_model);
438                handlers.push(std::thread::spawn(move || {
439                    let mut instance = instance.lock().unwrap();
440                    instance.build_with_weight_function_region(
441                        &mut simulator,
442                        noise_model,
443                        weight_of,
444                        t_start,
445                        t_end,
446                        use_brief_edge,
447                    );
448                }));
449            }
450            for handler in handlers.drain(..) {
451                handler.join().unwrap();
452            }
453            // move the data from instances (without additional large memory allocation)
454            for instance in instances.iter() {
455                let mut instance = instance.lock().unwrap();
456                simulator_iter!(simulator, position, delta_t => simulator.measurement_cycles, if instance.is_node_exist(position) {
457                    let instance_model_graph_node = instance.get_node_mut_unwrap(position);
458                    let model_graph_node = self.get_node_mut_unwrap(position);
459                    for boundary in instance_model_graph_node.all_boundaries.drain(..) {
460                        model_graph_node.all_boundaries.push(boundary);
461                    }
462                    let mut all_edges = BTreeMap::new();
463                    std::mem::swap(&mut all_edges, &mut instance_model_graph_node.all_edges);
464                    for (target, (mut edges, mut brief_edges)) in all_edges.into_iter() {
465                        if !model_graph_node.all_edges.contains_key(&target) {
466                            model_graph_node.all_edges.insert(target.clone(), (Vec::new(), Vec::new()));
467                        }
468                        let (node_edges, node_brief_edges) = model_graph_node.all_edges.get_mut(&target).unwrap();
469                        for edge in edges.drain(..) {
470                            node_edges.push(edge);
471                        }
472                        for brief_edge in brief_edges.drain(..) {
473                            node_brief_edges.push(brief_edge);
474                        }
475                    }
476                });
477            }
478        }
479        self.elect_edges(simulator, use_combined_probability, weight_of); // by default use combined probability
480    }
481
482    /// add asymmetric edge from `source` to `target`; in order to create symmetric edge, call this function twice with reversed input
483    pub fn add_edge(
484        &mut self,
485        positions: (&Position, &Position),
486        probability: f64,
487        weight: f64,
488        error_pattern: Arc<SparseErrorPattern>,
489        correction: Arc<SparseCorrection>,
490        use_brief_edge: bool,
491    ) {
492        let (source, target) = positions;
493        let node = self.get_node_mut_unwrap(source);
494        if !node.all_edges.contains_key(target) {
495            node.all_edges.insert(target.clone(), (Vec::new(), Vec::new()));
496        }
497        let (node_edges, node_brief_edges) = node.all_edges.get_mut(target).unwrap();
498        if use_brief_edge {
499            if node_edges.is_empty() {
500                node_edges.push(ModelGraphEdge {
501                    probability,
502                    weight,
503                    error_pattern,
504                    correction,
505                });
506            } else if probability > node_edges[0].probability {
507                // replace it
508                node_brief_edges.push(BriefModelGraphEdge {
509                    probability: node_edges[0].probability,
510                    weight: node_edges[0].weight,
511                });
512                node_edges.push(ModelGraphEdge {
513                    probability,
514                    weight,
515                    error_pattern,
516                    correction,
517                });
518            } else {
519                // put it into brief node
520                node_brief_edges.push(BriefModelGraphEdge { probability, weight });
521            }
522        } else {
523            node_edges.push(ModelGraphEdge {
524                probability,
525                weight,
526                error_pattern,
527                correction,
528            });
529        }
530    }
531
532    /// add symmetric edge between `source` and `target`
533    pub fn add_edge_between(
534        &mut self,
535        positions: (&Position, &Position),
536        probability: f64,
537        weight: f64,
538        error_pattern: Arc<SparseErrorPattern>,
539        correction: Arc<SparseCorrection>,
540        use_brief_edge: bool,
541    ) {
542        self.add_edge(
543            positions,
544            probability,
545            weight,
546            error_pattern.clone(),
547            correction.clone(),
548            use_brief_edge,
549        );
550        self.add_edge(
551            (positions.1, positions.0),
552            probability,
553            weight,
554            error_pattern.clone(),
555            correction.clone(),
556            use_brief_edge,
557        );
558    }
559
560    /// unlike [`CompleteModelGraph::build_correction_matching`], this function can only match between incident nodes
561    pub fn build_correction_matching(&self, source: &Position, target: &Position) -> &SparseCorrection {
562        let node = self.get_node_unwrap(source);
563        let edge = node.edges.get(target);
564        &edge.as_ref().unwrap().correction
565    }
566
567    pub fn build_correction_boundary(&self, source: &Position) -> &SparseCorrection {
568        let node = self.get_node_unwrap(source);
569        &node.boundary.as_ref().unwrap().correction
570    }
571
572    /// if there are multiple edges connecting two stabilizer measurements, elect the best one
573    pub fn elect_edges<F>(&mut self, simulator: &Simulator, use_combined_probability: bool, weight_of: F)
574    where
575        F: Fn(f64) -> f64 + Copy,
576    {
577        simulator_iter!(simulator, position, delta_t => simulator.measurement_cycles, if self.is_node_exist(position) {
578            let model_graph_node = self.get_node_mut_unwrap(position);
579            // elect normal edges
580            for (target, (edges, brief_edges)) in model_graph_node.all_edges.iter() {
581                let mut elected_idx = 0;
582                let mut elected_probability = edges[0].probability;
583                for i in 1..edges.len() {
584                    let edge = &edges[i];
585                    // update `elected_probability`
586                    if use_combined_probability {
587                        elected_probability = elected_probability * (1. - edge.probability) + edge.probability * (1. - elected_probability);  // XOR
588                    } else {
589                        elected_probability = elected_probability.max(edge.probability);
590                    }
591                    // update `elected_idx`
592                    let best_edge = &edges[elected_idx];
593                    if edge.probability > best_edge.probability {
594                        elected_idx = i;  // set as best, use its
595                    }
596                }
597                for brief_edge in brief_edges.iter() {
598                    if use_combined_probability {
599                        elected_probability = elected_probability * (1. - brief_edge.probability) + brief_edge.probability * (1. - elected_probability);  // XOR
600                    }
601                }
602                let elected = ModelGraphEdge {
603                    probability: elected_probability,
604                    weight: weight_of(elected_probability),
605                    error_pattern: edges[elected_idx].error_pattern.clone(),
606                    correction: edges[elected_idx].correction.clone(),
607                };
608                // update elected edge
609                // println!("{} to {} elected probability: {}", position, target, elected.probability);
610                model_graph_node.edges.insert(target.clone(), elected);
611            }
612            // elect boundary edge
613            if !model_graph_node.all_boundaries.is_empty() {
614                let mut elected_idx = 0;
615                let mut elected_probability = model_graph_node.all_boundaries[0].probability;
616                for i in 1..model_graph_node.all_boundaries.len() {
617                    let edge = &model_graph_node.all_boundaries[i];
618                    // update `elected_probability`
619                    if use_combined_probability {
620                        elected_probability = elected_probability * (1. - edge.probability) + edge.probability * (1. - elected_probability);  // XOR
621                    } else {
622                        elected_probability = elected_probability.max(edge.probability);
623                    }
624                    // update `elected_idx`
625                    let best_edge = &model_graph_node.all_boundaries[elected_idx];
626                    if edge.probability > best_edge.probability {
627                        elected_idx = i;  // set as best, use its
628                    }
629                }
630                let elected = ModelGraphBoundary {
631                    probability: elected_probability,
632                    weight: weight_of(elected_probability),
633                    error_pattern: model_graph_node.all_boundaries[elected_idx].error_pattern.clone(),
634                    correction: model_graph_node.all_boundaries[elected_idx].correction.clone(),
635                    virtual_node: model_graph_node.all_boundaries[elected_idx].virtual_node.clone(),
636                };
637                // update elected edge
638                // println!("{} to virtual boundary elected probability: {}", position, elected.probability);
639                model_graph_node.boundary = Some(Box::new(elected));
640            } else {
641                model_graph_node.boundary = None;
642            }
643        });
644        // sanity check, two nodes on one edge have the same edge information, should be a cheap sanity check
645        debug_assert!({
646            let mut sanity_check_passed = true;
647            for t in (simulator.measurement_cycles..simulator.height).step_by(simulator.measurement_cycles) {
648                simulator_iter_real!(simulator, position, node, t => t, if node.gate_type.is_measurement() {
649                    let model_graph_node = self.get_node_unwrap(position);
650                    for (target, edge) in model_graph_node.edges.iter() {
651                        let target_model_graph_node = self.get_node_unwrap(target);
652                        let reverse_edge = target_model_graph_node.edges.get(position).expect("edge should be symmetric");
653                        if !float_cmp::approx_eq!(f64, edge.probability, reverse_edge.probability, ulps = 5) {
654                            println!("[warning] the edge between {} and {} has unequal probability {} and {}"
655                                , position, target, edge.probability, reverse_edge.probability);
656                            sanity_check_passed = false;
657                        }
658                    }
659                });
660            }
661            sanity_check_passed
662        });
663    }
664
665    /// create json object for debugging and viewing
666    pub fn to_json(&self, simulator: &Simulator) -> serde_json::Value {
667        json!({
668            "code_type": simulator.code_type,
669            "height": simulator.height,
670            "vertical": simulator.vertical,
671            "horizontal": simulator.horizontal,
672            "nodes": (0..simulator.height).map(|t| {
673                (0..simulator.vertical).map(|i| {
674                    (0..simulator.horizontal).map(|j| {
675                        let position = &pos!(t, i, j);
676                        if self.is_node_exist(position) {
677                            let node = self.get_node_unwrap(position);
678                            Some(json!({
679                                "position": position,
680                                "all_edges": node.all_edges,
681                                "edges": node.edges,
682                                "all_boundaries": node.all_boundaries,
683                                "boundary": node.boundary,
684                            }))
685                        } else {
686                            None
687                        }
688                    }).collect::<Vec<Option<serde_json::Value>>>()
689                }).collect::<Vec<Vec<Option<serde_json::Value>>>>()
690            }).collect::<Vec<Vec<Vec<Option<serde_json::Value>>>>>()
691        })
692    }
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698
699    #[test]
700    fn model_graph_basics() {
701        // cargo test model_graph_basics -- --nocapture
702        println!(
703            "std::mem::size_of::<ModelGraphNode>() = {}",
704            std::mem::size_of::<ModelGraphNode>()
705        );
706        println!(
707            "std::mem::size_of::<ModelGraphEdge>() = {}",
708            std::mem::size_of::<ModelGraphEdge>()
709        );
710        println!(
711            "std::mem::size_of::<ModelGraphBoundary>() = {}",
712            std::mem::size_of::<ModelGraphBoundary>()
713        );
714        println!(
715            "std::mem::size_of::<BriefModelGraphEdge>() = {}",
716            std::mem::size_of::<BriefModelGraphEdge>()
717        );
718        if std::mem::size_of::<ModelGraphNode>() > 80 {
719            // too expensive
720            panic!("ModelGraphNode which is unexpectedly large, check if anything wrong");
721        }
722    }
723}