Introduction to Quantum Computing

Chapter 12
Quantum Programming and Experimentation

Diploma in Quantum Computing
Introduction to Quantum Computing   •   Diploma

Quantum Programming and Experimentation

Introduction

Quantum computing becomes practically useful only when abstract quantum principles are translated into executable programs. A quantum program specifies a circuit, a measurement strategy, a target backend, and a method for interpreting results. Contemporary quantum software development kits (SDKs) provide the tools needed to construct, simulate, transpile, execute, visualize, and evaluate these programs.

This chapter uses the Qiskit ecosystem as a representative SDK. Software interfaces change over time, so learners should consult the documentation for the installed release. The central workflow, however, is stable:

design → construct → validate → transpile → simulate or execute → collect data → visualize → evaluate → document

The objective is not merely to run code. A professional quantum developer must be able to explain what the circuit represents, identify assumptions, distinguish simulation from hardware execution, and produce results that another person can reproduce.

Learning objectives

By the end of this chapter, you should be able to:

  1. Explain the role of a quantum SDK and its main software components.
  2. Construct quantum circuits containing gates, measurements, and classical registers.
  3. Simulate circuits and interpret measurement counts and probability distributions.
  4. Transpile circuits for a selected backend and explain the effects of hardware constraints.
  5. Execute circuits on simulators or cloud-accessible quantum hardware using responsible workflows.
  6. Visualize circuits, distributions, and experimental results.
  7. Evaluate noise, sampling uncertainty, fidelity, and reproducibility.
  8. Design a small, documented quantum experiment.

1. The quantum software stack

A quantum application normally contains several layers:

LayerPurposeTypical artifact
AlgorithmDefines the computational or scientific objectiveSearch, estimation, optimization, simulation
CircuitExpresses operations on qubitsQuantum gates and measurements
SDKProvides programming interfaces and utilitiesQiskit, Cirq, PennyLane
TranspilerConverts abstract circuits to backend-compatible circuitsBasis gates, routing, scheduling
BackendExecutes the circuitSimulator or quantum processor
AnalysisConverts raw samples into evidenceCounts, probabilities, plots, error metrics

A circuit is a sequence of operations on qubits. A measurement maps quantum information to classical outcomes. If a circuit measures an n-qubit register, an outcome is commonly represented as an n-bit string such as 010, although the displayed bit order must be checked because SDK conventions can differ.

The probability of observing outcome x when the final state is |ψ⟩ is:

P(x) = |⟨x|ψ⟩|²

Here, |ψ⟩ is the final state vector, |x⟩ is the computational-basis state associated with outcome x, and P(x) is dimensionless. The equation applies to ideal projective measurement in the computational basis. In an experiment with N shots, the observed count kₓ gives the empirical frequency:

p̂(x) = kₓ/N

where 0 ≤ kₓ ≤ N and ∑ₓ kₓ = N. The empirical frequency estimates the underlying probability; it is not necessarily equal to it.

2. Installing and organizing a reproducible environment

A practical environment should record the Python version, SDK versions, operating system, backend name, circuit source, random seeds where applicable, and execution date. A minimal installation for local circuit construction and simulation may include:

python -m venv qc-env
# Activate the environment according to your operating system
python -m pip install --upgrade pip
python -m pip install qiskit qiskit-aer matplotlib

A useful project structure is:

quantum-project/
├── README.md
├── requirements.txt
├── notebooks/
├── src/
├── experiments/
│   ├── raw/
│   └── processed/
└── results/

A requirements file freezes dependencies sufficiently for a teaching or research exercise:

qiskit==<tested-version>
qiskit-aer==<tested-version>
matplotlib==<tested-version>

Exact version numbers should be selected and tested by the project owner rather than copied indefinitely from an old example. Cloud credentials must never be placed directly in source code or committed to a public repository.

3. Constructing a circuit with Qiskit

The following example creates a Bell state. The Hadamard gate produces superposition, and the controlled-NOT gate creates entanglement. Measurement is then applied to both qubits.

from qiskit import QuantumCircuit

bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
bell.measure([0, 1], [0, 1])

print(bell)

The ideal state before measurement is:

|Φ⁺⟩ = (|00⟩ + |11⟩)/√2

Consequently, ideal measurements produce 00 and 11 with approximately equal frequency. The symbols |00⟩ and |11⟩ denote computational-basis states, while |Φ⁺⟩ denotes a Bell state.

A circuit object records operations; it does not automatically execute them. This separation is important because the same circuit can be sent to different simulators or hardware backends.

Gates, barriers, and measurements

