QuantumLearning/notebooks/foundations/module_03_gates_and_measurement/lecture.ipynb

356 lines
20 KiB
Text
Raw Normal View History

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Gates and Measurement Lecture\n",
"\n",
"This module turns two ideas into engineering habits. The first idea is that gates are not collectible icons; they are transformations whose meaning depends on what state has already been prepared and what measurement question will be asked later. The second idea is that measurement is not the neutral end of a circuit. It is a protocol: basis choice, classical wiring, repeated sampling, and interpretation. If those two ideas land properly, a large class of beginner confusion disappears.\n"
],
"id": "6b1d34eb"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- COURSE_NAV_TOP -->\n",
"## Mainline Navigation\n",
"\n",
"Step 11 of 59. Follow the mainline in order and do not skip ahead.\n",
"\n",
"Previous notebook: [Qubit and Statevector Intuition Studio](../module_02_qubit_and_statevector_intuition/studio.ipynb)\n",
"\n",
"Next notebook: [Gates and Measurement Lab](lab.ipynb)\n",
"\n",
"Rule: finish this notebook top-to-bottom before you open the next one.\n"
],
"id": "913ee845"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Learning Objective\n",
"\n",
"By the end of this lecture, you should be able to explain why the same prepared state can yield different-looking evidence under different basis choices, why classical wiring belongs in the explanatory story, and how to compare ideal probabilities with shot-based counts without exaggerating the role of sampling noise. You should also be able to speak about a small gate set in structural language rather than as a list of symbols to memorize.\n"
],
"id": "b4fc23ab"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Gates Are Transformations In Context\n",
"\n",
"A gate becomes intelligible only inside a state story. `X` is not just “bit flip,” `Z` is not just “phase flip,” and `H` is not just “puts a qubit into superposition.” Those slogans are useful doorway phrases, but they are not enough for design. The real question is always: what transformation does this gate apply to the object currently on the wire, and how does that affect the experiment the rest of the circuit is building?\n",
"\n",
"This contextual view matters because the same symbol can carry a different teaching burden in different places. A final Hadamard before measurement is not doing the same job as an initial Hadamard during preparation, even if the matrix is the same. The lecture therefore treats gates by role inside a circuit story rather than by symbol name alone.\n"
],
"id": "85c98469"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Measurement Is A Protocol, Not A Punctuation Mark\n",
"\n",
"Many beginners read the measurement symbol as if it were the period at the end of a sentence. That is too weak. A measurement stage contains real design choices. Which basis are you measuring in? Which classical bits record the results? How many shots are you taking? Are you comparing the sampled evidence to an ideal probability model or simply admiring the bars? These are protocol questions, and they change what you are justified in saying about the experiment.\n",
"\n",
"Once you start seeing measurement this way, many later notebooks become easier. Basis rotation is no longer weird. Readout mapping is no longer bookkeeping trivia. Counts are no longer mistaken for the state itself. The whole evidence chain becomes more legible.\n"
],
"id": "d237d4bb"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Small Gate Vocabulary That Already Matters\n",
"\n",
"At this stage you do not need a zoo of gates to become dangerous in a good way. `X` lets you change preparation in a visibly classical-looking way. `Z` lets you change phase without changing computational-basis probabilities. `H` serves as a bridge between bases and therefore between hidden structure and visible evidence. `CX` lets one wire's story become part of another wire's story. That is already enough to build serious beginner insights.\n",
"\n",
"A strong course resists the urge to flood the beginner with symbols too early. The point is not to shrink the field. The point is to make the field legible by keeping the vocabulary small enough that the important distinctions remain visible.\n"
],
"id": "69e41bdd"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Counts, Probabilities, And Shot Noise\n",
"\n",
"A probability model and a finite-shot histogram are related, but they are not the same object. The model says what outcomes are expected in the ideal story. The histogram says what repeated sampling returned in this run with this shot budget. Differences between the two can be conceptually meaningful, but they can also be ordinary sampling fluctuation. Professional reasoning does not panic about that distinction. It names it.\n",
"\n",
"This is why the course keeps showing both the ideal description and the shot-based evidence. You need both. The ideal story gives you a reference. The sampled evidence tells you what the chosen protocol produced empirically.\n"
],
"id": "1e7ac0e1"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"import sys\n",
"\n",
"project_root = Path.cwd().resolve()\n",
"while not (project_root / \"pyproject.toml\").exists():\n",
" if project_root.parent == project_root:\n",
" raise RuntimeError(\"Could not locate the project root from this notebook.\")\n",
" project_root = project_root.parent\n",
"\n",
"src_path = project_root / \"src\"\n",
"if str(src_path) not in sys.path:\n",
" sys.path.insert(0, str(src_path))\n"
],
"id": "30dd0fcd"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from quantum_learning import (\n",
" counts_to_probabilities,\n",
" editable_circuit_lab,\n",
" plot_counts,\n",
" plot_probabilities,\n",
" quiz_block,\n",
" reflection_box,\n",
" simulate_counts,\n",
" statevector_probabilities,\n",
" step_reference_table,\n",
")\n",
"from qiskit import QuantumCircuit\n",
"from qiskit.quantum_info import Statevector\n"
],
"id": "c703e4f7"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code-To-Diagram Anchor\n",
"\n",
"The anchor circuit below is deliberately chosen to mix preparation, basis change, and final readout. Read the marker table before you touch the code. The objective is to keep the three layers separate in your head: what was prepared, what question was asked, and how the evidence was reported.\n"
],
"id": "21cebc74"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"step_reference_table([{'marker': '[1]', 'code_focus': 'Prepare a Bell-style correlated state with `H` and `CX`.', 'diagram_effect': 'The first two operations create a structured two-wire object rather than two independent qubits.', 'why_it_matters': 'Measurement interpretation depends on what was prepared before the final question is asked.'}, {'marker': '[2]', 'code_focus': 'Rotate one qubit with `H` immediately before measurement.', 'diagram_effect': 'The final question changes on that wire without erasing the rest of the preparation story.', 'why_it_matters': 'Basis changes are part of the experiment design, not cosmetic extras.'}, {'marker': '[3]', 'code_focus': 'Measure into explicitly chosen classical bits.', 'diagram_effect': 'The circuit commits to a specific readout question and a specific reporting layout.', 'why_it_matters': 'Classical wiring is part of the evidence trail and can itself become a source of confusion.'}])\n"
],
"id": "316ae070"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"editable_code = '\\ncircuit = QuantumCircuit(2, 2)\\n# [1] Prepare the correlated state.\\ncircuit.h(0)\\ncircuit.cx(0, 1)\\n# [2] Change the basis of the first measurement question.\\ncircuit.h(0)\\n# [3] Measure both qubits into the matching classical bits.\\ncircuit.measure([0, 1], [0, 1])\\n'\n",
"editable_circuit_lab(\n",
" initial_code=editable_code,\n",
" context={\"QuantumCircuit\": QuantumCircuit, \"simulate_counts\": simulate_counts},\n",
" title='Measurement Anchor: Bell Preparation With Basis Rotation',\n",
" instructions='Change the final basis rotation or the classical wiring and explain whether you changed the preparation story, the measurement question, or only the reporting layer.',\n",
" shots=256,\n",
")\n"
],
"id": "91e3b6e5"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comparing The Same Preparation Under Different Questions\n",
"\n",
"The fastest way to internalize basis dependence is to compare near-identical circuits that differ only by a final basis rotation. The prepared object is closely related, but the question changes. That alone can change the counts dramatically. This is not a contradiction. It is the intended behavior of a protocol-sensitive experiment.\n"
],
"id": "0d247b0b"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"z_basis = QuantumCircuit(1, 1)\n",
"z_basis.h(0)\n",
"z_basis.measure(0, 0)\n",
"\n",
"x_basis_probe = QuantumCircuit(1, 1)\n",
"x_basis_probe.h(0)\n",
"x_basis_probe.h(0)\n",
"x_basis_probe.measure(0, 0)\n",
"\n",
"z_counts = simulate_counts(z_basis, shots=512)\n",
"x_counts = simulate_counts(x_basis_probe, shots=512)\n",
"\n",
"{\n",
" \"z_basis_counts\": z_counts,\n",
" \"x_basis_counts\": x_counts,\n",
"}\n"
],
"id": "77dcd541"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot_counts(z_counts, title=\"Same Preparation, Z-Basis Readout\")\n",
"plot_counts(x_counts, title=\"Same Preparation, X-Basis Readout\")\n"
],
"id": "b04b2d08"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"quiz_block([{'prompt': 'What is the cleanest interpretation of a measurement basis change?', 'options': ['It changes the question asked of the prepared state', 'It deletes the earlier gates', 'It is only a formatting step for counts'], 'correct_index': 0, 'explanation': 'Measurement basis is part of the experiment design and the story of the circuit.'}, {'prompt': 'Why should classical register wiring be treated seriously?', 'options': ['Because wrong wiring can make correct quantum behavior look incorrect in the reported bitstrings', 'Because it changes the quantum state directly', 'Because it forces extra transpilation'], 'correct_index': 0, 'explanation': 'Evidence can be misread if the mapping from qubits to reported bits is not tracked carefully.'}, {'prompt': 'What does a shot-based histogram approximate?', 'options': ['The empirical distribution of answers to the chosen measurement question', 'The exact statevector amplitudes', 'The coupling map of the device'], 'correct_index': 0, 'explanation': 'Counts are sampled evidence, not a direct amplitude dump.'}], heading='Measurement Checkpoint A')\n"
],
"id": "25ac00d4"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Classical Wiring Is Part Of The Explanation\n",
"\n",
"There is a common beginner habit of stopping the explanation at the quantum wires and treating classical bits as a passive output tray. That is not good enough. Classical mapping can preserve the intended story, scramble it, or at least make it much harder to read. A correct quantum preparation with careless reporting can still produce misleading evidence. Good notebook pedagogy therefore keeps the classical bits visible and discussed.\n"
],
"id": "337385b6"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Common Misreadings To Avoid\n",
"\n",
"The first misreading is to treat the final Hadamard as if it “changes the state at the last minute” without asking what measurement basis it is inducing. The second is to treat counts as exact probabilities rather than samples. The third is to ignore classical bit order and then invent a wrong explanation for the resulting labels. The fourth is to describe `CX` as copy without checking what state sits on the control wire. Each of those mistakes can survive for a while if no notebook forces explicit writing. This course forces the writing so the mistakes become easier to catch.\n"
],
"id": "fb65ba8c"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A Reviewer's Checklist For Measurement Claims\n",
"\n",
"Suppose a teammate shows you a histogram and says the circuit “worked.” A weak review asks only whether the bars look plausible. A strong review asks at least five questions. What exactly was prepared? In what basis was the final question asked? How were qubits mapped onto classical bits? What shot count produced this evidence? And what competing interpretation would become visible if one of those protocol choices changed? That checklist sounds heavy for a beginner module, but it is precisely the right weight. The whole point of this lecture is to introduce professional suspicion early, before the circuits become large enough to hide sloppy reasoning.\n",
"\n",
"Notice that none of those review questions require advanced hardware knowledge. They are conceptual hygiene. That is good news. It means you can practice real engineering discipline locally on small circuits right now. The habits do not need to wait for larger projects. They just need to be named and repeated until they become normal.\n"
],
"id": "8f9e24b2"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Why This Module Cares About Tiny Protocol Details\n",
"\n",
"Some learners initially resent the amount of attention paid to basis labels, classical mappings, and shot budgets. They want the quantum part and regard the rest as bureaucracy. That instinct has to be corrected. In real circuit work, many bad conclusions are not caused by exotic quantum subtleties. They are caused by ordinary protocol sloppiness. A basis change was inserted and forgotten. A histogram was treated as if it were exact probability. A swapped classical mapping made the evidence look inconsistent. Those are not glamorous errors, but they are expensive ones. A good lecture series trains against them early.\n"
],
"id": "52c6704f"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## From Measurement Literacy To Design Judgment\n",
"\n",
"The real long-term point of this module is not merely to make you careful around histograms. It is to prepare you for later design judgment. Once circuits become larger, you will constantly face questions such as: did the transpiler change only the routing structure or did it alter the effective question being asked at the end, is a mismatch between ideal and empirical behavior likely to come from noise or from a protocol mistake, and does a proposed optimization preserve the intended evidence path? Those are hard questions only if the current small questions are still blurry. If, however, you have already learned to separate preparation, basis, and reporting on tiny circuits, the larger versions become recognizable.\n",
"\n",
"That is why the lecture is unapologetically detailed about matters that can look pedestrian. Professional competence is often the accumulation of correctly handled small distinctions. Basis discipline, count interpretation, and reporting clarity are part of that accumulation. They are not glamorous, but they are absolutely central.\n"
],
"id": "cc0987d5"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Transfer Forward\n",
"\n",
"Once you can separate preparation, question, and reporting, later modules on noisy evidence, verification, and hardware-aware redesign become much easier. You will know which part of the story changed and which part remained stable. That is the real payoff of this lecture. It is building disciplined measurement language before the course moves into more crowded engineering territory.\n"
],
"id": "6340c55e"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"quiz_block([{'prompt': 'Why is `H` often described as a basis bridge?', 'options': ['Because it lets Z-basis measurement act like an X-basis probe', 'Because it adds extra classical bits', 'Because it removes phase from all circuits'], 'correct_index': 0, 'explanation': 'The Hadamard is often the simplest way to express a different measurement question.'}, {'prompt': 'What should you conclude if 64-shot and 4096-shot runs look similar but not identical?', 'options': ['Sampling variation exists, but both runs can still support the same underlying probability story', 'One of the runs is invalid', 'The circuit changed between runs even if the code stayed the same'], 'correct_index': 0, 'explanation': 'Shot noise is normal and should be discussed rather than dramatized.'}, {'prompt': 'What is the main beginner danger of treating gates as isolated icons?', 'options': ['You miss how their meaning depends on context, basis, and surrounding preparation', 'You will always get syntax errors', 'You stop using notebooks'], 'correct_index': 0, 'explanation': 'Gate meaning is contextual, not merely symbolic.'}], heading='Measurement Checkpoint B')\n"
],
"id": "e2054e6c"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"reflection_box('Explain why a final Hadamard before measurement is often better described as a basis choice than as a mysterious last-minute state change.')\n"
],
"id": "a1939ca5"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"reflection_box('Write a short paragraph on why classical bit mapping belongs in a professional explanation of a circuit result.')\n"
],
"id": "174cce26"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mastery Gate\n",
"\n",
"Leave this lecture only when you can inspect a circuit and say, in separate sentences, what the gates prepared, what the measurement protocol asked, and how the reported counts should be interpreted. If those three sentences still blur together, stay with the module.\n"
],
"id": "0c18e249"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- COURSE_NAV_BOTTOM -->\n",
"## What To Open Next\n",
"\n",
"Next notebook: [Gates and Measurement Lab](lab.ipynb)\n",
"\n",
"If this notebook still feels unstable, repeat it before you move on. The mainline only works if each handoff is earned.\n"
],
"id": "569afbf7"
}
],
"metadata": {
"kernelspec": {
"display_name": "QuantumLearning (.venv)",
"language": "python",
"name": "quantum-learning"
},
"language_info": {
"name": "python",
"version": "3.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}