Skip to content

Examples

Worked, runnable problems. Every block on this page is run against the release it documents.

Each is complete: copy one into a file and run it.

Compare topologies

The same circuit on four datacenter topologies, holding QPU hardware fixed. This is the basic question the SDK exists to answer: does the wiring matter for my workload?

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import (build_clos, build_fattree, build_bcube,
                                  build_qfly, QPUSpec)
from qndk.partition.kl import KernighanLinPartitioner
from qndk.simulator.dqc import DQCScheduler

circuit = QiskitCircuit("qft", num_qubits=8)
qpu = QPUSpec(comp_qubits=4, connectivity="all2all")

topologies = {
    "clos":    build_clos(ports_per_switch=4, qpus_per_rack=1, qpu_spec=qpu),
    "fattree": build_fattree(num_qpus=4, qpu_spec=qpu),
    "bcube":   build_bcube(num_qpus=4, switch_layers=1,
                           ports_per_switch=4, qpu_spec=qpu),
    "qfly":    build_qfly(num_switches=4, qpus_per_switch=1, qpu_spec=qpu),
}

print(f"{'topology':10s} {'qpus':>5s} {'switches':>9s} "
      f"{'remote':>7s} {'epr':>5s} {'ms':>9s}")
for name, network in topologies.items():
    partition = KernighanLinPartitioner(circuit, network).partition()
    result = DQCScheduler(partition).run_simulation()
    print(f"{name:10s} {len(network.qpu_ids()):5d} "
          f"{len(network.switch_ids()):9d} "
          f"{result.gate_counts()['num_remote']:7d} "
          f"{result.epr_cost():5d} {result.final_timestep:9.4f}")

build_network("clos", ...) is the dispatching form if the topology name is data rather than code.

Compare partitioners

Same circuit, same network, three splitting strategies. EPR cost is the number to watch — it is a direct consequence of the partitioning decision.

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.transpile.transpile import TranspiledCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.partition.kl import KernighanLinPartitioner
from qndk.partition.wbcp import WindowBasedCircuitPartitioner
from qndk.simulator.dqc import DQCScheduler

