QuantumLearning/notebooks/algorithms/module_03_qft/lecture.ipynb

290 lines
17 KiB
Text

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# QFT and Periodic Structure Lecture\n"
],
"id": "9156a3d9"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The QFT module marks a major transition in the course because the circuit can no longer be understood as simple compute-then-measure logic. The point of the transform is to reorganize phase information into a different basis. That makes it more abstract, but it also makes it more reusable. Many later algorithms rely on QFT-style reasoning, so the lecture has to do two jobs at once: keep the mathematics concrete enough for a beginner who is still growing, and make the transform explicit enough that it becomes a design tool instead of a magic box.\n"
],
"id": "d4cf38f0"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Learning Objective\n",
"\n",
"\n",
" By the end of this lecture you should be able to explain a small QFT as a basis-change circuit built from a deliberate ladder of controlled phases and swaps, verify a hand-written implementation using statevector or inverse checks, and defend a small approximation as a tradeoff rather than as an arbitrary gate deletion.\n"
],
"id": "95d37897"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The safest way to begin the QFT is to reject the urge to treat it as a name that excuses vagueness. In professional work, a named transform still has to be rendered into explicit design choices. Which qubits are involved? Which controlled phases appear? Why are the angles what they are? What ordering convention do the swaps enforce? A world-class course cannot let the learner glide past those questions just because the transform is famous. The entire module is built to keep the famous thing inspectable.\n"
],
"id": "cc1916bc"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The phrase basis change is the most useful first handle. It tells you that the circuit is not trying to compute a classical answer and then measure it directly. It is trying to express the same state information in a new coordinate language where periodic or phase relationships become easier to read. That phrase also tells you what kind of evidence to seek. Basis-change circuits are poorly served by naive count histograms alone. You need statevector pictures, recovery checks, or other forms of structural verification.\n"
],
"id": "2eda8820"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The controlled-phase ladder is the conceptual center of the transform. Each step adds a graded phase relationship conditioned on another wire, so the transform accumulates information with different scales of influence. This is why small-angle terms matter even when they look visually minor. They are part of the representational contract. Later, when approximation becomes relevant, you may decide that some of those small contributions are expendable under a cost budget, but that decision only becomes meaningful once you understand what is being discarded.\n"
],
"id": "5bf37ecb"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Swaps deserve equal honesty. Many beginner explanations hide them in a footnote about bit reversal. In this course, swaps are part of the interface. They state which wire order the rest of the notebook should interpret as the transform output. That matters because every later comparison, inverse check, or algorithm embedding depends on stable conventions. A professional designer does not shrug at output ordering and promise to remember it later.\n"
],
"id": "343a3395"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The QFT is also the first place where explicit verification habits become non-negotiable. A rendered circuit that resembles the textbook does not prove that the implementation is correct. A small sign error, angle error, or ordering mistake can leave you with a circuit that looks authoritative while being wrong in the only way that matters. That is why this lecture keeps pairing circuit graphics with statevector evidence and inverse composition. A serious notebook must connect representation to verification, not leave them as separate worlds.\n"
],
"id": "73de8150"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, the QFT is a perfect place to introduce principled approximation. If you remove a small-angle term, you are not merely simplifying the diagram. You are making a resource tradeoff. The tradeoff can be good, but only if it is named and checked. This attitude will matter later in hardware-aware and noisy settings. Approximation should never mean 'I removed a gate because the picture was crowded.' It should mean 'I removed a specific contribution for a stated reason and I measured the cost.'\n"
],
"id": "b8dac3c2"
},
{
"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": "d4700ff6"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from math import pi\n",
"\n",
"from quantum_learning import (\n",
" counts_to_probabilities,\n",
" draw_circuit,\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": "4c0cfb48"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code-To-Diagram Anchor\n",
"\n",
"\n",
" The anchor circuit below is intentionally explicit. No helper library call hides the transform. Read the marker table, inspect the circuit, and then verify it with the cells that follow. This module is about making a canonical transform readable, not about making it short.\n"
],
"id": "c1a96044"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"step_reference_table([{'marker': '[1]', 'code_focus': 'Start with a small, fully explicit QFT instead of hiding it behind a library call.', 'diagram_effect': 'The circuit shows every controlled phase and swap directly.', 'why_it_matters': 'A professional designer needs to know which pieces are essential and which are optional approximations.'}, {'marker': '[2]', 'code_focus': 'Interpret each controlled phase as a graded correlation, not as a mysterious flourish.', 'diagram_effect': 'The middle of the circuit becomes a ladder of phase relationships.', 'why_it_matters': 'Controlled-phase structure is the real content of the QFT.'}, {'marker': '[3]', 'code_focus': 'Use swaps to state the intended output ordering explicitly.', 'diagram_effect': 'The end of the diagram makes the bit-reversal issue visible.', 'why_it_matters': 'Output ordering is part of the interface, not a postscript.'}, {'marker': '[4]', 'code_focus': 'Verify the transform with statevector or inverse-QFT checks instead of trusting the picture alone.', 'diagram_effect': 'The notebook connects circuit graphics to basis-change evidence.', 'why_it_matters': 'Basis-change circuits need stronger verification habits than simple compute-and-measure patterns.'}])\n"
],
"id": "53b84d61"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"editable_code = '\\nfrom math import pi\\nfrom qiskit import QuantumCircuit\\n\\ndef qft3() -> QuantumCircuit:\\n circuit = QuantumCircuit(3, name=\"qft3\")\\n # [1] Start with explicit local structure.\\n circuit.h(2)\\n circuit.cp(pi / 2, 1, 2)\\n circuit.cp(pi / 4, 0, 2)\\n # [2] Continue the controlled-phase ladder.\\n circuit.h(1)\\n circuit.cp(pi / 2, 0, 1)\\n circuit.h(0)\\n # [3] State the output ordering explicitly.\\n circuit.swap(0, 2)\\n return circuit\\n\\ncircuit = qft3()\\n'\n",
"editable_circuit_lab(\n",
" initial_code=editable_code,\n",
" context={\"QuantumCircuit\": QuantumCircuit, \"simulate_counts\": simulate_counts},\n",
" title='QFT and Periodic Structure Anchor',\n",
" instructions='Edit one causal region at a time. Use the reference table to keep code changes tied to circuit meaning.',\n",
" shots=256,\n",
")\n"
],
"id": "5a7d0154"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def qft3() -> QuantumCircuit:\n",
" circuit = QuantumCircuit(3, name=\"qft3\")\n",
" circuit.h(2)\n",
" circuit.cp(pi / 2, 1, 2)\n",
" circuit.cp(pi / 4, 0, 2)\n",
" circuit.h(1)\n",
" circuit.cp(pi / 2, 0, 1)\n",
" circuit.h(0)\n",
" circuit.swap(0, 2)\n",
" return circuit\n",
"\n",
"basis_one = QuantumCircuit(3)\n",
"basis_one.x(0)\n",
"transformed = basis_one.compose(qft3())\n",
"probs = statevector_probabilities(transformed)\n",
"ax = plot_probabilities(probs, title=\"QFT Of |001>\")\n",
"ax.figure\n"
],
"id": "52542776"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"quiz_block([{'prompt': 'What is the most useful first description of the QFT in this course?', 'options': ['A basis change that reorganizes phase information', 'A mysterious speedup box', 'A measurement replacement technique'], 'correct_index': 0, 'explanation': 'The QFT becomes legible when treated as an explicit basis transformation.'}, {'prompt': 'Why are the controlled-phase gates the conceptual heart of the QFT?', 'options': ['They progressively encode relative phase relationships across the wires', 'They are the only gates a simulator can draw', 'They replace swaps in all cases'], 'correct_index': 0, 'explanation': 'The ladder of controlled phases is where the transform actually lives.'}, {'prompt': 'Why should swaps be explained rather than dismissed as cleanup?', 'options': ['Because output ordering is part of the interface contract of the transform', 'Because swaps always improve fidelity', 'Because QFT cannot run without measuring every qubit'], 'correct_index': 0, 'explanation': 'Bit reversal is not housekeeping; it is a deliberate part of the output convention.'}], heading='Lecture Checkpoint A')\n"
],
"id": "38c3c6fc"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A good self-check in this module is to ask whether you can point to each gate and classify its role. If a gate is present only because 'QFT has one of those,' your understanding is still too inert. The lecture is trying to replace inert recognition with role-aware reading.\n"
],
"id": "79eace45"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another good self-check is whether you can defend a verification method. If you know the picture but do not know whether a statevector view, an inverse-composition check, or a sampled histogram is appropriate for the question at hand, then the transform is still more symbol than tool. This module wants the opposite outcome. It wants the transform to become something you can test and discuss.\n"
],
"id": "3056271d"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reading Discipline For This Module\n",
"\n",
"A serious lecture notebook has to teach more than recognition. It has to teach what to look at, what to ask, and what kind of evidence would count as a meaningful check. That is why this module keeps repeating a small number of disciplined questions. Which region prepares the state or question format? Which region encodes the task-specific structure? Which region translates that hidden structure into evidence you can actually read? And which parts of the notebook are presentation choices rather than mechanism? Those questions may sound repetitive, but repetition is useful here because algorithmic circuits become opaque very quickly when the learner loses the habit of dividing them into roles.\n",
"\n",
"Another reason for this slower lecture style is that professional design does not tolerate admiration as a substitute for analysis. It is perfectly possible to feel impressed by an algorithm, reproduce the overall diagram, and still be unable to explain what would break if one line changed. This course is trying to build the opposite habit. A mature notebook reader should be able to look at a circuit region and say what burden it carries, what evidence would test it, and what kind of mistake would falsify the current explanation. If that standard feels demanding, that is appropriate. The goal is to create designers, not spectators.\n"
],
"id": "7a5f3223"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Forward Link\n",
"\n",
"One reason these notebooks are written so densely is that later professional-design modules will assume this vocabulary is stable. When you later compare transpiled candidates, argue about noise sensitivity, or defend a capstone recommendation, you will not have time to rediscover what an oracle contract, reporting convention, controlled phase, or iteration choice means. The language has to be ready. That is why this lecture insists on precision now. The details are not there to slow you down forever. They are there so later speed is built on something trustworthy.\n"
],
"id": "9bf07c99"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"quiz_block([{'prompt': 'What does an approximate QFT change first?', 'options': ['It removes small-angle interactions to trade fidelity for structural simplicity', 'It replaces all Hadamards with X gates', 'It turns the transform into a classical FFT'], 'correct_index': 0, 'explanation': 'Approximation is a design tradeoff on controlled-phase detail.'}, {'prompt': 'What is the best verification habit for a small QFT notebook?', 'options': ['Use statevector evidence or inverse-QFT recovery checks, not just the circuit image', 'Trust the textbook diagram once it renders', 'Measure every qubit immediately after each gate'], 'correct_index': 0, 'explanation': 'Basis-change circuits need explicit evidence.'}, {'prompt': 'Why does the QFT belong in an algorithmic-design band?', 'options': ['Because it teaches a reusable basis-change motif that reappears inside larger algorithms', 'Because it is only useful as a historical example', 'Because it avoids all phase reasoning'], 'correct_index': 0, 'explanation': 'The module is about a transferable design pattern, not a museum piece.'}], heading='Lecture Checkpoint B')\n"
],
"id": "fa09c325"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"reflection_box('Explain why basis-change language is more useful than speedup language for learning the QFT.')\n"
],
"id": "bd15f0b7"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"reflection_box('Write one paragraph defending why the swap layer should be treated as part of the interface contract.')\n"
],
"id": "f3e1f00d"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mastery Gate\n",
"\n",
"Leave this lecture only when you can explain the mechanism line by line, not just recognize the diagram.\n"
],
"id": "f3b127e3"
}
],
"metadata": {
"kernelspec": {
"display_name": "QuantumLearning (.venv)",
"language": "python",
"name": "quantum-learning"
},
"language_info": {
"name": "python",
"version": "3.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}