These problems practise Lecture 1 and
Lecture 2. Each one starts on paper and ends with a
few lines of code that confirm the answer, so try the paper part first and run the code second.
Problem 1 and Problem 2 drill the algebra of Lecture 1. Problem 3 asks
about a code too large to check by hand. Problem 4 and Problem 5 use the tableau and
measurement rules of Lecture 2, and Problem 6 reads detection events in the memory
circuit of Notebook 2.
Qubits are numbered from 0, as in Stim. A Pauli string such as XYZI means
, with qubit 0 on the left.
Pauli and stabilizer algebra
Problem 1 (Pauli products and the symplectic form).
Let be the string XYZI and the string ZZXX.
Compute and , phases included. Do and commute?
Write both as binary vectors and compute their symplectic product.
Does it agree with part 1?
Show that exactly half of the Pauli strings on four qubits (signs ignored)
commute with . Hint: the symplectic product with a fixed vector is a linear map
.
Check parts 1 to 3 with stim.PauliString.
Solution
1. Multiply site by site, using , , :
Three of the four sites hold an anticommuting pair. Swapping the order of the factors costs a
sign at each of them, so , and and anticommute.
2. A sets both bits. For , and . For ,
and . The symplectic product is
: they anticommute, as in part 1.
3. Fix and let for . This
map is linear, and it is not identically zero: if has a 1 in place , the vector
with a single 1 in gives (likewise for ). A nonzero linear map
has a kernel of dimension 7, so of the strings
commute with . The argument works for any non-identity Pauli on qubits and gives
.
4.to_numpy() returns the bits and the bits.
import itertoolsimport deltakit_stim as stimP, Q = stim.PauliString("XYZI"), stim.PauliString("ZZXX")print("PQ =", P * Q, " QP =", Q * P, " commute:", P.commutes(Q))for name, p in (("P", P), ("Q", Q)): xs, zs = p.to_numpy() print(f"{name}: x = {xs.astype(int).tolist()}" f" z = {zs.astype(int).tolist()}")count = sum(P.commutes(stim.PauliString("".join(s))) for s in itertools.product("IXYZ", repeat=4))print(count, "of", 4**4, "Pauli strings commute with P")
PQ = +iYXYX QP = -iYXYX commute: FalseP: x = [1, 1, 0, 0] z = [0, 1, 1, 0]Q: x = [0, 0, 1, 1] z = [1, 1, 0, 0]128 of 256 Pauli strings commute with P
Problem 2 (The four-qubit code).
The code has stabilizer generators and .
Check that and commute, and find .
Show that , , and
are logical operators with the commutation relations of two qubits:
anticommutes with exactly when .
Show that the distance is 2: every single-qubit error is detected, and some weight-2
error is a logical operator.
Use the Knill–Laflamme conditions of Lecture 1 to show that the code cannot correct every
single-qubit error. Which pair of errors breaks them?
Build the code with CSSCode.from_matrix and confirm . Does the object report a
distance? If not, find by brute force over all strings of ‘s.
Solution
1. and meet as against on all four sites, an even number, so they
commute. They are independent, so (equivalently
).
2. Each of the four operators meets and in an even number of anticommuting
sites (none or two), so all four commute with the stabilizers. None of them is in
, so they act nontrivially on the code space. The
anticommuting sites between the pairs are
qubit 0: anticommute
qubits 0, 1: commute
qubits 0, 2: commute
qubit 0: anticommute
and two -type (or two -type) strings always commute. That is the algebra of two qubits.
3. anticommutes with , with , and with both, so every
single-qubit error changes the syndrome. has weight 2, commutes with both
checks, and is not a stabilizer, so .
4. The conditions require for every pair of
correctable errors, with the projector onto the code space. Take and
. Then , which maps the code space to itself but
is not a multiple of the identity there, so .
In words: and have the same syndrome, . A decoder must
undo one of them, and when it picks the wrong one the net effect is , a
logical flip. A distance-2 code detects one error but corrects none; correcting errors
needs .
5.CSSCode does not compute distances for a general code (no x_distance; the
surface-code classes have one). The rowspace of is , so an
logical is any string that passes the check and is neither of those two.
import numpy as npfrom deltakit.explorer.codes import CSSCodeh = np.array([[1, 1, 1, 1]], dtype=np.uint8)c422 = CSSCode.from_matrix(h_x=h, h_z=h)print("k =", c422.calculate_number_of_logical_qubits(), "| has x_distance:", hasattr(c422, "x_distance"))words = (np.arange(16)[:, None] >> np.arange(4)) & 1passes = words[(words @ h.T % 2 == 0).all(axis=1)]logicals = [w for w in passes if 0 < w.sum() < 4]print(len(passes), "X strings pass ZZZZ,", len(logicals), "are logicals,", "weights", sorted({int(w.sum()) for w in logicals}))
k = 2 | has x_distance: False8 X strings pass ZZZZ, 6 are logicals, weights [2]
So , and by the symmetry of the code. The six
logicals are the three nontrivial classes , , , each
with two representatives that differ by (for example and ).
Problem 3 (A rectangular surface code).
RotatedPlanarCode(width=3, height=5) places 15 data qubits on a grid of 3 columns and
5 rows, at coordinates and .
Count the checks before running anything. Every square of four neighbouring qubits
carries a weight-4 check, and in a checkerboard, and an edge of qubits
carries weight-2 checks. If the checks are independent, what is ? Deltakit
puts the weight-2 checks on the long edges: predict the shapes of and .
Search all strings of ‘s and all strings of ‘s for logical
operators. What is the lightest weight of each type, and how many logicals have it?
Compare with code.x_distance and code.z_distance.
Which edges do the lightest logicals connect? Use this to predict the distances of
RotatedPlanarCode(width=5, height=3).
Suppose errors are much more frequent than errors (biased noise). Which of the
two orientations would you choose, and why?
Solution
1. The grid has squares, four of each type. The two short edges
() carry one weight-2 check each and the two long edges () carry two each,
six in all. That makes 14 checks on 15 qubits, so . With the weight-2 checks on
the long edges, has rows and has .
2. The search is the one of Lecture 1, run for both types. A string of ‘s is a
logical if it passes every check and is not in the rowspace of , and the other way
round for .
import numpy as npfrom deltakit.explorer.codes import RotatedPlanarCodedef gf2_rank(m): """Rank over F_2, by Gaussian elimination with XOR.""" m = np.array(m, dtype=np.uint8) % 2 rank = 0 for col in range(m.shape[1]): rows = rank + np.flatnonzero(m[rank:, col]) if rows.size == 0: continue m[[rank, rows[0]]] = m[[rows[0], rank]] for i in np.flatnonzero(m[:, col]): if i != rank: m[i] ^= m[rank] rank += 1 return rankcode = RotatedPlanarCode(width=3, height=5)hx, hz = code.parity_check_matricesprint("H_X", hx.shape, " H_Z", hz.shape, " k =", code.calculate_number_of_logical_qubits())print("x_distance", code.x_distance, " z_distance", code.z_distance)cols = sorted(code.data_qubits, key=lambda q: q.unique_identifier)xy = [tuple(int(v) for v in q.unique_identifier) for q in cols]words = (np.arange(2**15)[:, None] >> np.arange(15)) & 1lightest = {}for name, same, other in (("X", hx, hz), ("Z", hz, hx)): ok = words[~(words @ other.T % 2).any(axis=1)] r = gf2_rank(same) logs = [w for w in ok if gf2_rank(np.vstack([same, w])) > r] d = min(int(w.sum()) for w in logs) lightest[name] = [w for w in logs if w.sum() == d] print(f"{name}: {len(logs)} logicals, lightest weight {d},", f"{len(lightest[name])} of them")
H_X (8, 15) H_Z (6, 15) k = 1x_distance 3 z_distance 5X: 256 logicals, lightest weight 3, 16 of themZ: 64 logicals, lightest weight 5, 21 of them
The shapes match part 1, and the brute force agrees with Deltakit: , ,
so this is a code. The count of lightest logicals matters too: each one is a
cheapest way for errors to cause a logical failure, so it enters the prefactor of the
logical error rate at low noise.
3. Look at where the lightest logicals and the weight-2 checks sit:
def edge_checks(h, axis): return sorted({xy[j][axis] for r in h if r.sum() == 2 for j in np.flatnonzero(r)})print("weight-2 X checks on x =", edge_checks(hx, 0))print("weight-2 Z checks on y =", edge_checks(hz, 1))print("every lightest X logical has one qubit per column:", all(sorted(xy[j][0] for j in np.flatnonzero(w)) == [1, 3, 5] for w in lightest["X"]))print("every lightest Z logical has one qubit per row:", all(sorted(xy[j][1] for j in np.flatnonzero(w)) == [1, 3, 5, 7, 9] for w in lightest["Z"]))
weight-2 X checks on x = [1, 5]weight-2 Z checks on y = [1, 9]every lightest X logical has one qubit per column: Trueevery lightest Z logical has one qubit per row: True
Every lightest logical crosses from the edge to the edge: these are
the two edges whose boundary checks are type. Every lightest logical runs from
to , the two edges with -type boundary checks. The reason is where a
string can end. A string of ‘s anticommutes with any check it touches an odd number
of times, and in the bulk every qubit sits in two squares, so an end in the bulk is
always flagged. Along an -type edge, the squares that would stick out of the grid
are simply absent, and the string can end there unseen. So is the width and the
height. Swapping them, RotatedPlanarCode(width=5, height=3) has and .
4. errors are caught by the checks, and they cause a logical failure when they
build up a logical, whose weight is at least . If errors dominate, make
the larger distance: width 3 and height 5 (). The rarer errors still face
. Both orientations use the same 15 qubits; only the orientation changes which
error type gets the longer distance.
Clifford circuits and Stim
Problem 4 (A tableau by hand).
Let . Using , and the
table of Lecture 2, compute and for .
Which familiar gate is ?
Count the single-qubit Cliffords, up to global phase, by counting the possible images of
and then of . How many remain if the signs of the images are ignored?
The number of -qubit Cliffords up to global phase is
. Check part 2 against it, then enumerate and
with stim.Tableau.iter_all.
Solution
1. Conjugate through the three layers in turn (the circuit reads the same forwards and
backwards, so the order does not matter):
This is the table of a with control 1 and target 0: Hadamards on both sides swap
the roles of control and target.
2. A Clifford is fixed, up to phase, by the images of and . The image of can
be any of : 6 choices. The image of must anticommute with it,
which leaves the other two letters with either sign: 4 choices. That gives
. Without signs, : the permutations of the letters
.
3. For the formula gives . For it gives
. Each of the images carries a free sign, so ignoring
signs divides by : and . These are the orders of the symplectic groups
and , the binary picture of Lecture 1 again.
import deltakit_stim as stimU = stim.Tableau.from_circuit(stim.Circuit("H 0 1\nCX 0 1\nH 0 1"))for j in range(2): print(f"X{j} -> {U.x_output(j)} Z{j} -> {U.z_output(j)}")print("U == CX 1 0:", U == stim.Tableau.from_circuit(stim.Circuit("CX 1 0")))for n in (1, 2): signed = sum(1 for _ in stim.Tableau.iter_all(n)) unsigned = sum(1 for _ in stim.Tableau.iter_all(n, unsigned=True)) print(f"n = {n}: {signed} Cliffords, {unsigned} ignoring signs")
The three-qubit GHZ state has stabilizer generators
, and .
Show that , and each equal minus a stabilizer, so each has the value
with certainty.
Suppose each qubit carried predetermined answers to “measure
” and “measure ”, and the outcome of a product such as was the product of
the answers. Show that part 1 forces . What does the state say about
?
Give , and without
computing an amplitude.
Measure on qubit 0 and suppose the outcome is . Use the Gottesman–Knill update
rule to find the new stabilizer generators. What state are qubits 1 and 2 in? Repeat for
the outcome .
Check parts 1, 3 and 4 with stim.TableauSimulator.
Solution
1. Write on each site. Then
In the same way
and , where . Products of
stabilizers are stabilizers, so each of the three has the value on the state.
2. The three certain outcomes say . Their
product is . But is a stabilizer,
so the state gives , every time. No table of predetermined answers can reproduce four
predictions that quantum mechanics makes with certainty. This is Mermin’s form of the
Greenberger–Horne–Zeilinger argument: a contradiction without any inequality or statistics.
3. meets in three anticommuting sites, so it anticommutes with a stabilizer
and . is a stabilizer: .
anticommutes with (one site), so .
4. commutes with and and anticommutes with . The update replaces
by , the sign being the outcome, and keeps the rest. Multiplying by
gives the generators , , . Qubit 0 is in , and
qubits 1 and 2 are left in the Bell state stabilized by and , which is
for and for . Both
outcomes have probability , because anticommuted with a generator.
5.postselect_x forces the outcome, so the code shows both branches without depending
on a random draw.
import deltakit_stim as stimghz = stim.Circuit("H 0\nCX 0 1\nCX 0 2")sim = stim.TableauSimulator(seed=0)sim.do_circuit(ghz)for p in ["XXX", "XYY", "YXY", "YYX", "YYY", "ZIZ", "XXY"]: print(p, sim.peek_observable_expectation(stim.PauliString(p)))for minus in (False, True): s = stim.TableauSimulator(seed=0) s.do_circuit(ghz) s.postselect_x(0, desired_value=minus) print("X0 =", "-1:" if minus else "+1:", [str(g) for g in s.canonical_stabilizers()])
desired_value is the measurement bit, so False is the eigenvalue .
Problem 6 (Reading detection events).
Take the distance-3 repetition-code memory with two rounds from
Lecture 2. Data qubits sit at
and ancillas at ; the ancilla at measures and the
one at measures :
position x 0 1 2 3 4 d --- a --- d --- a --- dround 0 m0 m1round 1 m2 m3data M m6 m5 m4
The detectors and the observable are, with sums mod 2,
, , , ,
, and .
For each fault, predict which detectors fire and whether flips.
(a) An error on data qubit at the start of round 0, before any check.
(b) A wrong outcome of the ancilla at in round 1.
(c) A error on data qubit between the rounds.
(d) errors on data qubits and , both between the rounds.
(e) An error on data qubit between the rounds.
Faults (d) and (e) fire the same detectors. A decoder that picks the most likely
explanation chooses which, and what happens to the logical qubit? What does this say
about how many errors a distance-3 code corrects?
Check part 1 by inserting each fault into the noiseless Stim circuit and sampling one
shot.
Solution
1. An error on a data qubit flips every later outcome of the checks that
contain it, and that qubit’s final measurement.
(a) flips and . Then , while
, , and
each contain two flips and stay 0. Fires ; is
unchanged. Only the first comparison, with the reset state, sees the change.
(b) flips alone, so and fire, a time-like pair; is unchanged.
(c) A error commutes with every check and every measurement, so nothing
fires and is unchanged. It does nothing at all here: the data are in ,
an eigenstate of . The repetition code in this basis protects against only.
(d) flips and ; flips , and . Net: , ,
flip and does not. , , .
Fires only, and flips.
(e) flips and : , . Fires only; is
unchanged.
2. At error rate , the single fault (e) is more likely than the double fault (d) by
a factor of order . The decoder explains by (e) and predicts no flip of .
If (d) really happened, did flip and the shot ends in a logical error. The two
faults differ by on , which is the logical : the same failure as
in Problem 2, part 4, now in space and time. A distance-3 code corrects every single fault,
but two faults can imitate one, so it corrects .
3. The Stim circuit prepares the ancillas with RX, couples them with CZ, and measures
them with MX. So round 0 starts at the first CZ line, “between the rounds” is just
before the second RX line, and a wrong ancilla outcome is a Z_ERROR just before its
MX. Stim numbers qubits in its own order, so the code first maps each position to a
Stim index through the QUBIT_COORDS of the circuit.
import numpy as npimport deltakit_stim as stimfrom deltakit.circuit.gates import PauliBasisfrom deltakit.explorer.codes import RepetitionCode, css_code_memory_circuitrep = RepetitionCode(distance=3)smem = css_code_memory_circuit( rep, num_rounds=2, logical_basis=PauliBasis.Z).as_stim_circuit()lines = str(smem).splitlines()q = {int(c[0]): k for k, c in smem.get_final_qubit_coordinates().items()}def fires(error, before, nth): """Insert `error` before the nth line starting with `before`; run it.""" at = [i for i, s in enumerate(lines) if s.startswith(before)][nth] circ = stim.Circuit("\n".join(lines[:at] + [error] + lines[at:])) dets, obs = circ.compile_detector_sampler(seed=0).sample( 1, separate_observables=True) return [f"D{k}" for k in np.flatnonzero(dets[0])], bool(obs[0, 0])faults = { "(a) X on x=2, round 0": (f"X_ERROR(1) {q[2]}", "CZ", 0), "(b) ancilla x=3 misread, round 1": (f"Z_ERROR(1) {q[3]}", "MX", 1), "(c) Z on x=2, between rounds": (f"Z_ERROR(1) {q[2]}", "RX", 1), "(d) X on x=0 and x=2, between": (f"X_ERROR(1) {q[0]} {q[2]}", "RX", 1), "(e) X on x=4, between rounds": (f"X_ERROR(1) {q[4]}", "RX", 1),}for name, args in faults.items(): dets, flipped = fires(*args) print(f"{name:33s} fires {dets}, L0 flips: {flipped}")
(a) X on x=2, round 0 fires ['D0', 'D1'], L0 flips: False(b) ancilla x=3 misread, round 1 fires ['D3', 'D5'], L0 flips: False(c) Z on x=2, between rounds fires [], L0 flips: False(d) X on x=0 and x=2, between fires ['D3'], L0 flips: True(e) X on x=4, between rounds fires ['D3'], L0 flips: False