circuit = TranspiledCircuit(QiskitCircuit("qft", num_qubits=8))
network = build_clos(ports_per_switch=4, qpus_per_rack=1,
                     qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"))

strategies = {
    "kernighan-lin": KernighanLinPartitioner(circuit, network),
    "wbcp":          WindowBasedCircuitPartitioner(circuit, network),
}

for name, partitioner in strategies.items():
    partition = partitioner.partition()
    result = DQCScheduler(partition).run_simulation()
    print(f"{name:14s} epr={result.epr_cost():3d}  "
          f"remote={result.gate_counts()['num_remote']:3d}  "
          f"{result.final_timestep:.4f} ms")

MetisPartitioner slots in identically, on any platform that is not Windows.

A heterogeneous network

Real fleets are not uniform. Override specific QPUs by index while the rest take the baseline spec.

from qndk.quantum_network import build_clos, QPUSpec, QubitSpec

older = QPUSpec(comp_qubits=4, connectivity="all2all",
                qubit=QubitSpec(gate_fidelity=0.99, t1_time_ms=500.0))
newer = QPUSpec(comp_qubits=9, connectivity="all2all",
                qubit=QubitSpec(gate_fidelity=0.9999, t1_time_ms=2000.0))

# QPUs 0 and 1 are the new generation; everything else is older hardware
network = build_clos(
    ports_per_switch=4, qpus_per_rack=2,
    qpu_spec=older,
    qpu_specs={0: newer, 1: newer},
)

for qpu_id in sorted(network.qpu_ids()):
    qpu = network.get_qpu(qpu_id)
    # .comp_qubits yields Qubit objects, not ids
    a_qubit = qpu.comp_qubits[0]
    print(f"{qpu_id:8s} comp={qpu.num_comp_qubits:2d} "
          f"fidelity={a_qubit.gate_fidelity} t1={a_qubit.t1_time_ms} ms")

print("total compute qubits:", network.total_comp_qubits())

Switches and links stay uniform at construction time. Vary them afterwards:

from qndk.quantum_network import build_clos, QPUSpec

network = build_clos(ports_per_switch=4, qpus_per_rack=2,
                     qpu_spec=QPUSpec(comp_qubits=4))

# one congested switch with extra Bell-state measurement capacity
first = sorted(network.switch_ids())[0]
network.update_switch(first, bsm_count=16)
print(first, "bsm_count ->", network.get_switch(first).bsm_count)

# one long, lossy inter-rack link
link_id = network.link_ids()[0]
network.update_link(link_id, length_m=2000.0, loss_db_km=0.25)
link = network.get_link(link_id)
print(f"{link_id}: {link.length_m} m, {link.loss_db():.3f} dB total loss")

Model a real photonic switch

SwitchSpec(model="cisco") derives reconfiguration delay, fidelity, purity and loss from a simulated Cisco photonic switch instead of generic placeholder constants.

from qndk.quantum_network import build_clos, QPUSpec, SwitchSpec

for model in ("generic", "cisco"):
    network = build_clos(
        ports_per_switch=4, qpus_per_rack=2,
        qpu_spec=QPUSpec(comp_qubits=4),
        switch_spec=SwitchSpec(model=model),
    )
    switch = network.get_switch(sorted(network.switch_ids())[0])
    print(f"{model:8s} reconfig={switch.reconfig_delay_ms:.5f} ms  "
          f"fidelity={switch.fidelity:.5f}  loss={switch.loss:.4f}")

Sweep code distance and entanglement speed

The fault-tolerant question: where does spending more qubits stop paying? TlerSweep runs the error budget over a grid so the curves can be compared on one axis.

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.simulator.dqc import DQCScheduler
from qndk.quantum_error_correction import (
    fault_tolerant_encode, SurfaceCode, TlerSweep, tler, FixedIdleEpr)

circuit = QiskitCircuit("tfim", num_qubits=8, num_trotter_steps=1).circuit
circuit.t(3)

network = build_clos(
    ports_per_switch=4, qpus_per_rack=1,
    qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"),
    num_magic_factories=1,
)

partition = fault_tolerant_encode(circuit, network,
                                  code=SurfaceCode(d=15), num_ancilla=1)
result = DQCScheduler(partition).run_simulation()

# one row per code distance, at a fixed idle-noise multiplier
print(f"{'d':>3s} {'total @ p=1e-4':>16s}")
for d in (9, 15, 21, 27):
    budget = tler(result, code=SurfaceCode(d=d), epr=FixedIdleEpr(k_idle=4))
    print(f"{d:3d} {budget.total[0]:16.3e}")

# the same grid as one object, for plotting
sweep = TlerSweep(result, code=[SurfaceCode(d=d) for d in (9, 15, 21, 27)],
                  epr=[FixedIdleEpr(k_idle=k) for k in (1, 4, 16)])
print(f"\nsweep produced {len(sweep.results)} curves")

Then plot from the objects that own the data rather than writing matplotlib by hand:

# fragment: opens windows
sweep.plot_comparison()      # LER_total for every curve on shared axes
sweep.plot_vs_distance(p=1e-4)   # does more distance keep helping?
sweep.plot_threshold_vs_k()  # the fitted threshold, straight from the table
  • plot_comparison()

    plot_comparison() — LERtotal for every code distance, on shared axes.

  • plot_vs_distance()

    plot_vs_distance(p=1e-4) — does more distance keep helping, at a fixed physical error rate?

  • plot_threshold_vs_k()

    plot_threshold_vs_k() — the fitted remote threshold, read straight from the table.

Compare the two entanglement models

They are not two spellings of the same number, and the gap between them is worth seeing on your own workload.

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.simulator.dqc import DQCScheduler
from qndk.quantum_error_correction import (
    fault_tolerant_encode, SurfaceCode, tler, FixedIdleEpr, PoissonEpr)

circuit = QiskitCircuit("tfim", num_qubits=8, num_trotter_steps=1).circuit
circuit.t(3)
network = build_clos(ports_per_switch=4, qpus_per_rack=1,
                     qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"),
                     num_magic_factories=1)
code = SurfaceCode(d=9)
partition = fault_tolerant_encode(circuit, network, code=code,
                                  num_ancilla=1)
result = DQCScheduler(partition).run_simulation()

models = [
    FixedIdleEpr(k_idle=1),
    FixedIdleEpr(k_idle=16),
    PoissonEpr(mu=1.0, policy="async"),
    PoissonEpr(mu=0.2, policy="async"),
    PoissonEpr(mu=0.2, policy="sync"),
]
budgets = []
for epr in models:
    budget = tler(result, code=code, epr=epr)
    budgets.append(budget)
    print(f"{type(epr).__name__:14s} {epr.label:12s} "
          f"total={budget.total[0]:.3e}")

The sync versus async pair is the scheduling-policy result: each seam ancilla measuring on whichever round its own pair lands in, versus all of them waiting for the slowest on a shared clock.

Plot the same budgets against each other with plot_comparison():

# fragment: opens a window
from qndk.quantum_error_correction import plot_comparison

plot_comparison(budgets, label_fn=lambda b: b.epr.label)

Total logical error rate under FixedIdleEpr and PoissonEpr, at k_idle=1, k_idle=16, mu=1.0 and mu=0.2

k_idle=16 is the outlier — over an order of magnitude more pessimistic than everything else. All three Poisson curves stay close to the fast FixedIdleEpr baseline, which is the point made in the FAQ entry on FixedIdleEpr or PoissonEpr: the two are not interchangeable spellings of "slow."

Schedule many jobs on one topology

QuantumBatchScheduler runs a queue of circuits against a shared network and reports makespan and wastage.

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.transpile.transpile import TranspiledCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.partition.kl import KernighanLinPartitioner
from qndk.batchscheduler.batch_scheduler import QuantumBatchScheduler

network = build_clos(ports_per_switch=4, qpus_per_rack=2,
                     qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"))

jobs = []
for i, n in enumerate((4, 6, 5, 8)):
    tc = TranspiledCircuit(QiskitCircuit("qft", num_qubits=n))
    jobs.append({"id": f"job-{i}", "num_qubits": n,
                 "transpiled_circuit": tc})

scheduler = QuantumBatchScheduler(
    network=network,
    partitioner_fn=lambda circuit, net:
        KernighanLinPartitioner(circuit, net).partition(),
)

def report(label, out):
    # total_execution_cost is the makespan; wastage_per_qubit is average
    # idle time per qubit in the same units, not a fraction
    print(f"{label:11s} makespan={out['total_execution_cost']:8.2f} "
          f"wastage/qubit={out['wastage_per_qubit']:8.2f} "
          f"jobs={len(out['job_results'])}")

report("fifo", scheduler.run_fifo_strict(jobs))
for heuristic in ("hybrid", "min_qubits", "max_qubits"):
    report(heuristic, scheduler.run_batch_optimized(jobs,
                                                    heuristic=heuristic))

Compile to a runnable distributed circuit

The other packages stop at metrics. qndk.compile emits an actual circuit, with explicit entanglement-generation gates, that Qiskit Aer can execute.

import json

from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.partition.kl import KernighanLinPartitioner
from qndk.compile.distributed import new_exec_plan

circuit = QiskitCircuit("simple", num_qubits=4)
network = build_clos(ports_per_switch=4, qpus_per_rack=1,
                     qpu_spec=QPUSpec(comp_qubits=2, connectivity="all2all"))

partition = KernighanLinPartitioner(circuit, network).partition()
plan = new_exec_plan(partition)

# to_json() carries both the QASM3 of the compiled circuit and its op counts
blob = json.loads(plan.to_json())
for key, value in sorted(blob["stats"].items()):
    print(f"{key:18s} {value}")
print(f"{'qasm3 bytes':18s} {len(blob['qasm3'])}")

Because this one really does simulate the quantum state, it scales like any state-vector simulator — keep the circuit small.

Record and compare many runs

Analyzer collects metrics passively across a run without changing simulation state, and turns a batch of runs into dataframes.

from qndk.analysis.analyzer import Analyzer
from qndk.circuit.qiskit_circuits import QiskitCircuit
from qndk.transpile.transpile import TranspiledCircuit
from qndk.quantum_network import build_clos, QPUSpec
from qndk.partition.kl import KernighanLinPartitioner
from qndk.simulator.dqc import DQCScheduler

analyzer = Analyzer(run_id="topology-comparison")

for qpus_per_rack in (1, 2):
    circuit = TranspiledCircuit(QiskitCircuit("qft", num_qubits=8))
    network = build_clos(ports_per_switch=4, qpus_per_rack=qpus_per_rack,
                         qpu_spec=QPUSpec(comp_qubits=4, connectivity="all2all"))
    partition = KernighanLinPartitioner(circuit, network).partition()
    result = DQCScheduler(partition).run_simulation()

    analyzer.record_circuit(circuit, name=f"qft8-{qpus_per_rack}")
    analyzer.record_network(network)
    analyzer.record_partition("kernighan-lin", partition)
    analyzer.record_run_global(
        run_key=f"clos-{qpus_per_rack}",
        topology_type="clos",
        topology_id=f"qpus_per_rack={qpus_per_rack}",
        algorithm="kernighan-lin",
        makespan=result.final_timestep,
    )

print(analyzer.get_runs_df().to_string(index=False))

Where to go next

Each example above stands alone. For the types each stage hands the next, see Packages; for the full callable surface, the Complete API Reference.