mirror of
https://github.com/saymrwulf/QuantumLearning.git
synced 2026-06-05 00:00:01 +00:00
341 lines
20 KiB
Text
341 lines
20 KiB
Text
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Qiskit Patterns and Workflow Design Lecture\n"
|
|
],
|
|
"id": "aef1d98b"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The first professional-design module changes the unit of thinking. Up to this point, the course has trained you to understand circuits, engineer them cleanly, and reason about algorithms as reusable motifs. That is necessary, but it is still not the full shape of professional work. In a real project, a circuit almost never lives alone. It sits inside a broader workflow: a design brief defines what question is being asked, configuration or preprocessing shapes the inputs, the circuit is built and executed under explicit assumptions, and a downstream step interprets the outputs into a decision, score, or report. This module teaches that larger unit.\n"
|
|
],
|
|
"id": "75e13532"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Learning Objective\n",
|
|
"\n",
|
|
"\n",
|
|
" By the end of this lecture you should be able to explain why a Qiskit pattern is more than a reusable circuit, how the map-optimize-execute-post-process cycle changes notebook design, and how to structure a local-first workflow so that another engineer can tell what the stable routine is, what the variable experimental question is, and how the final recommendation is being derived from the raw evidence.\n"
|
|
],
|
|
"id": "35f4eacb"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The word pattern is easy to misuse. In weak notebook culture, a pattern can mean nothing more than a favorite code idiom or a circuit shape copied into multiple files. In this course the word is stricter. A pattern is a reusable arrangement of responsibilities. It says where configuration belongs, where the quantum body belongs, where the compile or execution context belongs, and where the reporting or decision rule belongs. That definition matters because it turns a runnable notebook into something you can vary, extend, and review without losing the causal story.\n"
|
|
],
|
|
"id": "cb31886f"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The best way to see the need for patterns is to notice how many notebook failures are really workflow failures. A beginner might put configuration, circuit construction, execution, plotting, and interpretation in one long cell. The cell runs, but the roles are mixed together. A later reader cannot tell which parts are stable, which parts are experimental knobs, and which assumptions the final interpretation is silently relying on. The purpose of this module is to prevent that kind of muddle before it hardens into habit.\n"
|
|
],
|
|
"id": "bc56455e"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The map-optimize-execute-post-process language helps because it gives the notebook a sequence of burdens. Map means: what question or data is being translated into a circuit-ready form? Optimize means: what compilation or structural decisions are shaping the circuit before execution? Execute means: under what local conditions is the circuit being sampled or simulated? Post-process means: what derived quantity or decision rule is being computed from the result? None of these stages is optional in serious work, even when some of them remain small in a teaching notebook.\n"
|
|
],
|
|
"id": "e00d1813"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"One subtle benefit of pattern thinking is that it improves the quality of explanation as much as the quality of code. When the workflow is well structured, the prose can name each layer cleanly. You can tell a reviewer where the question is configured, where the stable quantum routine lives, and where the score or judgment is produced. That kind of narratability is not fluff. It is the difference between a notebook that merely runs today and a notebook that another engineer could trust, critique, or adapt later.\n"
|
|
],
|
|
"id": "49001a93"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Pattern design is also where local-first discipline becomes especially valuable. If every stage of the workflow lives inside the same project and can be rerun locally, then debugging becomes much less theatrical. A bad score can be traced back through the record: was the circuit itself wrong, did the measurement contract drift, did the post-processing assume a readout order that the builder never stated, or did the question configuration silently change? These are concrete engineering questions, and they are easiest to learn when the whole loop stays close at hand.\n"
|
|
],
|
|
"id": "6fa0772d"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The point of the module is therefore not to make the notebook feel more corporate. It is to give circuits a professional habitat. Once you can build a small local pattern that survives variation and yields a reviewable record, the later modules on redesign, verification, and capstone decision-making become much more natural. They stop feeling like add-ons and start feeling like the next responsibilities inside the same overall workflow.\n"
|
|
],
|
|
"id": "c25117a8"
|
|
},
|
|
{
|
|
"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 quantum_learning import (\n",
|
|
" build_demo_noise_model,\n",
|
|
" counts_to_probabilities,\n",
|
|
" draw_circuit,\n",
|
|
" editable_circuit_lab,\n",
|
|
" evidence_checklist,\n",
|
|
" feedback_iteration_panel,\n",
|
|
" line_coupling_map,\n",
|
|
" load_assessment_blueprint,\n",
|
|
" plot_counts,\n",
|
|
" plot_probabilities,\n",
|
|
" quiz_block,\n",
|
|
" reflection_box,\n",
|
|
" rubric_scorecard,\n",
|
|
" simulate_counts,\n",
|
|
" statevector_probabilities,\n",
|
|
" step_reference_table,\n",
|
|
" transpile_summary,\n",
|
|
")\n",
|
|
"from qiskit import QuantumCircuit\n",
|
|
"from qiskit.providers.basic_provider import BasicSimulator\n"
|
|
],
|
|
"id": "2f0f437e"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Code-To-Diagram Anchor\n",
|
|
"\n",
|
|
"\n",
|
|
" The anchor pattern is intentionally small. Its purpose is to make the workflow layers visible, not to impress with circuit complexity. Read the reference table first. Then inspect how the same small routine can be embedded inside a larger record that states the question being asked and the decision derived from the raw counts.\n"
|
|
],
|
|
"id": "8c86e3a3"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"step_reference_table([{'marker': '[1]', 'code_focus': 'Treat the question being asked of the circuit as configuration, not as a hidden side effect.', 'diagram_effect': 'The rendered circuit becomes one phase of a workflow rather than the whole workflow.', 'why_it_matters': 'Professional notebooks separate design brief, circuit body, and evaluation record.'}, {'marker': '[2]', 'code_focus': 'Keep basis adaptation or other query-specific logic in a clearly named layer.', 'diagram_effect': 'The middle of the circuit shows which part is core routine and which part customizes the question.', 'why_it_matters': 'Patterns become reusable only when stable and variable regions are visibly distinct.'}, {'marker': '[3]', 'code_focus': 'Make the reporting contract explicit instead of relying on later guesswork.', 'diagram_effect': 'The diagram ends with an auditable readout layer.', 'why_it_matters': 'Workflow quality includes trustworthy evidence, not only a correct quantum body.'}, {'marker': '[4]', 'code_focus': 'Pair the circuit with post-processing that produces a reviewable record rather than an isolated histogram.', 'diagram_effect': 'The circuit is now visibly part of a larger map-optimize-execute-post-process cycle.', 'why_it_matters': 'Patterns matter when circuits live inside applications, experiments, and reports.'}])\n"
|
|
],
|
|
"id": "911b822c"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"editable_code = '\\nfrom qiskit import QuantumCircuit\\n\\ndef build_agreement_probe(basis: str = \"z\") -> QuantumCircuit:\\n circuit = QuantumCircuit(2, 2)\\n # [1] The workflow chooses the question before the circuit is built.\\n circuit.h(0)\\n circuit.cx(0, 1)\\n # [2] Basis adaptation belongs in its own visible layer.\\n if basis == \"x\":\\n circuit.h([0, 1])\\n elif basis != \"z\":\\n raise ValueError(\"basis must be \\'z\\' or \\'x\\'\")\\n # [3] Keep the reporting contract explicit.\\n circuit.measure([0, 1], [0, 1])\\n return circuit\\n\\ncircuit = build_agreement_probe(basis=\"x\")\\n'\n",
|
|
"editable_circuit_lab(\n",
|
|
" initial_code=editable_code,\n",
|
|
" context={\"QuantumCircuit\": QuantumCircuit, \"simulate_counts\": simulate_counts},\n",
|
|
" title='Qiskit Patterns and Workflow Design Anchor',\n",
|
|
" instructions='Edit one structural burden at a time and use the reference table to keep the code and the engineering story aligned.',\n",
|
|
" shots=256,\n",
|
|
")\n"
|
|
],
|
|
"id": "2816d9bd"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def build_agreement_probe(basis: str = \"z\") -> QuantumCircuit:\n",
|
|
" circuit = QuantumCircuit(2, 2)\n",
|
|
" circuit.h(0)\n",
|
|
" circuit.cx(0, 1)\n",
|
|
" if basis == \"x\":\n",
|
|
" circuit.h([0, 1])\n",
|
|
" elif basis != \"z\":\n",
|
|
" raise ValueError(\"basis must be 'z' or 'x'\")\n",
|
|
" circuit.measure([0, 1], [0, 1])\n",
|
|
" return circuit\n",
|
|
"\n",
|
|
"def run_pattern(basis: str, shots: int = 256) -> dict[str, object]:\n",
|
|
" circuit = build_agreement_probe(basis)\n",
|
|
" compiled = transpile_summary(\n",
|
|
" circuit,\n",
|
|
" BasicSimulator(),\n",
|
|
" basis_gates=[\"rz\", \"sx\", \"x\", \"cx\"],\n",
|
|
" )\n",
|
|
" counts = simulate_counts(circuit, shots=shots)\n",
|
|
" probabilities = counts_to_probabilities(counts)\n",
|
|
" agreement = round(probabilities.get(\"00\", 0.0) + probabilities.get(\"11\", 0.0), 3)\n",
|
|
" return {\n",
|
|
" \"basis\": basis,\n",
|
|
" \"depth_after\": compiled[\"depth_after\"],\n",
|
|
" \"agreement_rate\": agreement,\n",
|
|
" \"counts\": counts,\n",
|
|
" }\n",
|
|
"\n",
|
|
"[run_pattern(basis) for basis in [\"z\", \"x\"]]\n"
|
|
],
|
|
"id": "9eab603f"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"quiz_block([{'prompt': 'What is the main reason to separate workflow configuration from the circuit builder?', 'options': ['So the stable quantum routine and the changing experimental question can be reviewed independently', 'So the circuit always uses fewer gates', 'So Qiskit can avoid classical data structures'], 'correct_index': 0, 'explanation': 'Pattern design depends on making stable and variable responsibilities visible.'}, {'prompt': 'Why is an explicit reporting contract part of a pattern notebook?', 'options': ['Because the evidence layer is part of the design, not a last-minute add-on', 'Because all patterns must measure every qubit twice', 'Because plotting replaces analysis'], 'correct_index': 0, 'explanation': 'Professional workflow design includes trustworthy readout and post-processing.'}, {'prompt': 'What makes a notebook pattern reusable?', 'options': ['It keeps intent, circuit body, and evaluation record distinct enough to vary inputs without losing the story', 'It hides the circuit inside a large helper', 'It avoids any post-processing code'], 'correct_index': 0, 'explanation': 'Reusable patterns survive variation because their boundaries are clear.'}], heading='Lecture Checkpoint A')\n"
|
|
],
|
|
"id": "118b2b8d"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"A strong self-check for this module is whether you can point to each stage of the workflow and say what would count as a mistake there. If the question configuration is wrong, the circuit may still run while answering the wrong question. If the circuit body is wrong, the result record may be beautifully structured and still meaningless. If the measurement contract drifts, the post-processing may produce a polished lie. Pattern thinking helps because it lets you localize those risks instead of treating the whole notebook as one opaque blob.\n"
|
|
],
|
|
"id": "8b92e0a7"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Another self-check is whether your prose tracks the code boundaries honestly. If the notebook says the builder is reusable, can you name which parameters are genuinely meant to vary? If it says the output score is meaningful, can you say exactly how that score is derived from the counts? Professional workflow design is not only about code refactoring. It is about making the notebook legible as an engineering argument.\n"
|
|
],
|
|
"id": "dc5c2f8c"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Reading Discipline For This Module\n",
|
|
"\n",
|
|
"The professional band demands slower reading than the earlier bands because the unit of judgment is larger. You are no longer inspecting only a circuit body. You are inspecting a design brief, a constraint model, a verification story, or a recommendation workflow. That means every notebook should be read with questions like these in mind: what burden is this stage carrying, what evidence would justify it, and what kind of failure would falsify the current explanation? If those questions stay active while you read, the notebook becomes training. If they disappear, the notebook becomes performance.\n",
|
|
"\n",
|
|
"Another discipline worth installing here is conditional confidence. Professional engineering rarely says only \"this works.\" It says \"under these assumptions, with this evidence, this is the choice I recommend.\" That conditional phrasing is not weakness. It is rigor. The purpose of the final band is to make that rigor normal in both your code and your prose.\n"
|
|
],
|
|
"id": "9c782648"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Professional Review Habit\n",
|
|
"\n",
|
|
"Another habit worth building here is review-minded reading. Do not read these notebooks only as the author of the current code cell. Read them as the future reviewer who must decide whether the workflow, redesign, diagnosis, or recommendation is trustworthy. That reviewer wants to know what assumptions were fixed, what evidence was gathered, what remained uncertain, and what could still break if the surrounding constraints changed. Practicing that perspective now is what turns the final band into professional training instead of advanced entertainment.\n"
|
|
],
|
|
"id": "5a843c15"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Forward Link\n",
|
|
"\n",
|
|
"Every later notebook artifact in a real project will inherit the standards practiced here. Workflow patterns affect how experiments are reproduced. Hardware-aware redesign affects whether ideal elegance survives implementation. Verification determines whether bad results are diagnosed honestly. And capstone review determines whether a chosen circuit can actually be defended. The point of this band is not to add optional polish. It is to make the entire project behave like professional engineering work.\n"
|
|
],
|
|
"id": "3b90cc67"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"quiz_block([{'prompt': 'What should a workflow record contain beyond raw counts?', 'options': ['The design brief, circuit or compile context, and a derived decision or score', 'Only the screenshot of the circuit', 'Only the token URL of the notebook server'], 'correct_index': 0, 'explanation': 'Pattern notebooks need enough context to be reviewed later.'}, {'prompt': \"Why is 'the code runs' a weak endpoint for this module?\", 'options': ['Because workflow design is about repeatable evidence and interfaces, not only execution success', 'Because workflows should never execute locally', 'Because classical preprocessing is irrelevant'], 'correct_index': 0, 'explanation': 'A runnable cell is not yet a professional workflow artifact.'}], heading='Lecture Checkpoint B')\n"
|
|
],
|
|
"id": "439a2472"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"reflection_box('Write a paragraph explaining why a circuit builder and a workflow pattern are not the same thing.')\n"
|
|
],
|
|
"id": "e560cd72"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"reflection_box('Describe one hidden assumption between execution and post-processing that you would want a professional notebook to state explicitly.')\n"
|
|
],
|
|
"id": "442dbf97"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"feedback_iteration_panel(title='Qiskit Patterns and Workflow Design Lecture Revision Loop', prompt='State the judgement this lecture is training, the strongest evidence that would justify it, the current weakness in your own explanation, and the next revision you should make.')\n"
|
|
],
|
|
"id": "c5ea7b49"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"assessment_blueprint = load_assessment_blueprint()\n",
|
|
"rubric_scorecard(\n",
|
|
" assessment_blueprint.get_rubric('module_self_review'),\n",
|
|
" title='Qiskit Patterns and Workflow Design Lecture Self-Grading',\n",
|
|
")\n"
|
|
],
|
|
"id": "36f948cc"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Mastery Gate\n",
|
|
"\n",
|
|
"Leave this lecture only when you can explain what evidence would justify the final professional judgment and what evidence would force you to revise it.\n"
|
|
],
|
|
"id": "056441be"
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "QuantumLearning (.venv)",
|
|
"language": "python",
|
|
"name": "quantum-learning"
|
|
},
|
|
"language_info": {
|
|
"name": "python",
|
|
"version": "3.12"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|