Common operations include:

  • h(q): Hadamard gate on qubit q.
  • x(q), y(q), and z(q): Pauli gates.
  • rz(angle, q): rotation around the z-axis.
  • cx(control, target): controlled-NOT gate.
  • measure(qubit, classical_bit): measurement and storage of the classical result.
  • barrier(): a visual or transpilation boundary, useful for readability but not a physical operation.

Angles are normally expressed in radians. For example, a rotation of π/2 is written using numpy.pi / 2.

The order of quantum and classical bits deserves attention. Qiskit commonly displays bit strings with the highest-index classical bit on the left. Therefore, a result labelled 01 may correspond to classical bit 0 being 1 and classical bit 1 being 0. Always verify bit ordering with a small known circuit.

4. Simulation: ideal and noisy models

A statevector simulator calculates amplitudes for an ideal circuit. It is useful for debugging and for examining states before measurement, but it becomes expensive as the number of qubits grows because a general n-qubit state requires 2ⁿ complex amplitudes.

A shot-based simulator samples measurement outcomes. The following example uses AerSimulator, a commonly used simulator in the Qiskit ecosystem:

from qiskit_aer import AerSimulator

simulator = AerSimulator()
compiled_bell = bell
job = simulator.run(compiled_bell, shots=1024, seed_simulator=7)
result = job.result()
counts = result.get_counts()
print(counts)

The shots argument specifies the number of independent circuit repetitions. With 1,024 shots, results might be approximately {'00': 510, '11': 514}, although exact values vary.

For a binary event with true probability p, the standard deviation of its empirical frequency is:

σₚ̂ = √[p(1 − p)/N]

This expression assumes independent identically distributed shots and a fixed probability p. For p = 0.5 and N = 1,024:

σₚ̂ = √[0.5 × 0.5/1024] = 0.015625

Thus, random sampling alone produces fluctuations of roughly 1.6 percentage points in the estimated probability. This is not hardware noise; it is statistical sampling uncertainty.

A noisy simulator adds a model of errors such as gate depolarization, readout error, relaxation, or dephasing. A noisy result therefore combines sampling variation with the assumptions of the selected noise model. A noisy simulation is not evidence that a physical device behaved in exactly that way.

5. Transpilation and backend constraints

An abstract circuit may use gates or connections unavailable on a target device. Transpilation converts it into a circuit compatible with that backend. It can:

  • rewrite gates into the backend’s basis gate set;
  • map logical qubits to physical qubits;
  • insert SWAP gates when required connectivity is absent;
  • optimize redundant operations;
  • schedule operations in time;
  • adapt the circuit to backend instruction and timing constraints.

A simple local example is:

from qiskit import transpile

transpiled_bell = transpile(
    bell,
    backend=simulator,
    optimization_level=1,
    seed_transpiler=11
)
print(transpiled_bell)

Optimization levels are backend- and version-dependent, but they generally trade compilation effort against circuit reduction. The seed_transpiler helps make stochastic compilation choices repeatable.

Important metrics include:

  • Depth: the length of the longest sequence of dependent operations.
  • Gate count: the number of operations, sometimes reported by gate type.
  • Two-qubit gate count: especially important because two-qubit operations are often less reliable than single-qubit operations.
  • Width: the number of qubits and classical bits.
  • SWAP overhead: additional operations introduced by connectivity constraints.

Transpilation may change the visual appearance of a circuit without changing its intended logical function. It can also affect performance: a logically simple circuit may become less reliable if routing introduces many additional two-qubit gates.

6. Execution on cloud hardware

Cloud execution normally involves four stages:

  1. Authenticate using a provider-supported account mechanism.
  2. Select a backend that satisfies qubit, queue, instruction, and access requirements.
  3. Transpile the circuit for that backend.
  4. Submit the job, record its identifier, wait for completion, and retrieve results.

A provider-specific workflow may use IBM Quantum services and Qiskit Runtime primitives such as a sampler. Since authentication and runtime interfaces evolve, code should follow the installed Qiskit Runtime documentation. Conceptually, the sampler returns sampled bitstrings or related distributions for one or more circuits.

A responsible hardware record should include:

ItemExample description
BackendPublic superconducting processor, with full name
Job identifierProvider-issued permanent identifier
Shots4,096
Transpiler settingsOptimization level and seed
Circuit hashHash of source or serialized circuit
Calibration contextDate and relevant backend properties
Software versionsPython and package versions

Queue time, calibration drift, qubit selection, crosstalk, thermal relaxation, readout error, and transient faults can affect outcomes. Repeating a job later is not necessarily an exact replication because the hardware state may have changed.

