Skip to content

Commit

Permalink
Fix panic in dump reordering after swap (#67)
Browse files Browse the repository at this point in the history
This fixes an issue where state dump could crash if run after a swap of qubit ids. Specifically, a qubit id swap followed by a release of one of the qubits can put the id map into a state where not every desired id for the swap is occupied by an existing qubit. As a result, updating the map for the swapped key should be a best effort and not a panic if the key is not present.  Also adds a unit test to cover this specific case.
  • Loading branch information
swernli authored May 12, 2023
1 parent 617fa33 commit 7141d6e
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions backend/src/simulator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,11 @@ impl QuantumSim {
sorted_keys.iter().enumerate().for_each(|(index, &key)| {
if index != self.id_map[&key] {
self.swap_qubit_state(self.id_map[&key], index);
let swapped_key = *self
.id_map
.iter()
.find(|(_, &value)| value == index)
.unwrap()
.0;
*(self.id_map.get_mut(&swapped_key).unwrap()) = self.id_map[&key];
if let Some((&swapped_key, _)) =
self.id_map.iter().find(|(_, &value)| value == index)
{
*(self.id_map.get_mut(&swapped_key).unwrap()) = self.id_map[&key];
}
*(self.id_map.get_mut(&key).unwrap()) = index;
}
});
Expand Down Expand Up @@ -177,13 +175,11 @@ impl QuantumSim {
sorted_keys.iter().enumerate().for_each(|(index, &key)| {
if index != self.id_map[&key] {
self.swap_qubit_state(self.id_map[&key], index);
let swapped_key = *self
.id_map
.iter()
.find(|(_, &value)| value == index)
.unwrap()
.0;
*(self.id_map.get_mut(&swapped_key).unwrap()) = self.id_map[&key];
if let Some((&swapped_key, _)) =
self.id_map.iter().find(|(_, &value)| value == index)
{
*(self.id_map.get_mut(&swapped_key).unwrap()) = self.id_map[&key];
}
*(self.id_map.get_mut(&key).unwrap()) = index;
}
});
Expand Down Expand Up @@ -1270,6 +1266,17 @@ mod tests {
assert_eq!(val1, val2);
}

/// Verify that dump after swap on released qubits doesn't crash.
#[test]
fn test_swap_dump() {
let mut sim = QuantumSim::new();
let q = sim.allocate();
let inner_q = sim.allocate();
sim.swap_qubit_ids(q, inner_q);
sim.release(inner_q);
sim.dump();
}

/// Utility for testing operation equivalence.
fn assert_operation_equal_referenced<F1, F2>(mut op: F1, mut reference: F2, count: usize)
where
Expand Down

0 comments on commit 7141d6e

Please sign in to comment.