Lecture 4 - Computation, Measurement, and Dynamic Circuits
1. Revision
Clifford Set of Quantum Gates
Table 1: Single-qubit gates
| Gates | Symbols | From | From | |---|---|---|---| | NOT | X | | | | Hadamard | H | | | | Phase shift | S | | | | Pauli-X | X | | | | Pauli-Y | Y | | | | Pauli-Z | Z | | |
Table 2: Two-qubit gates
| Gates | Symbols | Descriptions |
|---|---|---|
| CNOT | CNOT | $ |
| Swap | SWAP | $ |
| CZ | CZ | $ |
Operator Augmentation
- If we have a quantum operator
we can **augment** $\mathbf{Q}$ with trivial qubits by
-
This is useful for accommodating all entangled qubits, some of which are not involved with the operator
-
For any quantum operator , we can augment it with trivial qubits by
📝 Instructor's annotation: on the recap slide, again drew an arrow from the superscript to "N qubits in total" and from the subscript to "only apply on these qubits" — the same key from Chapter 3, re-added by hand here for the revision.
where the output mixed state is specified by the indices $p_1,\dots,p_M$, i.e.
while the remaining input qubits are unchanged, i.e. $x_{p_j}'=x_{p_j}$ for all indices $j\notin\{p_1,\dots,p_M\}$
2. Non-Clifford Set
Related
Non-Clifford Set of Quantum Logic Gates
- Limitation: We cannot construct all arbitrary quantum operators using only Clifford gates; for example,
- Gottesman-Knill Theorem: "Some quantum algorithms can be efficiently simulated by classical computers, even though they use superposition and entanglement."
- Non-Clifford Set: All quantum operators that cannot be constructed using only the Clifford gates
- Additional building blocks are needed: Toffoli gate, phase shift gate, rotation gates, and universal gate
- Simulation of these gates on classical computers is inefficient, which means it takes non-polynomial computation time
- When combined with superpositions and entanglement, these gates make some NP-hard problems solvable in polynomial time complexity
💡 Analogy: The Clifford set is "the safe, well-understood toolbox" — powerful enough to build entanglement and superposition, but also efficiently trackable by an ordinary computer (that's the Gottesman-Knill theorem), so it never gives quantum computers a genuine speed advantage. The Non-Clifford gates are what actually pushes past classical simulation — they're the reason quantum computers can, in principle, beat classical ones.
Toffoli Gate
📝 Instructor's annotation: next to the title, wrote "sometimes called CCNOT".
- Toffoli gate flips the third qubit only if the first and second qubits are
- The quantum operator CCX is
- Example:
- CCX is self-inversible
qml.Toffoli(wires=…)
image-2 Caption — Figure 1: Toffoli gate. Three wires : the first two (control) wires pass through unchanged; the third (target) wire comes out as .
Boolean Universality of Toffoli Gate
- Toffoli gate is said to be universal: we can construct any classical Boolean logic gate from it, similar to the NAND gate
- Theoretically, it enables quantum computers to emulate the classical ones with an FPGA-like Toffoli circuit
📝 Instructor's annotation: boxed the whole "Theoretically…" bullet in green and added, next to the AND-gate figure, "All classical programs can be run on quantum computers!" — the headline takeaway of Boolean universality.
image-3 Caption — Figures 2–4: Classical logic gates emulated with Toffoli gates.
- Figure 2 (NOT): control wires are and a constant (both pass through unchanged); the target wire is a second constant , which comes out as — since both controls are 1 exactly when , the target flips exactly when , giving .
- Figure 3 (AND): the standard CCX layout — controls pass through unchanged, and a target ancilla comes out as .
- Figure 4 (OR): built from De Morgan's law — and each pass through a NOT sub-circuit (as in Figure 2), the two results feed an AND sub-circuit (as in Figure 3), and the AND's output passes through one more NOT sub-circuit to yield .
💡 Analogy: This is exactly how classical CPUs are built from NAND gates alone — except here the one universal building block is the Toffoli gate, and "wiring constants into some of the inputs" is the quantum equivalent of hard-wiring a
1into a classical logic gate's input pin.
Generalized Controlled Gate
- Any single-qubit quantum operator can be expressed in the exponential form
📝 Instructor's annotation: the printed line originally read "where is the Hermitian matrix of " — the instructor crossed out "Hermitian matrix" and wrote "Hamiltonian matrix" above it. ( is still required to be Hermitian — the correction is about what to call it: it's 's Hamiltonian.)
where $\mathbf{H}_U$ is the Hamiltonian matrix of $\mathbf{U}$
- Generalized controlled gate of is denoted by , where
📝 Instructor's annotation: circled the bottom-right block \begin{bmatrix}u_{11}&u_{12}\u_{21}&u_{22}\end{bmatrix} and drew an arrow labeling it simply "" — i.e. that block is itself: when the control reads 1, the target block is exactly ; when the control reads 0, it's left as identity.
qml.ctrl(opr, control=…)- Example:
image-4 Caption — Figure 5: Controlled gate. Two cases shown on stacked circuits: with control , the control wire passes through as and the target wire passes through unchanged; with control , the control wire passes through as and the target wire comes out as .
Example 1
import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit', wires=[0,1,2,3,4,5])
@qml.qnode(dev)
def circuit():
# Prepare wires[0,1] = |00> + |11>
qml.H(wires=[0])
qml.CNOT(wires=[0,1])
# Prepare wires[2,3] = |00> + i|11>
qml.H(wires=[2])
qml.ctrl(qml.Y(wires=[3]), control=[2])
# Compute wires[0,1] AND wires[2,3]
qml.Toffoli(wires=[0,2,4])
qml.Toffoli(wires=[1,3,5])
# Expect |000000> + |001100> + i|110000> + i|111111>
return qml.state()
print(circuit())Exercise 4.1 — Toffoli Gate and Controlled Gates
Answer the following questions.
- Design a quantum algorithm emulating an XOR gate using only Toffoli gates.
- Design a quantum algorithm emulating a NAND gate using only Toffoli gates.
- Design a quantum algorithm emulating a NOR gate using only Toffoli gates.
- Why do we have to emulate classical logic gates using the Toffoli gate? What are the properties superior to classical Boolean algebra?
- Explain why simulation of a Toffoli gate is inefficient on classical computers.
- Design a quantum algorithm that imitates the gate , where is a unitary matrix, using only the Toffoli gate and the gate .
Design quantum algorithms that compute the following quantum-logical expressions. Develop PennyLane code to verify them.
Generalized Phase Shift Gate
- We can generalize the phase shift gate so that rotation can be done more freely
📝 Instructor's annotation: labeled this "State mapping:" in the margin.
qml.PhaseShift(angle, wires=…)- Some Clifford gates can be redefined in terms of the generalized phase shift gate
- Let's introduce the T gate
qml.T(wires=…)- Note that and
- is not always Hermitian, so we have to incorporate these adjoint gates into the instruction set
\mathbf{S}^{_} = \mathbf{P}(-\pi/2) \qquad \mathbf{T}^{_} = \mathbf{P}(-\pi/4)
qml.adjoint(opr)
Generalized Rotation Gates
- Let be a unitary matrix (i.e. Hermitian \mathbf{M}=\mathbf{M}^{_} and orthonormal \mathbf{M}^{-1}=\mathbf{M}^{_}), where
- Let's define a generalized rotation gate for a unitary matrix as follows
- General form:
- Mapping:
📝 Instructor's annotation: at the bottom of the slide, wrote "In most cases, ." — a reassurance that although is defined for any unitary matrix, in practice you'll almost always plug in a Pauli matrix, giving the RX, RY, RZ gates on the next three slides.
X-Rotation Gates
- X-Rotation gate flips the qubit
- Mapping:
qml.RX(angle, wires=…)
📝 Instructor's annotation: wrote at the bottom of the slide: "RX, RY, RZ are used in quantum ML." — flagging these rotation gates as the parametrized building blocks used in variational / quantum machine-learning circuits.
image-5 Caption — Figure 6: X-Rotation gate, shown as a rotation by angle around the real axis on the phase circle (Bit 0 at top, Bit 1 at bottom, pos/neg real and pos/neg img axes marked). Figures 7 and 8 (below) show the same style of diagram for Y- and Z-Rotation.
Y-Rotation Gates
- Y-Rotation gate flips the qubit, the sign, and the amplitude
- Mapping:
qml.RY(angle, wires=…)(Figure 7: Y-Rotation gate — rotation by around the imaginary axis)
Z-Rotation Gates
- Z-Rotation gate flips the sign
- Mapping:
💡 Note: the printed slide writes this mapping with rather than (i.e. "" and ""), which doesn't match the diagonal matrix directly above it — the matrix's entries are and (complex phases), so the mapping shown here uses for consistency with that matrix.
qml.RZ(angle, wires=…)(Figure 8: Z-Rotation gate — rotation by around the vertical bit-axis)
Universality of Phase Shift and Rotation Gates
- Any single-qubit operator can be simulated by:
- Equivalently, we can also replace with to flip qubits, signs, and amplitudes
- Universal quantum gate set: , , , , and CNOT
image-6 Caption — Figure 9: Generalized rotation gates, shown as a 5-panel Bloch-sphere decomposition: Start ( at top, at bottom) → Step 1: rotate only by relative phase → Step 2: rotate and together around the Z axis by global phase → Step 3: rotate and together around the X axis by global phase → Step 4: rotate and together around the Z axis by global phase .
💡 Analogy: This is the Chapter 2 "3-step universal rotation" () with one more knob added at the very front: an extra relative-phase twist (via ) before the rotation sequence even begins — together the four steps can reach any single-qubit unitary.
Exercise 4.2 — Generalized Phase Shift and Rotation Gates
Compute quantum operators , , , and of the following phases.
Design quantum algorithms that prepare the following states using generalized phase shift and rotation gates. Develop PennyLane code to verify each of them.
Uniform State Preparation (Shukla and Vedula, 2024)
⏭️ Marked "SKIPPED" by the instructor — this section's title slide has a large red "SKIPPED" stamped across it by hand, meaning it was not covered in lecture. It's transcribed below in full from the slides for completeness, but treat it as reference material rather than examined content unless your instructor says otherwise.
- We can prepare a quantum state that corresponds to our problem's input domain
- Property: We can create a superposition of two basis states and by rotating around Y with phase :
where $P_1 = P(\psi_1|q)$ is the probability of $q$ collapsing to 1
-
There is a recursive algorithm that constructs a superposition of equal probability where the number of states is NOT , where is the number of qubits
-
Algorithm: , where is the index of qubits, each bitstring is of length , and is a control qubit
- If , we apply and terminate here.
- If then we apply the controlled Hadamard gates to each qubit and terminate here.
- Compute the phase for rotation with where P_1 = #_k(\psi_k[i]=1)/K is the ratio of the -th bit being 1 w.r.t. the set
- We put rotation on the -th qubit.
- If , we terminate here.
- Otherwise, we will now split the set of bitstrings into two parts
- For , we frame with NOT gates and prepare the state recursively with
- For , we introduce an ancilla qubit and conditionally rotate it with
- We frame it with CX gates, and prepare the state recursively with
image-7 Caption — Figure 10: Uniform state preparation at step , " conditioned on " — a recursive circuit block: qubit gets an , then is framed by X gates around two nested sub-blocks labeled "Prep cond " and "Prep cond ," with an ancilla qubit getting its own and X-framing to feed the second sub-block.
Example 2 — Uniform State Preparation
- Example: Let's create a superposition for
- We measure the probability of collapsing to 1
- We therefore obtain the phase
- Rotate 1:
- We distinguish into
- Frame-in 1/0:
- For , we observe that four possibilities correspond to , resulting in applying the controlled H on
- Operation:
- Frame-out 1/0:
- Ancilla 1:
- Frame-in 1/1:
- For , the two possibilities have to be recursively converted resulting in the phase
- We distinguish into
- Frame-in 2/0:
- For , we observe that
- Operation:
- Frame-out 2/0:
- Ancilla 2:
- Frame-in 2/1:
- For , we observe that
- Operation:
- Frame-in 2/1:
- Frame-out 1/1:
image-8 Caption — Figure 11: Example of uniform state preparation for . Pink dashed boxes denote a recursive conversion, while green boxes represent a termination case; three qubits results in a recursion depth of three. The full circuit nests and inside the outer , with and nested one level deeper still.
Exercise 4.3 — Uniform State Preparation
Prepare a uniform quantum state from each of the following bitstring sets.
3. Measurement
State Measurement
- Observing the final quantum state of a quantum algorithm
- Type 1: Analytical solution
- Type 2: Projective measurement
- Type 3: State expectation
- Type 4: Variance
- Type 5: Simulation
image-9 Caption — Figure 12: Projective measurement. A "wave superposition" splits at each stage into a projection onto (sent to a Detector) and a rejection (carried forward to the next projection), illustrated as a cascade of triangular prisms.
Type 1: Analytical Solution
- To observe the final state theoretically by emulating a quantum algorithm
- PennyLane:
qml.state() - In reality, measured quantum states may deviate from the analytical solution due to quantum decoherence (i.e. noise)
- Any quantum algorithm has to be evaluated by
- Computing the analytical solution; this is the expected output
- Running on an actual quantum computer to measure noise sensitivity of the algorithm
(Figure 13: a photograph of a physical quantum computer.)
Example 3 (Analytical Solution)
import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit', wires=[0, 1])
@qml.qnode(dev)
def circuit(theta: float):
qml.RY(theta, wires=[0])
qml.CNOT(wires=[0,1])
qml.RZ(theta, wires=[1])
# Analytical solution
return qml.state()
print(circuit(np.pi / 3))Expected output:
[0.75-0.433j 0. 0. 0.433+0.25j]
Type 2: Projective Measurement
- To observe a quantum state with laser-beam projection
- We can measure a qubit by collapsing it, i.e. projecting it on a set of unitary vectors
where each $|u_k\rangle = c_k|0\rangle+d_k|1\rangle$ is called an **observable**
- In measurement, the qubit is destroyed; i.e. measurement is irreversible
(Figure 14: the same projective-measurement idea drawn on a Bloch-sphere-like ellipse, with projected onto an observable .)
Information Extraction
- When decomposed into observables , we can measure the probability for each of them as follows
(Figure 15: the measurement-gate symbol — a small box with a meter icon on a wire.)
- Information extraction: We collapse a qubit on pure states
This is a distribution of binary values
- PennyLane:
qml.probs()
(Figure 16: the measurement-gate symbol with a control-style output line.)
📝 Instructor's annotation: next to Figure 16, wrote "binary output is used as a control" — flagging that the classical bit this measurement produces can feed straight into a conditional gate (the subject of the Dynamic Circuit section below).
Example 3 (Projective Measurement)
import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit', wires=[0, 1])
@qml.qnode(dev)
def circuit(theta: float):
qml.RY(theta, wires=[0])
qml.CNOT(wires=[0,1])
qml.RZ(theta, wires=[1])
# Projective measurement
return qml.probs()
print(circuit(np.pi / 3))Expected output:
[0.75 0. 0. 0.25]
Information Extraction via Quantum Operator
- From Chapter 1, any quantum operator can be eigen-decomposed into
where $(\lambda_k,|u_k\rangle)_{k=1}^{N} = \operatorname{eigen}(\mathbf{U})$
- Pauli-Z Gate
Its eigen-pairs are $(1,|0\rangle)$ and $(-1,|1\rangle)$
-
and are called Z-bases (annotated: "computational base")
-
Pauli-X Gate
Its eigen-pairs are $(1,|+\rangle)$ and $(-1,|-\rangle)$
-
and are called X-bases (annotated: "superposition bases")
-
Pauli-Y Gate
Its eigen-pairs are $(1,|{+i}\rangle)$ and $(-1,|{-i}\rangle)$
- and are called Y-bases (annotated: "circular bases")
📝 Instructor's annotation: under each of the three "…-bases" labels, wrote the matching earlier name for that basis — "computational base" under Z-bases, "superposition bases" under X-bases, and "circular bases" under Y-bases — tying this terminology back to Chapter 2/3's naming.
Type 3: Multi-Shot Measurement with Expectation
- Since quantum computing is probabilistic, we sometimes repeat an experiment to obtain the distribution of outcomes
- The expectation of quantum operator on a state is
where $(\lambda_k,|u_k\rangle)$ is the $k$-th eigen-pair of $\mathbf{U}$
- In actual experiments, each state is a binary string sampled from
- The expectation is approximated by
where $N$ is an adequately large number
(Figure 17: the expectation-measurement gate symbol, labeled .)
Expectation on Pauli Projectors
- Suppose
- Pauli-Z Projector: Positive value implies more chance of pointing to the hemisphere
- Pauli-X Projector: Positive value implies more chance of pointing to the positive real hemisphere
- Pauli-Y Projector: Positive value implies more chance of pointing to the positive imaginary hemisphere
Table 3: Implication of expectation — projection on each axis
| Gates | Positive | Negative |
|---|---|---|
| Pauli-Z | $ | 0\rangle$ |
| Pauli-X | Pos. real | Neg. real |
| Pauli-Y | Pos. img | Neg. img |
Joint Expectation as Non-Destructive Projection
- Projection onto a single axis is irreversible, because it destroys, or decoheres, the quantum state throughout the complex vector space
- However, joint projection on multiple axes is reversible, because it makes a projection onto a subspace; therefore it does not decohere the quantum state
- For example, there are four possible axes for a two-qubit system: , and we choose to project a quantum state onto only two eigen-states and
- Joint projection on two states on projector and on is
- We can compute the joint probability, a.k.a. joint projection, for residing in each positive side
where each state $|\psi_k\rangle$ is measured on the quantum operator $\mathbf{U}_k$
Mixing and Matching of Expectations
- PennyLane:
qml.expval(op=qml.Z(wires=…))qml.expval(op=qml.X(wires=…))qml.expval(op=qml.Y(wires=…))
- PennyLane (a product of several operators on possibly different wires):
return qml.expval(
qml.Op1(wires=...)
@ qml.Op2(wires=...)
@ qml.Op3(wires=...)
...
@ qml.OpN(wires=...)
)where each `qml.Op`$_k$ is one of the projectors X, Y, and Z
- Linear combination of projectors:
return qml.expval(
0.5 * qml.X(wires=[0])
+ 0.1 * qml.Y(wires=[1])
+ 0.4 * qml.Z(wires=[2])
)Also: `qml.ops.LinearCombination(coeffs, projectors)`
- Returning several expectations is also possible in PennyLane:
return (
qml.expval(qml.Op1(wires=...)),
qml.expval(qml.Op2(wires=...)),
qml.expval(qml.Op3(wires=...)),
...
)Type 4: Variance
- In multi-shot measurement, it is useful to measure the dispersion in an outcome distribution
- The variance of quantum operator on a state is
- PennyLane:
qml.var(op=qml.Z(wires=…))qml.var(op=qml.X(wires=…))qml.var(op=qml.Y(wires=…))
- With the expectation and variance on the same quantum operator , we can altogether compare any two given qubits by addressing two questions:
- Which one goes to which extreme?
- Which one has a more consistent or volatile distribution?
- When measuring a qubit with several quantum operators, the one with the lowest variance is the most consistent
Example 3 (Expectation & Variance)
import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit', wires=[0, 1])
@qml.qnode(dev)
def circuit(theta: float):
qml.RY(theta, wires=[0])
qml.CNOT(wires=[0,1])
qml.RZ(theta, wires=[1])
# Expectation of each wire
return ( qml.expval(qml.Z(wires=[0])), qml.expval(qml.Z(wires=[1])),
qml.var(qml.Z(wires=[0])), qml.var(qml.Z(wires=[1])) )
print(circuit(np.pi / 3))Expected output: (0.5, 0.5, 0.75, 0.75)
(0.5, 0.5, 0.75, 0.75)
Type 5: Simulation
- Simulation is based on sampling mixed states from their probability distribution
- For a superposition , the probability distribution for each mixed state is
-
We can then sample a mixed state by
-
Suppose we have two superpositions and . The probability distribution of their tensor product is
- We can sample a tensor product by
(Figure 18: an illustrative photo of a die, captioned "Quantum dice roll.")
Simulation Methods
- By specifying the option
shotsin the instructionqml.device, we enable the simulation mode - Two simulation methods: step-by-step and end-to-end
- Step-by-step sampling: draw a set of bitstrings from the probability distribution repeatedly
shots= the number of shots for step-by-step sampling- PennyLane:
qml.sample() - Output: a list of qubit sequences
- End-to-end simulation: draw bitstrings from the probability distribution only once
shots= the number of shots for step-by-step sampling- PennyLane:
qml.counts() - Output: a frequency table for each possible bitstring
Example 3 (Sampling)
import pennylane as qml
from pennylane import numpy as np
# Step-by-step simulation by 10-shots sampling
dev = qml.device('default.qubit', wires=[0, 1], shots=10) # shots = number of samples
@qml.qnode(dev)
def circuit(theta: float):
qml.RY(theta, wires=[0])
qml.CNOT(wires=[0,1])
qml.RZ(theta, wires=[1])
# Sampling
return qml.sample()
print(circuit(np.pi / 3))Result ∼ 75% of and ∼ 25% of :
[ [0 0], [0 0], [0 0], [0 0], [1 1] ]
Example 3 (End-to-End Simulation)
import pennylane as qml
from pennylane import numpy as np
# End-to-end simulation with 1000 shots
dev = qml.device('default.qubit', wires=[0, 1]) # shots = number of samples
@qml.qnode(dev, shots=1000)
def circuit(theta: float):
qml.RY(theta, wires=[0])
qml.CNOT(wires=[0,1])
qml.RZ(theta, wires=[1])
# Simulation
return qml.counts()
print(circuit(np.pi / 3))Result ∼ 75% of and ∼ 25% of :
{'00': 738, '11': 262}
Density Matrix
📝 Instructor's annotation: wrote "(noisy state)" directly under the "Density Matrix" title.
- Density matrix: a unified form of pure states and mixed states
- A density matrix for is
- The diagonal entries are the probability of $|0\rangle$ and $|1\rangle$, respectively
- The off-diagonal entries are phase coherence
- Trace: sum of the diagonal line
- Property: Quantum state is pure if and only if
- Expectation of quantum operator on a state can be rewritten as
- Example:
Reconstructing a Pure State from a Density Matrix
- With the expectations of all Pauli projectors, we can reconstruct a qubit in terms of a density matrix
- Check if . If so, the qubit will be pure and we can proceed.
- We eigen-decompose into eigen-pairs
- If any , its eigenvector becomes a state vector of .
- Otherwise, it is a mixed state and the density matrix is already the best description for this qubit.
Exercise 4.4 — Measurement and Density Matrix
Convert the following qubits into equivalent density matrices.
Compute the projective measurements , , and from these density matrices, and check if they are pure states or mixed states.
- , where is a normalizing factor
4. Dynamic Circuit
Mid-Circuit Measurement
- We can introduce if-clauses and loops into a quantum algorithm, which means the quantum circuit dynamically changes w.r.t. the current state
- Mid-circuit measurement (MCM): A quantum state is measured in the middle of the algorithm, and optionally it can be reset
- Output: classical bit
- MCM can be done by taking a quick sneak peek of a qubit nondestructively, and estimating the actual quantum state — the result may be noisy
- MCM is used in combination with the if-clause to form a conditional statement or a loop
Table 4: Mid-circuit measurement
| Instruction | Description |
|---|---|
qml.measure(wires=…) | Measure the classical bit of the specified wire. |
qml.measure(wires=…, reset=True) | Measure the classical bit of the specified wire and reset that wire to $ |
qml.measure(wires=…, postselect=n) | Measure the classical bit of the specified wire. If it is NOT equal to the postselected value, terminate this circuit run. |
Conditional Operator
- We can perform quantum operators conditioned on the outcome of the measurement
- PennyLane:
qml.cond(bool_expr, opr)(params) - If the Boolean expression is true, then the operator is applied on the parameters
- We can form a complex Boolean expression using
&(and),|(or), andnot(negation)
| Instruction | Description |
|---|---|
qml.cond(bool, true_fn=…)(params) | If the condition is true, true_fn is called with the specified parameters. |
qml.cond(bool, true_fn=…, false_fn=…)(params) | If the condition is true, true_fn is called with the specified parameters. Otherwise, false_fn is called with the same parameters. |
qml.cond(bool, true_fn=…, false_fn=…, elifs=…)(params) | The option elifs is a list of (cond, opr), where each pair is a condition and its operation in the else-if part. |
Condition Operator
- We can emulate the if-clause in quantum computing by treating the condition as a classical control bit
image-10 Caption — Figure 19: Quantum algorithm with mid-circuit measurement and conditional operators. Qubit 1 gets then is measured to classical bit ; wire 2 gets if or if , and is then itself measured to ; wire 3 gets if or if .
Example 4 — Conditional Operator
dev = qml.device('default.qubit', wires=[0, 1, 2])
@qml.qnode(dev, shots=500)
def circuit(theta: float):
qml.Hadamard(wires=[0]) # wire-0 is |+>
m0 = qml.measure(wires=[0]) # m0 is either 0 or 1
qml.cond(m0 == 0, # If m0 == 0:
true_fn=qml.RY, # Y-rotate wire-1 by theta
false_fn=qml.RX # Else: X-rotate wire-1 by theta
)(theta, wires=[1]) # (Common parameters)
m1 = qml.measure(wires=[1]) # m1 is either 0 or 1
qml.cond(m1 == 1, # If m1 == 1
true_fn=qml.RX, # X-rotate wire-2 by theta
false_fn=qml.RZ # Else: Z-rotate wire-2 by theta
)(theta, wires=2) # (Common parameters)
return qml.counts()
# Result = {'000': 125, '001': 50, '010': 50, '100': 150, '101': 50, '110': 75}
# N.B. It sums to 500.
print(circuit(np.pi / 3))Postselection
- Postselection: If the measurement is not equal to the specified value, we will discard this circuit run
image-11 Caption — Figure 20: Quantum algorithm with postselection and condition on external parameter . Qubit 1 gets ; the CNOT-linked qubit 2 is measured with postselect= (runs where it comes out otherwise are discarded); wire 3 gets if or if — this condition is on the external parameter itself, not a measurement outcome.
Example 5 — Postselection
dev = qml.device('default.qubit', wires=[0, 1, 2])
@qml.qnode(dev, shots=500)
def circuit(theta: float):
qml.Hadamard(wires=[0])
qml.CNOT(wires=[0, 1]) # Bell state |Psi+>
qml.RX(theta, wires=[1]) # X-rotate wire-1 by theta
# Postselection: If wire-1 is not 1, terminate this circuit run
m = qml.measure(wires=[1], postselect=1)
qml.cond(theta > np.pi / 2, # If theta > pi / 2:
true_fn=qml.RX, # X-rotate wire-2 by theta
false_fn=qml.RY # Else: Y-rotate wire-2 by theta
)(theta, wires=[2]) # (Common parameters)
return qml.counts()
# Result: {'010': 40, '011': 10, '110': 150, '111': 50}.
# N.B. It does not sum to 500 due to the postselection.
print(circuit(np.pi / 3))Looping in PennyLane
- For-loop: Decorator
@qml.for_loop(start, stop, step) - While-loop: Decorator
@qml.while_loop(cond_fn) - The decorated function becomes the loop's body, where its parameters and returned values connect between each iteration
- Once you declare a function decorated with these decorators, you have to actually call it to run the loop — you are encouraged to modularize and parameterize your loops
image-12 Caption — Figures 21–22: For-loop and while-loop in quantum circuits. Both show qubit 1 repeatedly getting with each pass, and qubit 2 repeatedly getting with each pass. Figure 21's loop runs "for to "; Figure 22's loop runs "while and ."
Example 6 — For-Loop
dev = qml.device('default.qubit', wires=[0, 1])
@qml.qnode(dev, shots=500)
def circuit_for(iter_no: int, theta0: float, theta1: float):
@qml.for_loop(0, iter_no, 1) # for i in range(0, iter_no, 1):
def loop(i, theta0, theta1): # (This is the loop's body)
qml.RY(theta0, wires=[0]) # Y-rotate wire-0 by theta0
qml.RY(theta1, wires=[1]) # X-rotate wire-1 by theta1
theta0_new = theta0 / 2 # Update theta0
theta1_new = theta1 / 3 # Update theta1
return theta0_new, theta1_new # Pass theta0 and theta1 to the next iteration
loop(theta0, theta1) # Actually run the loop
qml.CNOT(wires=[0, 1])
return qml.counts()
circuit_for(10, np.pi / 4, np.pi / 4)Example 7 — While-Loop
dev = qml.device('default.qubit', wires=[0, 1])
@qml.qnode(dev, shots=500)
def circuit_while(iter_no: int, theta0: float, theta1: float):
@qml.while_loop( # while:
lambda t0, t1: # (Terminal condition)
t0 > 1e-3 and t1 > 1e-3 # theta0 > 1e-3 and theta1 > 1e-3
) #
def loop(theta0, theta1): # (This is the loop's body)
qml.RY(theta0, wires=[0]) # Y-rotate wire-0 by theta0
qml.RY(theta1, wires=[1]) # Y-rotate wire-1 by theta1
theta0_new = theta0 / 2 # Update theta0
theta1_new = theta1 / 3 # Update theta1
return theta0_new, theta1_new # Pass theta0 and theta1 to the next iteration
loop(theta0, theta1) # Actually run the loop
qml.CNOT(wires=[0, 1])
return qml.counts()
circuit_while(10, np.pi / 4, np.pi / 4)Exercise 4.5 — Dynamic Circuits
Develop PennyLane programs to compute the following states. Let each be the -th wire.
- Compute , for some .
- Let Compute , for some .
- Compute , where each , for some .
- Compute , where each , for some , and each phase . The number varies depending on this condition.
- Compute the GHZ state as illustrated below.
image-13 Caption — Figure 23: GHZ entangled state — qubit 1 gets , then a chain of CNOTs cascades from qubit 1 into qubit 2, qubit 2 into qubit 3, and so on down to qubit , producing .
- Compute the following quantum circuit. Each is a phase shift gate with phase . [Reminder: Phase shift gate is
qml.PhaseShift(angle, wires=…)in PennyLane] - Compute the following circuit for the quantum Fourier transform. Note that the computation for each can be seen as a modularized loop in Question 6.
- Compute the following circuit for the quantum inverse Fourier transform.
image-14 Caption — Figures 24–26: Half QFT, (full) Quantum Fourier Transform, and Quantum Inverse Fourier Transform circuits.
- Figure 24 (Half QFT): qubit 1 gets , then controlled phase-shift gates each controlled from qubits respectively.
- Figure 25 (QFT): the same pattern from Figure 24 is repeated on qubit 1, then on qubit 2 (one fewer), then qubit 3, and so on down to qubit (which gets only ) — each row is a smaller copy of the row above it, shifted one qubit to the right.
- Figure 26 (Inverse QFT): the exact mirror image of Figure 25, running right-to-left instead of left-to-right.
Conclusion
- Non-Clifford set of quantum logic gates
- Measurement of quantum states
- Dynamic quantum circuits
- Limitation: Quantum algorithm consisting of only Clifford gates can be efficiently simulated by classical computers, yielding no performance boost
- Divergence: Quantum algorithms that include Non-Clifford gates cannot be efficiently simulated by classical computers, but still perform well on quantum computers
Target Learning Outcomes
Master Non-Clifford Quantum Operations
- Differentiate between Clifford and non-Clifford gate sets and explain the significance of the Gottesman-Knill Theorem regarding classical simulation efficiency.
- Demonstrate boolean universality by constructing classical logic gates (AND, OR, NOT, XOR, NAND) using the Toffoli (CCX) gate.
- Apply generalized rotations using RX, RY, and RZ gates to manipulate qubit amplitudes, signs, and phases.
- Synthesize universal unitaries by combining RZ, RX, and P gates to simulate any single-qubit operator.
Implement and Evaluate Measurement Strategies
- Distinguish between five types of state measurement: analytical solutions, projective measurement, state expectation, variance, and simulation (sampling).
- Calculate probabilities and expectations for quantum states using Pauli projectors (X, Y, Z) and eigen-decomposition.
- Analyze outcome dispersion by computing the variance of quantum operators to determine the consistency of qubit distributions.
- Execute quantum simulations in PennyLane using both step-by-step sampling and end-to-end frequency counting.
Model Quantum States via Density Matrices
- Convert pure and mixed states into density matrix representations.
- Verify state purity by applying the trace property for pure states versus for mixed states.
- Reconstruct qubits from the expectations of Pauli projectors using the density matrix formula.
Design Dynamic and Algorithmic Quantum Circuits
- Implement mid-circuit measurements (MCM) to extract classical information during an algorithm's execution.
- Construct conditional logic using
qml.condto trigger quantum operators based on measurement outcomes or external parameters. - Apply postselection to refine algorithm results by discarding circuit runs that do not meet specific measurement criteria.
- Develop iterative algorithms using
for_loopandwhile_loopdecorators to automate complex structures like the GHZ state and Quantum Fourier Transform (QFT).