7. Visualizing circuits and results

Circuit diagrams communicate gate order and connectivity. Distribution plots communicate observed frequencies. A minimal plotting example is:

from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt

plot_histogram(counts)
plt.show()

For a Bell experiment, the plot should show two dominant bars, 00 and 11. Small counts in 01 or 10 may indicate sampling fluctuations, noise, or an implementation problem.

A visual result must be accompanied by metadata. A plot without the number of shots, backend, circuit version, and processing method is difficult to interpret or reproduce.

8. Evaluating experimental results

Distribution distance

For an ideal distribution p and an observed distribution q, total variation distance is:

DTV(p, q) = ½ ∑ₓ |p(x) − q(x)|

Both p and q must be normalized probability distributions over the same outcomes. The value lies between 0 and 1. A value of 0 means identical distributions; larger values indicate greater disagreement.

For an ideal Bell distribution p(00) = p(11) = 0.5 and p(01) = p(10) = 0, suppose an experiment gives q(00) = 0.48, q(11) = 0.47, q(01) = 0.03, and q(10) = 0.02. Then:

DTV = ½(0.02 + 0.03 + 0.03 + 0.02) = 0.05

The observed distribution differs from the ideal distribution by total variation distance 0.05.

Expectation values

For an observable O with outcomes oᵢ and probabilities pᵢ, its expectation value is:

⟨O⟩ = ∑ᵢ oᵢpᵢ

The sum must use the observable’s eigenvalues, not merely bit labels. For a Pauli-Z measurement, assigning bit 0 to eigenvalue +1 and bit 1 to eigenvalue −1 gives:

⟨Z⟩ = P(0) − P(1)

For a Bell state, each individual qubit has approximately equal 0 and 1 frequencies, so its individual Z expectation is near zero. However, the correlation observable ZZ has expectation near +1 because equal bits occur together.

Fidelity and correlation

For a pure target state |ψ⟩ and a simulated pure state |φ⟩, state fidelity is:

F = |⟨ψ|φ⟩|²

This formula applies to pure states. More general mixed-state fidelity uses a different density-matrix expression and should not be replaced casually by the pure-state formula.

For a Bell experiment, the same-bit correlation can be estimated as:

C = [n₀₀ + n₁₁ − n₀₁ − n₁₀]/N

Here nᵢⱼ is the count for outcome ij and N is the total number of shots. Perfect ideal correlation gives C = 1, while perfect anti-correlation gives C = −1.

9. A reproducible experimentation workflow

A professional experiment separates hypothesis, implementation, execution, and analysis.

Step 1: State the question

Example: “Does a hardware-executed Bell circuit preserve the same-bit correlation expected from the ideal circuit?”

Step 2: Define the reference

Create an ideal simulator result and record its circuit, shots, and seed. The ideal distribution is the reference model, not an assertion that hardware must produce identical counts.

Step 3: Validate the circuit

Check qubit count, measurement mapping, gate order, and bit-string convention. Test a simpler circuit when debugging.

Step 4: Compile deliberately

Transpile for the intended backend and inspect depth, gate counts, and routing overhead.

Step 5: Execute controls

Use a zero circuit and known basis-state circuits to investigate readout behaviour. Controls help distinguish circuit errors from backend-wide effects.

Step 6: Repeat when appropriate

Repeated jobs provide information about variability, but repetitions should be recorded rather than silently pooled. Report whether results are from one job, multiple jobs, or multiple backend days.

Step 7: Analyse with stated metrics

Report counts, normalized frequencies, uncertainty, correlation, and a distribution distance where useful. Do not report a single score without defining it.

Step 8: Preserve evidence

Save source code, environment information, circuit diagrams, transpiled circuits, job identifiers, raw counts, and analysis scripts.

Applied case: testing a Bell circuit on simulator and hardware

Background

This illustrative case concerns a student team evaluating whether a two-qubit entanglement circuit produces correlated measurements.

Problem

The team observes approximately equal 00 and 11 outcomes on an ideal simulator but obtains a smaller correlation on a cloud processor. They must determine whether the difference is caused by sampling, compilation, readout, or gate noise.

Approach

The team follows this sequence:

  1. Build the Bell circuit and verify that measurements are attached to both qubits.
  2. Run 4,096 shots on an ideal simulator with a recorded seed.
  3. Transpile for the selected hardware backend and record depth and two-qubit gate count.
  4. Run a zero-state control and a Bell circuit using the same shot count.
  5. Retrieve raw counts and calculate C, the same-bit correlation.
  6. Compare the hardware distribution with the ideal distribution using total variation distance.
  7. Repeat the hardware job twice and report each job separately.

