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