{"cells":[{"cell_type":"markdown","id":"d17da0bc","metadata":{"id":"d17da0bc"},"source":["# CS 1190: Fundamentals of Quantum Information Science\n","## IBM Quantum Cloud Lab — From Quantum Circuits to Real Hardware\n","\n","**Instructor:** Mohammad Saidur Rahman, Ph.D. \n","**Department of Computer Science, University of Texas at El Paso** \n","**Course website:** [qis.rahmanmsaidur.com](https://qis.rahmanmsaidur.com/)\n","\n","### Student laboratory notebook\n","\n","In this notebook you will **prepare, predict, simulate, and measure 21 quantum circuits**, then compare results from an ideal simulator with a physical IBM quantum processor. You will also study quantum key distribution (BB84) and interpret imperfect hardware measurements.\n","\n","> **Use your own IBM Quantum account.** Never enter your instructor's API key or CRN, put credentials into code, or include credentials in a submitted notebook. The credential prompts below hide what you type."]},{"cell_type":"markdown","id":"6b510c8e","metadata":{"id":"6b510c8e"},"source":["### Follow these sections in order\n","\n","| Section | Activity | Uses a real IBM QPU? |\n","|:--|:--|:--:|\n","| 0 | Install Qiskit and learn the notebook controls | No |\n","| 1 | Starting state, X gate, superposition | No |\n","| 2 | Interference, relative phase, measurement bases | No |\n","| 3 | CNOT and two-qubit behavior | No |\n","| 4 | Bell states and GHZ states | No |\n","| 5 | Why a CNOT is not a general quantum copier | No |\n","| 6 | BB84 preparation, measurement bases, and key sifting | No |\n","| 7 | Predict and simulate all circuits | No |\n","| 8 | Connect to IBM Quantum; submit selected circuits | **Only the submission cell** |\n","| 9 | Compare hardware results with predictions; save results | No new job |\n","| 10 | Answer the lab questions and submit your work | No new job |\n","\n","**How to work:** *Predict → Run → Observe → Explain.* A **shot** is one preparation and measurement of a circuit. Repeating a circuit many shots gives a histogram of classical bitstrings. The QPU may differ from ideal predictions due to both sampling variation and hardware errors.\n","\n","**Reading bitstrings:** In Qiskit, a two-qubit output is written **`q1 q0`** (not `q0 q1`). For example, `10` means `q1=1` and `q0=0`. Our circuits use the measurement register named `meas`."]},{"cell_type":"markdown","id":"50b3470d","metadata":{"id":"50b3470d"},"source":["## Section 0 — Set up the notebook\n","\n","Open this file in [Google Colab](https://colab.research.google.com/) using **File → Upload notebook**. Run cell 0A, then 0B. If Colab requests a runtime restart after installation, restart the runtime and rerun 0B. No IBM credentials are required until Section 8."]},{"cell_type":"code","execution_count":1,"id":"c5f9c581","metadata":{"id":"c5f9c581","executionInfo":{"status":"ok","timestamp":1793655479034,"user_tz":420,"elapsed":10,"user":{"displayName":"Mohammad Saidur Rahman","userId":"05662769360433032878"}}},"outputs":[],"source":["# 0A — Install the packages used by this notebook.\n","# Installation is local to your Colab or Jupyter environment; no QPU job is submitted.\n","# !%pip install \"python-dateutil==2.9.0.post0\"\n","# !pip -q install \"qiskit>=2.5,<3\" \"qiskit-ibm-runtime>=0.50,<1\" \"matplotlib>=3.7\" \"pylatexenc>=2.10\""]},{"cell_type":"code","execution_count":2,"id":"8c3074dc","metadata":{"id":"8c3074dc","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1793655483549,"user_tz":420,"elapsed":1179,"user":{"displayName":"Mohammad Saidur Rahman","userId":"05662769360433032878"}},"outputId":"a0c006fb-dc21-4406-f6f6-77452f932e40"},"outputs":[{"output_type":"stream","name":"stdout","text":["Setup complete. Continue to Section 1.\n"]}],"source":["# 0B — Imports and shared classroom functions.\n","from collections import OrderedDict\n","from pathlib import Path\n","import csv\n","import json\n","import matplotlib.pyplot as plt\n","from IPython.display import display\n","from qiskit import QuantumCircuit\n","from qiskit.quantum_info import Statevector\n","from qiskit.primitives import StatevectorSampler\n","\n","LOCAL_SHOTS = 256\n","HARDWARE_SHOTS = 256\n","SEED = 2026\n","\n","EXPERIMENTS = OrderedDict()\n","SIMULATOR_COUNTS = {}\n","QPU_COUNTS = {}\n","qpu_job = None\n","\n","\n","def register(exp_id, title, circuit, observation):\n"," \"\"\"Store the circuit, ideal probabilities, and a measured circuit.\"\"\"\n"," if exp_id in EXPERIMENTS:\n"," raise ValueError(f\"Duplicate experiment ID: {exp_id}\")\n"," ideal_state = Statevector.from_instruction(circuit)\n"," n = circuit.num_qubits\n"," probabilities = {\n"," format(i, f\"0{n}b\"): float(p)\n"," for i, p in enumerate(ideal_state.probabilities())\n"," if p > 1e-10\n"," }\n"," measured = circuit.copy()\n"," measured.measure_all()\n"," EXPERIMENTS[exp_id] = dict(\n"," title=title, circuit=measured, ideal=probabilities,\n"," n=n, observation=observation,\n"," )\n","\n","\n","def view(exp_id, draw=True):\n"," \"\"\"Show an experiment's actual gates and theoretical predictions.\"\"\"\n"," exp = EXPERIMENTS[exp_id]\n"," print(f\"Experiment {exp_id}: {exp['title']}\")\n"," if draw:\n"," try:\n"," display(exp['circuit'].draw(output='mpl'))\n"," except Exception:\n"," print(exp['circuit'].draw(output='text'))\n"," print(\"Ideal probabilities:\",\n"," {k: f\"{100*v:.1f}%\" for k, v in exp['ideal'].items()})\n"," print(\"Takeaway:\", exp['observation'])\n","\n","\n","def show_group(ids):\n"," \"\"\"Brief overview of the experiments in one section.\"\"\"\n"," for exp_id in ids:\n"," exp = EXPERIMENTS[exp_id]\n"," expected = ', '.join(f\"{k}:{v:.0%}\" for k,v in exp['ideal'].items())\n"," print(f\"{exp_id} {exp['title']} | {expected}\")\n","\n","\n","def plot_distribution(exp_id):\n"," \"\"\"Graph theoretical, simulator, and (when available) physical results.\"\"\"\n"," exp = EXPERIMENTS[exp_id]\n"," bits = [format(i, f\"0{exp['n']}b\") for i in range(2**exp['n'])]\n"," ideal = [exp['ideal'].get(k, 0.0) for k in bits]\n"," sources = [('Theory', ideal)]\n"," if exp_id in SIMULATOR_COUNTS:\n"," sim = SIMULATOR_COUNTS[exp_id]\n"," shots = sum(sim.values())\n"," sources.append(('Simulator', [sim.get(k, 0)/shots for k in bits]))\n"," if exp_id in QPU_COUNTS:\n"," real = QPU_COUNTS[exp_id]\n"," shots = sum(real.values())\n"," sources.append(('Real QPU', [real.get(k, 0)/shots for k in bits]))\n"," width = 0.75/len(sources)\n"," x = list(range(len(bits)))\n"," fig, ax = plt.subplots(figsize=(max(6.5, len(bits)*1.1), 3.8))\n"," for j, (name, values) in enumerate(sources):\n"," offset = (j-(len(sources)-1)/2)*width\n"," ax.bar([a+offset for a in x], values, width=width, label=name)\n"," ax.set_xticks(x, bits)\n"," ax.set_ylim(0, 1.06)\n"," ax.set_ylabel('Measured probability')\n"," ax.set_xlabel('Bitstring (highest-numbered qubit on the left)')\n"," ax.set_title(f\"{exp_id}: {exp['title']}\")\n"," ax.legend()\n"," plt.show()\n","\n","print('Setup complete. Continue to Section 1.')"]},{"cell_type":"markdown","id":"89cdd1c5","metadata":{"id":"89cdd1c5"},"source":["## Section 1 — Starting states, bit flips, and superposition\n","\n","A **qubit** is a quantum system described using two reference states, $|0\\rangle$ and $|1\\rangle$. A newly initialized Qiskit circuit begins in $|0\\rangle$ (or $|00\\rangle$, $|000\\rangle$ for more qubits). An **X gate** swaps $|0\\rangle$ and $|1\\rangle$. A **Hadamard (H) gate** prepares\n","\n","$$H|0\\rangle=|+\\rangle=\\frac{|0\\rangle+|1\\rangle}{\\sqrt2}.$$\n","\n","**Predict:** What should be measured from the three circuits below: no gate, one X gate, and one H gate? Will 256 shots of the H circuit necessarily give exactly 128 zeros and 128 ones?"]},{"cell_type":"code","execution_count":3,"id":"dc35fe56","metadata":{"id":"dc35fe56","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1793655515730,"user_tz":420,"elapsed":12,"user":{"displayName":"Mohammad Saidur Rahman","userId":"05662769360433032878"}},"outputId":"5fb1a0aa-29aa-4616-b883-36902f3dfef9"},"outputs":[{"output_type":"stream","name":"stdout","text":["01 Initial |0> state | 0:100%\n","02 X gate on |0> | 1:100%\n","03 H on |0>, measured in Z | 0:50%, 1:50%\n"]}],"source":["# Section 1 — Build experiments 01, 02, and 03.\n","q = QuantumCircuit(1)\n","register('01', 'Initial |0> state', q, 'The ideal measurement is always 0.')\n","\n","q = QuantumCircuit(1)\n","q.x(0)\n","register('02', 'X gate on |0>', q, 'X changes |0> to |1>.')\n","\n","q = QuantumCircuit(1)\n","q.h(0)\n","register('03', 'H on |0>, measured in Z', q, 'Both 0 and 1 have 50% ideal probability.')\n","\n","show_group(['01', '02', '03'])"]},{"cell_type":"code","execution_count":4,"id":"da4d1f66","metadata":{"id":"da4d1f66","colab":{"base_uri":"https://localhost:8080/","height":245},"executionInfo":{"status":"ok","timestamp":1793655531506,"user_tz":420,"elapsed":543,"user":{"displayName":"Mohammad Saidur Rahman","userId":"05662769360433032878"}},"outputId":"c391bba4-05c0-475f-8d9d-ccc79792c7ee"},"outputs":[{"output_type":"stream","name":"stdout","text":["Experiment 03: H on |0>, measured in Z\n"]},{"output_type":"display_data","data":{"text/plain":["
"],"image/png":"iVBORw0KGgoAAAANSUhEUgAAAVIAAACuCAYAAABk8oU5AAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAAAPYQAAD2EBqD+naQAAFOxJREFUeJzt3XtQVOfdB/DvwsouchEELIsIIgRFBBWCVk1C9MULGHUSzW1MxrfUlHYqMsZRHB3fpO9QY6LBJGqndNIY39gxWvXNxeuLsRC8VYzFovFCdHVEILqA4gICC8/7h2UrAYTd57CHxe9nhnH3nPOc81uQL895zk0jhBAgIiK7uahdABGRs2OQEhFJYpASEUlikBIRSWKQEhFJYpASEUlikBIRSWKQEhFJYpASEUlikBIRSWKQEhFJYpASEUlikBIRSWKQEhFJYpASEUlikBIRSWKQEhFJYpASEUlikBIRSWKQEhFJYpASEUlikBIRSWKQEhFJYpASEUlikBIRSWKQEhFJYpASEUlikBIRSdKqXQCRsyssLOz2siaTCXv27MELL7wAf3//brdLSEiwpzRyEPZIiRzIZDLh448/hslkUrsUUhCDlIhIEoOUiEgSg5SISBKDlMiBvLy8MGPGDHh5ealdCilII4QQahdB5MxsOWpvLx61793YIyVyoIaGBty4cQMNDQ1ql0IKYpASOZDRaMTcuXNhNBrVLoUUxBPyqUNCCMDZek06H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WF898IkAAAAASUVORK5CYII=\n"},"metadata":{}},{"output_type":"stream","name":"stdout","text":["Ideal probabilities: {'0': '50.0%', '1': '50.0%'}\n","Takeaway: Both 0 and 1 have 50% ideal probability.\n"]}],"source":["# Select an experiment and run this cell to see a clear circuit picture.\n","VIEW_ID = '03' # Choose: 01, 02, 03\n","view(VIEW_ID)"]},{"cell_type":"markdown","id":"a63b10e5","metadata":{"id":"a63b10e5"},"source":["**Explain in your own words:** A superposition is not a measurement reporting both bits at once. Each shot reports only one classical outcome. The 50/50 pattern describes many repetitions of the preparation-and-measurement process."]},{"cell_type":"markdown","id":"6453f77a","metadata":{"id":"6453f77a"},"source":["## Section 2 — Relative phase, interference, and measurement bases\n","\n","A **Z gate** changes the sign of the $|1\\rangle$ amplitude: $Z|+\\rangle=|-\\rangle=(|0\\rangle-|1\\rangle)/\\sqrt2$. Both $|+\\rangle$ and $|-\\rangle$ give 50/50 outcomes if measured directly in the **Z basis**. A final H gate changes an **X-basis measurement** into an ordinary Z-basis readout; it can reveal the difference:\n","\n","$$H|+\\rangle=|0\\rangle,\\qquad H|-\\rangle=|1\\rangle.$$\n","\n","**Predict:** Compare H–H with H–Z–H. Why does adding Z change the outcome even though it does not change the direct 50/50 measurement probabilities? A **barrier** below only keeps the teaching stages visible; it is not a physical transformation of the quantum state."]},{"cell_type":"code","execution_count":null,"id":"bd52ad51","metadata":{"id":"bd52ad51"},"outputs":[],"source":["# Section 2 — Build experiments 04–08.\n","q = QuantumCircuit(1)\n","q.h(0); q.barrier(); q.h(0)\n","register('04', 'Interference: H then H', q, 'The ideal measurement is 0.')\n","\n","q = QuantumCircuit(1)\n","q.h(0); q.barrier(); q.z(0); q.barrier(); q.h(0)\n","register('05', 'Interference: H then Z then H', q, 'The ideal measurement is 1.')\n","\n","q = QuantumCircuit(1)\n","q.h(0); q.barrier(); q.h(0)\n","register('06', 'Prepare |+>, measure in X', q, 'The ideal X-basis result is 0.')\n","\n","q = QuantumCircuit(1)\n","q.h(0); q.barrier(); q.z(0)\n","register('07', 'Prepare |->, measure in Z', q, 'Z-basis results are 50% 0 and 50% 1.')\n","\n","q = QuantumCircuit(1)\n","q.h(0); q.barrier(); q.z(0); q.barrier(); q.h(0)\n","register('08', 'Prepare |->, measure in X', q, 'The ideal X-basis result is 1.')\n","\n","show_group(['04', '05', '06', '07', '08'])"]},{"cell_type":"code","execution_count":null,"id":"63ef684c","metadata":{"id":"63ef684c"},"outputs":[],"source":["# View any phase or measurement-basis circuit.\n","VIEW_ID = '05' # Choose: 04, 05, 06, 07, 08\n","view(VIEW_ID)"]},{"cell_type":"markdown","id":"4fee857a","metadata":{"id":"4fee857a"},"source":["**Observe:** Experiments 04 and 06 use the same circuit and have the same result, but teach different ideas (interference versus measurement basis). The same is true of 05 and 08. These are not new algorithms; they are different ways of interpreting familiar gates."]},{"cell_type":"markdown","id":"84f4cbd8","metadata":{"id":"84f4cbd8"},"source":["## Section 3 — Two qubits, the CNOT gate, and independent superpositions\n","\n","A **CNOT** (controlled-NOT) gate flips the target qubit **only when its control qubit is 1** in the computational basis. In `q.cx(0, 1)`, `q0` is the control and `q1` is the target. The printed measurement order is **`q1q0`**, so the input/output order can look reversed when read as a bitstring.\n","\n","**Predict:** Determine all four CNOT outputs. Then compare two *independent* Hadamard qubits with an entangled pair in Section 4."]},{"cell_type":"code","execution_count":null,"id":"9909fc3a","metadata":{"id":"9909fc3a"},"outputs":[],"source":["# Section 3 — All four CNOT inputs and two independent |+> qubits.\n","# Labels are written as q1q0. q0 controls q1.\n","for exp_id, q0, q1 in [\n"," ('09', 0, 0), ('10', 1, 0), ('11', 0, 1), ('12', 1, 1)\n","]:\n"," q = QuantumCircuit(2)\n"," if q0 == 1: q.x(0)\n"," if q1 == 1: q.x(1)\n"," q.barrier()\n"," q.cx(0, 1)\n"," register(exp_id, f'CNOT input q1q0={q1}{q0}', q,\n"," 'The target q1 flips exactly when control q0=1.')\n","\n","q = QuantumCircuit(2)\n","q.h(0); q.h(1)\n","register('13', 'Independent |+> qubits in Z', q,\n"," 'All four outcomes 00, 01, 10, 11 have probability 25%.')\n","\n","show_group(['09', '10', '11', '12', '13'])"]},{"cell_type":"code","execution_count":null,"id":"6d1d5ce7","metadata":{"id":"6d1d5ce7"},"outputs":[],"source":["# View a CNOT circuit or two independent superpositions.\n","VIEW_ID = '10' # Choose: 09, 10, 11, 12, 13\n","view(VIEW_ID)"]},{"cell_type":"markdown","id":"00c3fd81","metadata":{"id":"00c3fd81"},"source":["## Section 4 — Bell states, relative phase, and three-qubit GHZ states\n","\n","An **entangled state** is one that cannot be written as independent states of its qubits. A Bell pair is\n","\n","$$|\\Phi^+\\rangle=\\frac{|00\\rangle+|11\\rangle}{\\sqrt2},\\qquad\n","|\\Phi^-\\rangle=\\frac{|00\\rangle-|11\\rangle}{\\sqrt2}.$$\n","\n","Both show `00` and `11` in the Z basis, but their relative phases lead to **different correlations when measured in the X basis**. To measure both qubits in X, put an H gate on each immediately before ordinary Z measurement.\n","\n","A three-qubit **GHZ state** is $(|000\\rangle+|111\\rangle)/\\sqrt2$. For GHZ measured in X, the ideally allowed output bitstrings have an **even number of 1s**: `000`, `011`, `101`, and `110`.\n","\n","**Predict:** Which results will distinguish $|\\Phi^+\\rangle$ and $|\\Phi^-\\rangle$? Why do the ideal Z-basis Bell histograms look identical?"]},{"cell_type":"code","execution_count":null,"id":"3b274690","metadata":{"id":"3b274690"},"outputs":[],"source":["# Section 4 — Experiments 14–19.\n","q = QuantumCircuit(2)\n","q.h(0); q.barrier(); q.cx(0, 1)\n","register('14', 'Bell Phi+ in Z', q, '00 and 11 appear equally often ideally.')\n","\n","q = QuantumCircuit(2)\n","q.h(0); q.barrier(); q.cx(0, 1); q.barrier(); q.h(0); q.h(1)\n","register('15', 'Bell Phi+ in X', q, 'X-basis results are 00 and 11.')\n","\n","q = QuantumCircuit(2)\n","q.h(0); q.barrier(); q.cx(0, 1); q.barrier(); q.z(0)\n","register('16', 'Bell Phi- in Z', q, 'The same Z-basis histogram as Phi+.')\n","\n","q = QuantumCircuit(2)\n","q.h(0); q.barrier(); q.cx(0, 1); q.barrier(); q.z(0)\n","q.barrier(); q.h(0); q.h(1)\n","register('17', 'Bell Phi- in X', q, 'X-basis results are 01 and 10.')\n","\n","q = QuantumCircuit(3)\n","q.h(0); q.barrier(); q.cx(0, 1); q.cx(1, 2)\n","register('18', 'GHZ state in Z', q, 'The ideal results are 000 and 111.')\n","\n","q = QuantumCircuit(3)\n","q.h(0); q.barrier(); q.cx(0, 1); q.cx(1, 2)\n","q.barrier(); q.h(0); q.h(1); q.h(2)\n","register('19', 'GHZ state in X', q,\n"," 'Only even-parity strings 000, 011, 101, 110 appear ideally.')\n","\n","show_group(['14', '15', '16', '17', '18', '19'])"]},{"cell_type":"code","execution_count":null,"id":"92ff754c","metadata":{"id":"92ff754c"},"outputs":[],"source":["# View any Bell or GHZ experiment.\n","VIEW_ID = '17' # Choose: 14, 15, 16, 17, 18, 19\n","view(VIEW_ID)"]},{"cell_type":"markdown","id":"42249b47","metadata":{"id":"42249b47"},"source":["**Important interpretation:** A histogram that displays `00` and `11` illustrates correlations but, by itself, **does not prove entanglement**. A full entanglement test needs additional measurements or a suitable witness. The X-basis experiments help reveal information hidden from Z-basis measurements."]},{"cell_type":"markdown","id":"141ea4dd","metadata":{"id":"141ea4dd"},"source":["## Section 5 — Why CNOT is not a general quantum copier\n","\n","Suppose `q0` contains $|+\\rangle$ and `q1` contains $|0\\rangle$. Applying CNOT produces the **entangled** state $(|00\\rangle+|11\\rangle)/\\sqrt2$, not two independent copies of $|+\\rangle$. We can compare this with two genuinely independent $|+\\rangle$ qubits.\n","\n","**Predict:** After applying H to both qubits to measure in the X basis, which output should appear from two independent $|+\\rangle$ states? What appears after the attempted CNOT copy?"]},{"cell_type":"code","execution_count":null,"id":"b046daa4","metadata":{"id":"b046daa4"},"outputs":[],"source":["# Section 5 — Experiments 20 and 21: no-cloning comparison.\n","q = QuantumCircuit(2)\n","q.h(0); q.barrier(); q.cx(0, 1)\n","q.barrier(); q.h(0); q.h(1)\n","register('20', 'CNOT copy attempt, X measurement', q,\n"," 'A Bell pair appears: X results are 00 and 11, not 00 alone.')\n","\n","q = QuantumCircuit(2)\n","q.h(0); q.h(1); q.barrier(); q.h(0); q.h(1)\n","register('21', 'Two independent |+> states, X measurement', q,\n"," 'The ideal X-basis result is always 00.')\n","\n","show_group(['20', '21'])"]},{"cell_type":"code","execution_count":null,"id":"1f3b76ee","metadata":{"id":"1f3b76ee"},"outputs":[],"source":["# Compare the two circuits and their ideal predictions.\n","view('20')\n","view('21')"]},{"cell_type":"markdown","id":"ee96cd74","metadata":{"id":"ee96cd74"},"source":["**Explain:** These two examples show that a CNOT with an unknown $|+\\rangle$ input does not create two separate copies. This is an illustration of the **no-cloning principle**, not a general mathematical proof."]},{"cell_type":"markdown","id":"b28a721c","metadata":{"id":"b28a721c"},"source":["## Section 6 — BB84 and sifting a key\n","\n","BB84 uses two measurement bases. The **Z basis** distinguishes $|0\\rangle$ and $|1\\rangle$. The **X basis** distinguishes $|+\\rangle$ and $|-\\rangle$. If Alice and Bob choose the same basis and there are no errors or interference, Bob recovers Alice's bit. If they choose different bases, Bob's result is unpredictable.\n","\n","Relevant hardware experiments are `01` and `02` (Z-basis preparation), `03` and `07` (X-basis states measured in Z), and `06` and `08` (X-basis states measured in X).\n","\n","**Sifting:** Alice and Bob reveal **only their basis choices**, keep positions where the bases match, then use the corresponding bits. In an actual BB84 protocol, they also check errors and perform further security steps before using a final secret key."]},{"cell_type":"code","execution_count":null,"id":"eaa8579e","metadata":{"id":"eaa8579e"},"outputs":[],"source":["# Section 6 — Worked BB84 sifting example (classical post-processing).\n","# These example values do not reveal a real private key.\n","alice_bits = [1, 0, 1, 1, 0, 0, 1, 0]\n","alice_bases = ['Z','X','Z','X','Z','X','Z','X']\n","bob_bases = ['Z','Z','Z','X','X','X','Z','Z']\n","\n","kept_positions = [i+1 for i,(a,b) in enumerate(zip(alice_bases,bob_bases)) if a==b]\n","sifted_bits = [bit for bit,a,b in zip(alice_bits,alice_bases,bob_bases) if a==b]\n","print('Matching positions (counting from 1):', kept_positions)\n","print('Alice sifted bits: ', sifted_bits)\n","print('Sifted key for this example: ', ''.join(map(str,sifted_bits)))"]},{"cell_type":"markdown","id":"154472e8","metadata":{"id":"154472e8"},"source":["**Your task:** Work through this second dataset yourself (do not change the worked example above). Write down the kept positions and Alice's sifted bits, then complete the next cell.\n","\n","| Position | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |\n","|:--|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|\n","| Alice bit | 0 | 1 | 1 | 0 | 1 | 0 | 0 | 1 |\n","| Alice basis | X | Z | Z | X | X | Z | X | Z |\n","| Bob basis | X | X | Z | X | Z | Z | X | Z |"]},{"cell_type":"code","execution_count":null,"id":"4695709a","metadata":{"id":"4695709a"},"outputs":[],"source":["# Section 6 — Student sifting exercise.\n","student_bits = [0, 1, 1, 0, 1, 0, 0, 1]\n","student_alice_bases = ['X','Z','Z','X','X','Z','X','Z']\n","student_bob_bases = ['X','X','Z','X','Z','Z','X','Z']\n","\n","# TODO: Write code to calculate matching positions and sifted bits.\n","# Hint: start from the list-comprehension pattern in the previous cell.\n","student_positions = []\n","student_sifted_key = []\n","print('Matching positions:', student_positions)\n","print('Sifted key bits:', student_sifted_key)"]},{"cell_type":"markdown","id":"37cb55c9","metadata":{"id":"37cb55c9"},"source":["## Section 7 — Simulate all 21 experiments\n","\n","We have now constructed **all 21 circuits**. The next cell executes each circuit using Qiskit's **StatevectorSampler** on a classical computer. These are *simulated measurement samples*, not results from IBM hardware.\n","\n","The exact ideal probabilities and the sampled counts answer different questions: ideal probabilities come from the mathematical state, whereas sampled counts fluctuate because only a finite number of shots are taken."]},{"cell_type":"code","execution_count":null,"id":"a5c47e68","metadata":{"id":"a5c47e68"},"outputs":[],"source":["# Section 7A — Run all 21 circuits locally, without IBM credentials.\n","assert len(EXPERIMENTS) == 21, 'Run Sections 1–5 before this cell.'\n","local_sampler = StatevectorSampler(seed=SEED)\n","experiment_ids = list(EXPERIMENTS)\n","local_job = local_sampler.run(\n"," [EXPERIMENTS[exp_id]['circuit'] for exp_id in experiment_ids],\n"," shots=LOCAL_SHOTS,\n",")\n","local_results = local_job.result()\n","SIMULATOR_COUNTS = {\n"," exp_id: local_results[index].data.meas.get_counts()\n"," for index, exp_id in enumerate(experiment_ids)\n","}\n","print(f'Completed local simulation for {len(SIMULATOR_COUNTS)} circuits.')\n","for exp_id, exp in EXPERIMENTS.items():\n"," print(exp_id, f\"{exp['title']:<43}\", 'counts:', SIMULATOR_COUNTS[exp_id])"]},{"cell_type":"code","execution_count":null,"id":"5b70bd37","metadata":{"id":"5b70bd37"},"outputs":[],"source":["# Section 7B — Choose a circuit and see a readable histogram.\n","PLOT_ID = '14' # Any experiment from 01 through 21\n","view(PLOT_ID)\n","plot_distribution(PLOT_ID)"]},{"cell_type":"markdown","id":"b619464f","metadata":{"id":"b619464f"},"source":["## Section 8 — Connect and run experiments on real IBM Quantum hardware\n","\n","**Before connecting:** Sign in to [IBM Quantum Platform](https://quantum.cloud.ibm.com/) and locate your **own** IBM Quantum API key and **your authorized instance CRN**. They will be requested through hidden prompts. Do not type credentials into code or submit them with your assignment.\n","\n","**Submission safety:** The connection and backend-selection cells do **not** submit jobs. Only **8D** can submit a real QPU job. IBM account plans have usage allocations or charges; check your instance before you enable the submission switch. One job will contain your selected circuits."]},{"cell_type":"code","execution_count":null,"id":"a46bb582","metadata":{"id":"a46bb582"},"outputs":[],"source":["# Section 8A — Connect using YOUR IBM Quantum API key and CRN.\n","from getpass import getpass\n","from qiskit_ibm_runtime import QiskitRuntimeService\n","\n","api_token = getpass('Your IBM Quantum API key (hidden): ').strip()\n","instance_crn = getpass('Your IBM Quantum instance CRN (hidden): ').strip()\n","if not api_token or not instance_crn:\n"," raise ValueError('Both an API key and an instance CRN are required.')\n","\n","service = QiskitRuntimeService(\n"," channel='ibm_quantum_platform',\n"," token=api_token,\n"," instance=instance_crn,\n",")\n","del api_token, instance_crn # Do not print or save credentials.\n","print('IBM Quantum connection established. No QPU job has been submitted.')"]},{"cell_type":"markdown","id":"c7b61d85","metadata":{"id":"c7b61d85"},"source":["**Selecting hardware:** The notebook can use an available IBM QPU accessible to your instance. If your instructor provides a particular processor name, enter it in `QPU_NAME` below; otherwise, the code selects an available processor. You will see the selected backend before submitting anything."]},{"cell_type":"code","execution_count":null,"id":"f698e777","metadata":{"id":"f698e777"},"outputs":[],"source":["# Section 8B — Select circuits, shots, and a QPU. No job submitted.\n","# \"all\" includes every experiment in this student laboratory.\n","EXPERIMENT_GROUP = 'all' # all | fundamentals | bases | cnot | entanglement | no_cloning | custom\n","CUSTOM_IDS = ['03', '05', '14', '17', '18']\n","GROUPS = {\n"," 'all': list(EXPERIMENTS),\n"," 'fundamentals': ['01','02','03','04','05'],\n"," 'bases': ['03','04','05','06','07','08'],\n"," 'cnot': ['09','10','11','12','13'],\n"," 'entanglement': ['14','15','16','17','18','19'],\n"," 'no_cloning': ['20','21'],\n"," 'custom': CUSTOM_IDS,\n","}\n","SELECTED_IDS = GROUPS[EXPERIMENT_GROUP].copy()\n","assert len(SELECTED_IDS) == len(set(SELECTED_IDS))\n","assert all(i in EXPERIMENTS for i in SELECTED_IDS)\n","assert HARDWARE_SHOTS > 0\n","\n","QPU_NAME = '' # Leave blank for automatic selection, or choose an available QPU name.\n","if QPU_NAME:\n"," backend = service.backend(QPU_NAME)\n"," if backend.num_qubits < 3:\n"," raise ValueError('Choose a processor with at least 3 qubits.')\n","else:\n"," backend = service.least_busy(\n"," operational=True, simulator=False, min_num_qubits=3\n"," )\n","print('QPU:', backend.name, '| Qubits:', backend.num_qubits)\n","print('Selected circuits:', ', '.join(SELECTED_IDS))\n","print('Shots per circuit:', HARDWARE_SHOTS)\n","print('Review your IBM instance allocation before submitting.')"]},{"cell_type":"markdown","id":"89be39de","metadata":{"id":"89be39de"},"source":["**Why compile?** IBM hardware has a particular set of supported instructions and physical qubit connections. **Transpilation** converts our teaching circuits into instructions the selected device can execute. The learning-circuit diagrams are kept in their original form for easier interpretation."]},{"cell_type":"code","execution_count":null,"id":"66b062a3","metadata":{"id":"66b062a3"},"outputs":[],"source":["# Section 8C — Compile the selected circuits to the chosen device. No job submitted.\n","from qiskit.transpiler import generate_preset_pass_manager\n","\n","pass_manager = generate_preset_pass_manager(\n"," backend=backend, optimization_level=0\n",")\n","ISA_CIRCUITS = pass_manager.run(\n"," [EXPERIMENTS[i]['circuit'] for i in SELECTED_IDS]\n",")\n","assert len(ISA_CIRCUITS) == len(SELECTED_IDS)\n","print('Successfully compiled', len(ISA_CIRCUITS), 'circuits for', backend.name)\n","print('All selected circuits retain their measurement register.')"]},{"cell_type":"markdown","id":"5b8ab482","metadata":{"id":"5b8ab482"},"source":["### Section 8D — Submit your real QPU job\n","\n","This is the **only** cell that submits quantum hardware jobs. It contains two deliberate safeguards. Change `SUBMIT_TO_QPU` to `True` **and** `CONFIRM_SUBMISSION` to `'SUBMIT'` only when you are ready. Run the cell once and save the printed **job ID**. Re-running it will not submit a second job while a receipt exists.\n","\n","Submitting consumes the usage allocation associated with **your** IBM Quantum instance and may incur charges on paid plans. Never submit from another person's account."]},{"cell_type":"code","execution_count":null,"id":"42949a8f","metadata":{"id":"42949a8f"},"outputs":[],"source":["# Section 8D — Controlled submission of all selected circuits in ONE QPU job.\n","SUBMIT_TO_QPU = False # Change to True deliberately.\n","CONFIRM_SUBMISSION = '' # Type exactly 'SUBMIT' to confirm.\n","\n","from qiskit_ibm_runtime.executor_sampler import Sampler\n","RECEIPT_PATH = Path('CS1190_QPU_Job_Receipt.json')\n","\n","if not SUBMIT_TO_QPU or CONFIRM_SUBMISSION != 'SUBMIT':\n"," print(\"No job submitted. To submit, set SUBMIT_TO_QPU=True and CONFIRM_SUBMISSION='SUBMIT'.\")\n","elif qpu_job is not None or RECEIPT_PATH.exists():\n"," print('A job already exists in this session or a receipt is present.')\n"," print('Use Section 8E to recover the existing job rather than resubmitting.')\n","else:\n"," qpu_sampler = Sampler(mode=backend)\n"," qpu_job = qpu_sampler.run(ISA_CIRCUITS, shots=HARDWARE_SHOTS)\n"," job_receipt = {\n"," 'job_id': qpu_job.job_id(),\n"," 'backend': backend.name,\n"," 'experiment_ids': SELECTED_IDS,\n"," 'shots_per_circuit': HARDWARE_SHOTS,\n"," }\n"," RECEIPT_PATH.write_text(json.dumps(job_receipt, indent=2))\n"," print('Job submitted. Job ID:', job_receipt['job_id'])\n"," print('Use IBM Quantum Platform > Workloads to check your job.')\n"," print('Non-secret receipt saved:', RECEIPT_PATH)"]},{"cell_type":"markdown","id":"72f48b4c","metadata":{"id":"72f48b4c"},"source":["### Section 8E — Check or recover your job\n","\n","The next cell does **not** submit a new job. If your Colab session was restarted, reconnect with your credentials in 8A, then either keep the saved receipt file or enter your job ID in `RECOVER_JOB_ID`. For a recovered job, use the same experiment list as the original submission (normally `all`). You can also find the job ID on IBM Quantum Platform under **Workloads**."]},{"cell_type":"code","execution_count":null,"id":"43a0f843","metadata":{"id":"43a0f843"},"outputs":[],"source":["# Section 8E — Restore an existing job from receipt or a manually entered job ID.\n","RECOVER_JOB_ID = '' # Paste a job ID only when recovering. No credentials here.\n","\n","if RECOVER_JOB_ID.strip():\n"," qpu_job = service.job(RECOVER_JOB_ID.strip())\n"," # A manual recovery assumes the same selected experiment set.\n"," submitted_ids = SELECTED_IDS.copy()\n"," submitted_backend = qpu_job.backend().name\n","elif qpu_job is None and RECEIPT_PATH.exists():\n"," saved = json.loads(RECEIPT_PATH.read_text())\n"," qpu_job = service.job(saved['job_id'])\n"," submitted_ids = saved['experiment_ids']\n"," submitted_backend = saved['backend']\n","elif qpu_job is not None and RECEIPT_PATH.exists():\n"," saved = json.loads(RECEIPT_PATH.read_text())\n"," submitted_ids = saved['experiment_ids']\n"," submitted_backend = saved['backend']\n","else:\n"," print('No existing QPU job found. Return to Section 8D to submit.')\n","\n","if qpu_job is not None:\n"," print('Recovered / active job ID:', qpu_job.job_id())\n"," print('Job experiment IDs:', submitted_ids)"]},{"cell_type":"code","execution_count":null,"id":"dfd6d45a","metadata":{"id":"dfd6d45a"},"outputs":[],"source":["# Section 8F — Check status. Retrieve counts only when the job has completed.\n","if qpu_job is None:\n"," print('No QPU job available. Use 8D to submit or 8E to recover.')\n","else:\n"," s = qpu_job.status()\n"," state = getattr(s, 'name', str(s)).upper().split('.')[-1]\n"," print('IBM QPU job:', qpu_job.job_id(), '| Status:', state)\n"," if state in ('DONE', 'COMPLETED'):\n"," result = qpu_job.result()\n"," if len(result) != len(submitted_ids):\n"," raise RuntimeError('The job result count does not match the experiment list.')\n"," QPU_COUNTS = {\n"," exp_id: result[i].data.meas.get_counts()\n"," for i, exp_id in enumerate(submitted_ids)\n"," }\n"," print('Hardware counts retrieved for', len(QPU_COUNTS), 'circuits.')\n"," for exp_id in submitted_ids:\n"," print(exp_id, QPU_COUNTS[exp_id])\n"," elif state in ('CANCELLED', 'FAILED', 'ERROR'):\n"," print('The job did not complete successfully. Review its status in Workloads.')\n"," else:\n"," print('The job is not finished. Run this status cell again after it completes.')"]},{"cell_type":"markdown","id":"91ae6770","metadata":{"id":"91ae6770"},"source":["## Section 9 — Compare theory, local simulation, and IBM hardware\n","\n","For each experiment, the **theoretical** probabilities come from ideal mathematics; the **local simulator** produces finite-shot counts; and the **IBM QPU** gives physical hardware counts. These may differ because of sampling fluctuations and physical errors. The fraction of outcomes forbidden by the ideal circuit is a useful simple error indicator, **not a full fidelity measurement**."]},{"cell_type":"code","execution_count":null,"id":"9890821a","metadata":{"id":"9890821a"},"outputs":[],"source":["# Section 9A — View a three-way histogram for your chosen experiment.\n","PLOT_ID = '14' # Use any ID returned by your hardware job, such as 03, 05, 14, 17, 18.\n","view(PLOT_ID)\n","plot_distribution(PLOT_ID)\n","if PLOT_ID in QPU_COUNTS:\n"," print('IBM QPU raw counts:', QPU_COUNTS[PLOT_ID])\n","else:\n"," print('Hardware counts not loaded for this experiment; the plot shows available data.')"]},{"cell_type":"code","execution_count":null,"id":"8d3bbcb3","metadata":{"id":"8d3bbcb3"},"outputs":[],"source":["# Section 9B — A simple comparison table for hardware results.\n","if not QPU_COUNTS:\n"," print('Retrieve your QPU results in 8F before interpreting hardware data.')\n","else:\n"," print(f\"{'ID':<4} {'Experiment':<42} {'Unexpected fraction':>21}\")\n"," print('-' * 72)\n"," for exp_id in submitted_ids:\n"," exp = EXPERIMENTS[exp_id]\n"," counts = QPU_COUNTS[exp_id]\n"," total = sum(counts.values())\n"," unexpected = sum(num for bits, num in counts.items()\n"," if exp['ideal'].get(bits, 0.0) < 1e-10)\n"," print(f\"{exp_id:<4} {exp['title'][:42]:<42} {unexpected/total:>20.2%}\")\n"," print('Unexpected outcomes are not a complete measure of entanglement or device fidelity.')"]},{"cell_type":"code","execution_count":null,"id":"539208a1","metadata":{"id":"539208a1"},"outputs":[],"source":["# Section 9C — Save results as a CSV. This cell does not submit a job.\n","CSV_NAME = 'CS1190_Quantum_Hardware_Results.csv'\n","if not QPU_COUNTS:\n"," print('No physical QPU results are loaded yet.')\n","else:\n"," with open(CSV_NAME, 'w', newline='') as fp:\n"," writer = csv.writer(fp)\n"," writer.writerow([\n"," 'job_id','backend','experiment_id','experiment', 'bitstring',\n"," 'theory_probability','simulator_count','qpu_count','qpu_shots',\n"," 'qpu_probability'\n"," ])\n"," for exp_id in submitted_ids:\n"," exp = EXPERIMENTS[exp_id]\n"," real = QPU_COUNTS[exp_id]\n"," sim = SIMULATOR_COUNTS.get(exp_id, {})\n"," nshots = sum(real.values())\n"," for j in range(2 ** exp['n']):\n"," bits = format(j, f\"0{exp['n']}b\")\n"," writer.writerow([\n"," qpu_job.job_id(), submitted_backend, exp_id, exp['title'],\n"," bits, exp['ideal'].get(bits, 0.0), sim.get(bits, 0),\n"," real.get(bits, 0), nshots, real.get(bits, 0)/nshots\n"," ])\n"," print('Saved', CSV_NAME)\n"," print('In Google Colab, download it using the Files panel.')"]},{"cell_type":"markdown","id":"e2f9848a","metadata":{"id":"e2f9848a"},"source":["## Section 10 — Student analysis and submission\n","\n","Answer every question below in **your own words**. When a question asks for observed outcomes, refer to the **actual results** in Sections 7–9. Do not claim that ideal probabilities are hardware measurements. Your report should identify the experiment ID, measured bitstrings, and your explanation.\n","\n","1. **Initialization and X:** Compare experiments `01` and `02`. What is different in their ideal results? What did the real QPU produce?\n","2. **Superposition:** For `03`, calculate the fractions of `0` and `1`. Explain why the counts need not be equal.\n","3. **Interference:** Why do `04` (H–H) and `05` (H–Z–H) have different ideal outputs?\n","4. **Measurement bases:** Compare `07` and `08`. How can we reveal a relative phase that is invisible in a Z-basis measurement?\n","5. **CNOT:** Use `09`–`12` to write the full truth table with qubits in `q1q0` order.\n","6. **Independent versus entangled:** Why does `13` permit four equally likely outcomes while `14` permits only two ideally?\n","7. **Bell phase:** Compare `14` with `16`, then `15` with `17`. What is revealed in the X basis?\n","8. **GHZ state:** Which outcomes dominate in `18`? Why does `19` have four ideally allowed outcomes?\n","9. **No cloning:** Compare `20` and `21`. Why does the CNOT attempt fail to produce two independent $|+\\rangle$ qubits?\n","10. **BB84:** Complete the sifting exercise in Section 6. Why are Alice's and Bob's basis choices compared publicly rather than their secret bits?\n","11. **Physical noise:** Pick a deterministic circuit and an entangled circuit. For each, compute the fraction of measurement outcomes that the ideal circuit forbids. Explain why this is not a complete device-fidelity estimate.\n","12. **Your own quantum circuit:** Create a circuit using X, H, and Z (and a measurement). Predict its ideal outcomes, simulate it, and explain how your result follows from the gates you chose.\n","\n","### Experiment design exercise\n","\n","Edit the next code cell, run it locally, and attach the resulting circuit and histogram to your submission."]},{"cell_type":"code","execution_count":null,"id":"96c20dc7","metadata":{"id":"96c20dc7"},"outputs":[],"source":["# Section 10 — Design your own circuit. Edit the lines marked TODO.\n","my_circuit = QuantumCircuit(1)\n","# TODO: Add at least two gates selected from X, H, and Z.\n","# Example (replace it): my_circuit.h(0)\n","my_circuit.h(0)\n","my_circuit.measure_all()\n","print(my_circuit.draw(output='text'))\n","\n","my_sampler = StatevectorSampler(seed=SEED)\n","my_counts = my_sampler.run([my_circuit], shots=LOCAL_SHOTS).result()[0].data.meas.get_counts()\n","print('My circuit measurements:', my_counts)"]},{"cell_type":"markdown","id":"fdaf5495","metadata":{"id":"fdaf5495"},"source":["### Submit your work\n","\n","Save your notebook using **File → Download → Download `.ipynb`** in Colab. Include your answers to the twelve analysis questions, your edited BB84 sifting and circuit-design cells, and at least **four** hardware-versus-ideal comparisons from different topics (for example superposition, interference, Bell states, and GHZ states). Attach the CSV from Section 9 if you obtained physical QPU results.\n","\n","**Credential safety:** Never share an API key, paste it into notebook source, or upload it as part of your coursework. Use only your own approved IBM Quantum instance.\n","\n","### Official IBM learning references\n","\n","- [IBM Quantum account setup](https://quantum.cloud.ibm.com/docs/en/guides/initialize-account)\n","- [Qiskit StatevectorSampler](https://quantum.cloud.ibm.com/docs/en/api/qiskit/qiskit.primitives.StatevectorSampler)\n","- [Run the IBM Quantum Sampler](https://quantum.cloud.ibm.com/docs/en/guides/get-started-with-sampler)\n","- [Retrieve saved IBM quantum jobs](https://quantum.cloud.ibm.com/docs/en/guides/save-jobs)\n","- [IBM Quantum access plans](https://quantum.cloud.ibm.com/docs/en/guides/plans-overview)"]}],"metadata":{"colab":{"provenance":[]},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":5}