Suppose the hardware counts are 00 = 1,850, 11 = 1,790, 01 = 240, and 10 = 216. Since the total is 4,096:

C = (1850 + 1790 − 240 − 216)/4096 = 3184/4096 ≈ 0.777

The result demonstrates substantial positive correlation, but it is below the ideal value of 1. The team then inspects the transpiled circuit. If routing inserted extra two-qubit gates, those gates are a plausible contributor. If the zero-state control also shows many unexpected 1 outcomes, readout error is implicated. If the control is clean but the Bell circuit degrades, entangling-gate errors or decoherence are more likely.

Outcome

The team reports the ideal reference, hardware counts, correlation, backend and job identifiers, transpilation settings, and control results. It does not claim that one experiment estimates a universal hardware error rate.

Learning points

  • A circuit’s logical design is not the same as its hardware implementation.
  • Controls are essential for diagnosis.
  • Raw counts are more informative than an unsupported statement that the circuit “worked.”
  • Reproducibility requires software, hardware, and execution metadata.

Challenges, limitations, and responsible practice

Quantum software has several important limitations:

  • Exponential state descriptions: classical statevector simulation becomes impractical for sufficiently large general circuits.
  • Sampling cost: estimating a small probability accurately may require many shots.
  • Noise and drift: hardware performance changes over time.
  • Compilation dependence: different transpiler choices can produce materially different circuits.
  • Bit-order confusion: visually plausible output can still be interpreted backwards.
  • Benchmark ambiguity: a circuit that succeeds on a simulator may fail on hardware.
  • Provider dependence: cloud access, pricing, queues, and APIs vary.

Ethically and professionally, users should protect credentials, avoid submitting sensitive data to shared services, disclose whether results are simulated or hardware-derived, and report failed experiments rather than selectively presenting only favourable runs. Quantum computing does not remove ordinary software engineering responsibilities such as testing, version control, access control, and documentation.

Contemporary development increasingly combines circuit SDKs with hybrid classical–quantum workflows. Parameterized circuits, automatic differentiation, runtime primitives, error mitigation, pulse-level control, and resource estimation are active areas. These techniques are valuable, but they introduce further assumptions. For example, error mitigation can reduce bias in an estimate while increasing variance and classical processing cost; it does not magically restore an exact noiseless computation.

Best-practice checklist

Before publishing or submitting an experiment, confirm that you have:

  • stated the scientific or computational question;
  • identified the SDK and exact tested versions;
  • included circuit construction code;
  • explained qubit and classical-bit ordering;
  • specified shots and random seeds where relevant;
  • recorded backend and job identifiers;
  • distinguished ideal simulation, noisy simulation, and hardware execution;
  • inspected the transpiled circuit;
  • retained raw counts;
  • defined every evaluation metric;
  • included controls or sanity checks;
  • reported limitations and unexpected outcomes.

Chapter Summary

Quantum programming transforms quantum algorithms into executable circuits. A complete workflow includes circuit construction, measurement, simulation, transpilation, backend execution, visualization, and quantitative evaluation. Qiskit provides representative tools for each stage, but interfaces and provider services must be checked against the installed release.

Ideal simulation establishes a reference, while shot-based results estimate probabilities with sampling uncertainty. Transpilation adapts logical circuits to basis gates and hardware connectivity, potentially introducing routing overhead. Hardware experiments require authentication, backend selection, job tracking, and careful metadata. Counts should be analysed using defined measures such as empirical frequencies, expectation values, correlation, total variation distance, or appropriately defined fidelity. Reproducibility depends on version control, seeds, circuit records, raw data, backend information, and transparent reporting.

Key Terms

Quantum SDK: Software toolkit for constructing, compiling, executing, and analysing quantum programs.

Quantum circuit: Ordered collection of quantum operations and measurements.

Backend: Execution target, such as a simulator or quantum processor.

Shot: One repetition of a circuit execution used to obtain a sampled outcome.

Statevector: Vector of complex amplitudes describing an ideal pure quantum state.

Measurement: Operation that converts quantum information into classical outcomes.

Transpilation: Compilation of a circuit into a backend-compatible form.

Basis gate: Primitive gate supported by a target backend.

Qubit mapping: Assignment of logical qubits to physical hardware qubits.

Routing: Insertion of operations, often SWAP gates, to satisfy connectivity constraints.

Circuit depth: Longest sequence of dependent operations in a circuit.

Readout error: Error occurring when a measured quantum state is recorded as a classical bit.

