-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathguppy_opt.rs
More file actions
181 lines (157 loc) · 5.83 KB
/
Copy pathguppy_opt.rs
File metadata and controls
181 lines (157 loc) · 5.83 KB
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
//! Tests optimizing Guppy-generated programs.
use rayon::iter::ParallelIterator;
use smol_str::SmolStr;
use std::collections::HashMap;
use std::fs;
use std::io::BufReader;
use std::path::Path;
use tket::extension::{TKET1_EXTENSION_ID, TKET_EXTENSION_ID};
use hugr::algorithms::ComposablePass;
use hugr::{Hugr, HugrView};
use rstest::{fixture, rstest};
use tket::passes::NormalizeGuppy;
use tket::serialize::pytket::{EncodeOptions, EncodedCircuit};
use tket::Circuit;
use tket1_passes::Tket1Circuit;
use tket_qsystem::QSystemPass;
const GUPPY_EXAMPLES_DIR: &str = "../test_files/guppy_optimization";
enum HugrFileType {
Original,
Flat,
Optimized,
}
fn load_guppy_circuit(name: &str, file_type: HugrFileType) -> std::io::Result<Hugr> {
let suffix = match file_type {
HugrFileType::Original => "",
HugrFileType::Flat => ".flat",
HugrFileType::Optimized => ".opt",
};
let file = Path::new(GUPPY_EXAMPLES_DIR).join(format!("{name}/{name}{suffix}.hugr"));
let reader = fs::File::open(file)?;
let reader = BufReader::new(reader);
Ok(Hugr::load(reader, None).unwrap())
}
#[fixture]
fn guppy_angles() -> Hugr {
load_guppy_circuit("angles", HugrFileType::Original).unwrap()
}
#[fixture]
fn guppy_false_branch() -> Hugr {
load_guppy_circuit("false_branch", HugrFileType::Original).unwrap()
}
#[fixture]
fn guppy_nested() -> Hugr {
load_guppy_circuit("nested", HugrFileType::Original).unwrap()
}
#[fixture]
fn guppy_ranges() -> Hugr {
load_guppy_circuit("ranges", HugrFileType::Original).unwrap()
}
#[fixture]
fn guppy_simple_cx() -> Hugr {
load_guppy_circuit("simple_cx", HugrFileType::Original).unwrap()
}
fn run_pytket(h: &mut Hugr) {
let circ = Circuit::new(h);
let mut encoded =
EncodedCircuit::new(&circ, EncodeOptions::new().with_subcircuits(true)).unwrap();
encoded
.par_iter_mut()
.for_each(|(_region, serial_circuit)| {
let mut circuit_ptr = Tket1Circuit::from_serial_circuit(serial_circuit).unwrap();
circuit_ptr
.clifford_simp(tket_json_rs::OpType::CX, true)
.unwrap();
*serial_circuit = circuit_ptr.to_serial_circuit().unwrap();
});
encoded.reassemble_inplace(circ.into_hugr(), None).unwrap();
}
fn count_gates(h: &impl HugrView) -> HashMap<SmolStr, usize> {
let mut counts = HashMap::new();
for n in h.nodes() {
if let Some(eop) = h.get_optype(n).as_extension_op() {
if [TKET_EXTENSION_ID, TKET1_EXTENSION_ID].contains(eop.extension_id()) {
*counts.entry(eop.qualified_id()).or_default() += 1;
}
}
}
counts
}
/// Run some simple optimization passes on the guppy-generated HUGRs and validate the result.
///
/// This test is intended to check the current status of the Guppy optimization passes.
///
#[rstest]
#[should_panic = "xfail"]
#[case::angles("angles", Some(vec![
("tket.quantum.Rz", 2), ("tket.quantum.MeasureFree", 1), ("tket.quantum.H", 2), ("tket.quantum.QAlloc", 1)
]))]
#[should_panic = "xfail"]
#[case::simple_cx("simple_cx", Some(vec![
("tket.quantum.QAlloc", 2), ("tket.quantum.MeasureFree", 2),
]))]
#[should_panic = "xfail"]
#[case::nested("nested", Some(vec![
("tket.quantum.CZ", 6), ("tket.quantum.QAlloc", 3), ("tket.quantum.MeasureFree", 3), ("tket.quantum.H", 6)
]))]
#[should_panic = "xfail"]
#[case::ranges("ranges", Some(vec![
("tket.quantum.H", 8), ("tket.quantum.MeasureFree", 4), ("tket.quantum.QAlloc", 4), ("tket.quantum.CX", 6)
]))]
#[should_panic = "xfail"]
#[case::false_branch("false_branch", Some(vec![
("TKET1.tk1op", 2), ("tket.quantum.QAlloc", 1), ("tket.quantum.MeasureFree", 1)
]))]
#[cfg_attr(miri, ignore)] // Opening files is not supported in (isolated) miri
fn optimise_guppy_pytket(#[case] name: &str, #[case] xfail: Option<Vec<(&str, usize)>>) {
let mut hugr = load_guppy_circuit(name, HugrFileType::Flat)
.unwrap_or_else(|_| load_guppy_circuit(name, HugrFileType::Original).unwrap());
run_pytket(&mut hugr);
let should_xfail = xfail.is_some();
let expected_counts = match xfail {
Some(counts) => counts.into_iter().map(|(k, v)| (k.into(), v)).collect(),
None => count_gates(&load_guppy_circuit(name, HugrFileType::Optimized).unwrap()),
};
assert_eq!(count_gates(&hugr), expected_counts);
if should_xfail {
panic!("xfail");
}
}
#[rstest]
#[case::angles("angles")]
#[should_panic]
#[case::nested("nested")]
#[should_panic]
#[case::ranges("ranges")]
#[cfg_attr(miri, ignore)] // Opening files is not supported in (isolated) miri
fn flatten_guppy(#[case] name: &str) {
let mut hugr = load_guppy_circuit(name, HugrFileType::Original).unwrap();
NormalizeGuppy::default().run(&mut hugr).unwrap();
let target = load_guppy_circuit(name, HugrFileType::Flat).unwrap();
assert_eq!(count_gates(&hugr), count_gates(&target));
}
/// Check that each example optimizes to the full extent given by the .opt (and .flat) .hugr files.
#[rstest]
#[case::angles("angles")]
#[case::false_branch("false_branch")]
#[case::simple_cx("simple_cx")]
#[case::nested("nested")]
#[case::ranges("ranges")]
#[should_panic] // This does not yet pass for any case!
fn optimise_guppy(#[case] name: &str) {
let mut hugr = load_guppy_circuit(name, HugrFileType::Original).unwrap();
let flat = count_gates(
load_guppy_circuit(name, HugrFileType::Flat)
.ok()
.as_ref()
.unwrap_or(&hugr),
);
let opt = count_gates(&load_guppy_circuit(name, HugrFileType::Optimized).unwrap());
NormalizeGuppy::default().run(&mut hugr).unwrap();
assert_eq!(count_gates(&hugr), flat);
run_pytket(&mut hugr);
assert_eq!(count_gates(&hugr), opt);
// Lower to QSystem. This may blow up the HUGR size.
QSystemPass::default().run(&mut hugr).unwrap();
hugr.validate().unwrap_or_else(|e| panic!("{e}"));
}