{ "cells": [ { "cell_type": "markdown", "id": "64877183", "metadata": {}, "source": [ "Generated from cosmiq's `docs/tutorials/05_qiskit_digital.py` for Colab: the first cell installs cosmiq." ] }, { "cell_type": "code", "execution_count": null, "id": "5f83c765", "metadata": {}, "outputs": [], "source": [ "%pip install --quiet \"cosmiq[qiskit]\"" ] }, { "cell_type": "markdown", "id": "399a0dc3", "metadata": {}, "source": [ "# Tutorial 5: a digital circuit through Qiskit\n", "\n", "cosmiq's digital path runs gate-model circuits on the atoms of a register: CZ gates between\n", "atoms close enough to interact, and single-qubit rotations. You write the circuit in Qiskit.\n", "`cosmiq.qiskit` gives Qiskit a target for the device, and runs the transpiled circuit with\n", "local `SamplerV2` and `EstimatorV2` primitives. We'll\n", "\n", "1. read cosmiq-ref-1's digital profile, and build its Qiskit target on a chain of atoms;\n", "2. write a GHZ circuit in Qiskit, and transpile it to that target;\n", "3. run it without noise, and check the values against Qiskit's own simulator;\n", "4. run it with the profile's noise;\n", "5. see a circuit the device can't run refused, then transpiled so it can.\n", "\n", "It needs the extra: `pip install \"cosmiq[qiskit]\"`. Run it with\n", "`python docs/tutorials/05_qiskit_digital.py`; `COSMIQ_TUTORIAL_QUICK=1` gives a quick version,\n", "which runs in a few seconds. docs/qiskit.md and docs/digital.md have the details." ] }, { "cell_type": "code", "execution_count": null, "id": "ccbd8378", "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "import numpy as np\n", "from qiskit import QuantumCircuit, transpile\n", "from qiskit.primitives import StatevectorEstimator\n", "from qiskit.quantum_info import SparsePauliOp\n", "\n", "import cosmiq as cq\n", "from cosmiq.qiskit import EstimatorV2, SamplerV2, target\n", "from cosmiq.units import um\n", "\n", "QUICK = os.environ.get(\"COSMIQ_TUTORIAL_QUICK\") == \"1\"\n", "SHOTS = 400 if QUICK else 4000\n", "ATOMS = 5\n", "DEVICE = \"cosmiq-ref-1\"" ] }, { "cell_type": "markdown", "id": "d9b563f6", "metadata": {}, "source": [ "## 1. The device's gates, on a register\n", "\n", "A device's native gates, their timing and its noise make up its **digital profile**. A CZ acts\n", "only between atoms at most `cz_range_um` apart. `target(device, register)` turns the profile\n", "into a Qiskit `Target` on your atoms: `r` and `rz` on every atom, and `cz` on every pair in\n", "range. Qubit $q$ is atom $q$. Our five atoms sit in a chain, so only neighbours get a CZ." ] }, { "cell_type": "code", "execution_count": null, "id": "bbe4b1ad", "metadata": {}, "outputs": [], "source": [ "profile = cq.digital.profile(DEVICE)\n", "register = cq.Register.chain(ATOMS, spacing=5.0 * um)\n", "tgt = target(DEVICE, register)\n", "\n", "distances = register.distances()\n", "pairs = sorted(tgt.qargs_for_operation_name(\"cz\"))\n", "in_range = [\n", " (a, b)\n", " for a in range(ATOMS)\n", " for b in range(ATOMS)\n", " if a != b and distances[a, b] <= profile.cz_range_um\n", "]\n", "print(f\"{DEVICE}, digital profile {profile.profile_version}: CZ within {profile.cz_range_um} µm\")\n", "print(\"native gates:\", sorted(tgt.operation_names))\n", "print(\"CZ pairs:\", [(a, b) for a, b in pairs if a < b])\n", "assert pairs == sorted(in_range)\n", "assert all(abs(a - b) == 1 for a, b in pairs)" ] }, { "cell_type": "markdown", "id": "b8901398", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## 2. A circuit in Qiskit, transpiled to the device\n", "\n", "A GHZ state, $(|0\\cdots 0\\rangle + |1\\cdots 1\\rangle)/\\sqrt{2}$: a Hadamard, then a chain of\n", "CNOTs. Neither gate is native. Qiskit's transpiler rewrites them in `r`, `rz` and `cz`, and\n", "keeps every CZ on a pair the target allows. The sampler takes the circuit with its\n", "measurements, the estimator without them." ] }, { "cell_type": "code", "execution_count": null, "id": "1adfaf62", "metadata": {}, "outputs": [], "source": [ "def to_device(circuit: QuantumCircuit) -> QuantumCircuit:\n", " return transpile(circuit, target=tgt, optimization_level=2, seed_transpiler=1)\n", "\n", "\n", "def cz_pairs(circuit: QuantumCircuit) -> list[tuple[int, int]]:\n", " \"\"\"The atoms of every CZ in a circuit.\"\"\"\n", " found = []\n", " for instruction in circuit.data:\n", " if instruction.operation.name == \"cz\":\n", " a, b = (circuit.find_bit(qubit).index for qubit in instruction.qubits)\n", " found.append((a, b))\n", " return found\n", "\n", "\n", "ghz = QuantumCircuit(ATOMS)\n", "ghz.h(0)\n", "for q in range(ATOMS - 1):\n", " ghz.cx(q, q + 1)\n", "ghz_t = to_device(ghz)\n", "measured_t = to_device(ghz.measure_all(inplace=False))\n", "print(\"transpiled:\", dict(measured_t.count_ops()))\n", "assert not {\"h\", \"cx\"} & set(tgt.operation_names)\n", "assert set(measured_t.count_ops()) <= {\"cz\", \"r\", \"rz\", \"measure\", \"barrier\"}\n", "assert all(pair in pairs for pair in cz_pairs(ghz_t) + cz_pairs(measured_t))" ] }, { "cell_type": "markdown", "id": "2c57302a", "metadata": {}, "source": [ "## 3. Without noise, against Qiskit's own simulator\n", "\n", "With `noise=False` the sampler reads the ideal state: every shot is all 0 or all 1. The GHZ\n", "state has $\\langle Z_0 Z_1 \\rangle = 1$ and $\\langle X^{\\otimes 5} \\rangle = 1$. The\n", "observables follow the transpiled circuit's layout (`apply_layout`), as on any Qiskit backend.\n", "We run the same pub on Qiskit's `StatevectorEstimator` too: that is code against code, not\n", "hardware." ] }, { "cell_type": "code", "execution_count": null, "id": "e6ea093a", "metadata": {}, "outputs": [], "source": [ "ideal = SamplerV2(device=DEVICE, register=register, noise=False, seed=7)\n", "counts = ideal.run([measured_t], shots=SHOTS).result()[0].data.meas.get_counts()\n", "print(\"noise-free counts:\", counts)\n", "assert set(counts) == {\"0\" * ATOMS, \"1\" * ATOMS}\n", "\n", "observables = [\n", " SparsePauliOp.from_sparse_list([(\"ZZ\", [0, 1], 1.0)], num_qubits=ATOMS),\n", " SparsePauliOp(\"X\" * ATOMS),\n", "]\n", "pub = (ghz_t, [observable.apply_layout(ghz_t.layout) for observable in observables])\n", "ours = EstimatorV2(device=DEVICE, register=register).run([pub]).result()[0].data.evs\n", "theirs = StatevectorEstimator().run([pub]).result()[0].data.evs\n", "gap = float(np.max(np.abs(ours - theirs)))\n", "print(\"⟨Z0 Z1⟩, ⟨X...X⟩ from cosmiq:\", [f\"{value:.12f}\" for value in ours])\n", "print(\"the same from Qiskit: \", [f\"{value:.12f}\" for value in theirs])\n", "print(f\"largest difference: {gap:.1e}\")\n", "assert gap <= 1e-10\n", "assert np.allclose(ours, 1.0, rtol=0.0, atol=1e-10)" ] }, { "cell_type": "markdown", "id": "3aaa68a1", "metadata": {}, "source": [ "## 4. With the profile's noise\n", "\n", "`noise=True` draws a Pauli trajectory for each shot from the profile's channels: depolarising\n", "noise after gates, a Z on the spectators near each CZ, idle dephasing, atom loss, and\n", "preparation and readout errors (docs/digital.md lists each rate and where it acts). Some shots\n", "now leave the two GHZ outcomes. With noise, the estimator gives the mean over trajectories and\n", "its standard error; readout errors don't enter it. The parity $\\langle X^{\\otimes 5} \\rangle$\n", "falls below 1 by more than three standard errors." ] }, { "cell_type": "code", "execution_count": null, "id": "59e4e99b", "metadata": {}, "outputs": [], "source": [ "noisy = SamplerV2(device=DEVICE, register=register, noise=True, seed=7)\n", "counts = noisy.run([measured_t], shots=SHOTS).result()[0].data.meas.get_counts()\n", "ghz_shots = counts.get(\"0\" * ATOMS, 0) + counts.get(\"1\" * ATOMS, 0)\n", "top = sorted(counts.items(), key=lambda item: -item[1])[:4]\n", "print(f\"{ghz_shots} of {SHOTS} shots read all 0 or all 1; the most frequent: {top}\")\n", "assert ghz_shots < SHOTS\n", "\n", "estimator = EstimatorV2(device=DEVICE, register=register, noise=True, seed=7)\n", "data = estimator.run([pub]).result()[0].data\n", "for name, value, error in zip((\"⟨Z0 Z1⟩\", \"⟨X...X⟩\"), data.evs, data.stds, strict=True):\n", " print(f\"{name} = {value:.4f} ± {error:.4f}: {(1 - value) / error:.1f} standard errors below 1\")\n", "assert data.evs[1] < 1 - 3 * data.stds[1]" ] }, { "cell_type": "markdown", "id": "525892cb", "metadata": {}, "source": [ "## 5. What the device can't run\n", "\n", "A circuit is checked when you call `run()`, before anything is simulated. Here a native\n", "circuit puts atoms 0 and 2 in a Bell state with one CZ between them. They are two spacings\n", "apart, out of range, and the refusal names the rule and the fix. Transpiled with `target()`,\n", "the same circuit runs: every CZ is in range, and atoms 0 and 2 still always read alike." ] }, { "cell_type": "code", "execution_count": null, "id": "9d389579", "metadata": {}, "outputs": [], "source": [ "direct = QuantumCircuit(ATOMS)\n", "direct.r(np.pi / 2, np.pi / 2, 0) # r(theta, pi/2) is RY(theta)\n", "direct.r(np.pi / 2, np.pi / 2, 2)\n", "direct.cz(0, 2)\n", "direct.r(-np.pi / 2, np.pi / 2, 2)\n", "direct.measure_all()\n", "assert (0, 2) not in pairs\n", "try:\n", " ideal.run([direct])\n", "except cq.CapabilityError as error:\n", " refusal = str(error)\n", "else:\n", " raise RuntimeError(\"a CZ out of range ran\")\n", "print(refusal)\n", "assert refusal.startswith(\"[DIGITAL_RANGE]\")\n", "assert \"fix: transpile\" in refusal\n", "\n", "routed = to_device(direct)\n", "counts = ideal.run([routed], shots=SHOTS).result()[0].data.meas.get_counts()\n", "print(\"transpiled:\", dict(routed.count_ops()))\n", "print(\"counts:\", counts)\n", "assert all(pair in pairs for pair in cz_pairs(routed))\n", "assert set(counts) == {\"00000\", \"00101\"} # bit q is the q-th from the right" ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "-all", "main_language": "python", "notebook_metadata_filter": "-all", "text_representation": { "extension": ".py", "format_name": "percent" } }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5 }