Noise model: Mathematical or computational representation of physical imperfections.

Empirical frequency: Observed count divided by the total number of shots.

Expectation value: Probability-weighted average of observable outcomes.

Total variation distance: A measure of disagreement between two probability distributions.

Correlation: Statistical relationship between measurement outcomes, such as same-bit Bell correlation.

Reproducibility: Ability to repeat an analysis using preserved code, data, settings, and metadata.

Primitive: Higher-level execution interface that returns samples or expectation-related results.

Error mitigation: Methods intended to reduce the effect of errors in estimated results without fully correcting the computation.

Review Questions

Short Answer Questions

  1. What is the purpose of transpilation in a quantum software workflow?
  2. Distinguish an ideal simulator from a noisy simulator.
  3. Why must the number of shots be reported with measurement counts?
  4. What information should be recorded for a cloud hardware job?
  5. Why can a Bell circuit produce outcomes other than 00 and 11 on real hardware?

Long Answer Questions

  1. Explain the complete workflow from circuit design to experimental evaluation.
  2. Describe how hardware connectivity influences the transpiled form and reliability of a circuit.
  3. Explain the difference between sampling uncertainty and device noise.
  4. Discuss why circuit visualization and raw-data preservation are important for reproducibility.
  5. Compare simulation-based validation with hardware-based validation, including their respective limitations.

Analytical / Application Questions

  1. An experiment with 2,000 shots obtains 00 = 920, 11 = 860, 01 = 120, and 10 = 100. Calculate the same-bit correlation C and interpret its sign and magnitude.
  2. An ideal distribution assigns probability 0.5 to 00 and 11, while an experiment reports 0.46, 0.44, 0.06, and 0.04 for 00, 11, 01, and 10. Calculate the total variation distance and explain what it indicates.
  3. A hardware result is worse than an ideal simulation, but a zero-state control also has many incorrect readouts. Propose an investigation that separates readout error from entangling-gate error.

Multiple Choice Questions with Answers

Question 1

What is the primary purpose of a quantum SDK?

A. To replace all classical computers

B. To construct, compile, execute, and analyse quantum programs

C. To manufacture superconducting processors

D. To guarantee error-free hardware results

Correct Answer: B. To construct, compile, execute, and analyse quantum programs

Question 2

In a shot-based experiment, what does kₓ/N represent?

A. The circuit depth

B. The number of qubits

C. The empirical frequency of outcome x

D. The hardware fidelity

Correct Answer: C. The empirical frequency of outcome x

Question 3

Which operation commonly creates entanglement in the Bell-state example after a Hadamard gate?

A. A controlled-NOT gate

B. A barrier

C. A measurement on one classical bit

D. A transpiler seed

Correct Answer: A. A controlled-NOT gate

Question 4

Why might a transpiler insert SWAP gates?

A. To increase the number of measurement shots

B. To satisfy physical connectivity constraints

C. To convert counts into probabilities

D. To remove all noise from a circuit

Correct Answer: B. To satisfy physical connectivity constraints

Question 5

For p = 0.5 and N = 1,024, what is the standard deviation of the empirical frequency under independent sampling?

A. 0.0015625

B. 0.015625

C. 0.15625

D. 1.5625

Correct Answer: B. 0.015625

Question 6

What does a shot represent?

A. One repetition of a circuit execution

B. One physical qubit

C. One transpiler optimization level

D. One basis gate

Correct Answer: A. One repetition of a circuit execution

Question 7

Which quantity compares two normalized probability distributions using ½∑ₓ|p(x) − q(x)|?

A. Circuit depth

B. Total variation distance

C. Statevector dimension

D. Gate fidelity

Correct Answer: B. Total variation distance

Question 8

For the Bell-circuit correlation formula C = (n₀₀ + n₁₁ − n₀₁ − n₁₀)/N, what does C = 1 indicate?

A. Perfect same-bit correlation

B. Perfect anti-correlation

C. No measurements were performed

D. The circuit has zero qubits

Correct Answer: A. Perfect same-bit correlation

Question 9

Which item is most important for identifying a cloud execution unambiguously?

A. The plot colour

B. The job identifier

C. The screen size

D. The programming font

Correct Answer: B. The job identifier

Question 10

What is a key limitation of a general statevector simulator?

A. It cannot represent a one-qubit state

B. Its memory requirement generally grows exponentially with qubit count

C. It cannot apply Hadamard gates

D. It always includes hardware noise

Correct Answer: B. Its memory requirement generally grows exponentially with qubit count

Introduction to Quantum Computing
Chapter 12 of 14