Chapter 4
Quantum Programming and Hybrid Workflows
Diploma in Quantum Computing
Applications of Quantum Computing
•
Diploma
Quantum Programming and Hybrid Workflows
Introduction
Quantum computing becomes useful only when abstract quantum principles are connected to software, data, hardware, and classical decision-making. A quantum program is therefore not merely a list of gates. It is usually a workflow in which a classical computer prepares inputs, constructs and submits a quantum circuit, receives measurement results, processes those results, and possibly updates the circuit before repeating the experiment.
This chapter introduces the practical foundations needed to construct basic circuits, use simulators and cloud platforms, implement variational algorithms such as the Variational Quantum Eigensolver (VQE) and Quantum Approximate Optimization Algorithm (QAOA), and connect quantum processors with classical software, data pipelines, and artificial-intelligence workflows.
Learning Objectives
By the end of this chapter, you should be able to:
distinguish state preparation, circuit execution, measurement, and classical post-processing;
construct and interpret small quantum circuits;
explain the roles of simulators, emulators, and cloud quantum platforms;
describe the workflow and objective function of VQE and QAOA;
identify the effects of noise, finite sampling, and parameter optimization;
design a basic hybrid quantum–classical workflow;
evaluate practical, security, reproducibility, and governance issues in quantum applications.
1. The Quantum Program as a Hybrid Process
A classical program manipulates explicitly stored values. A quantum program manipulates a quantum state through unitary operations and measurements. For a system of n qubits, the ideal state is represented by a vector in a 2ⁿ-dimensional complex state space:
|ψ⟩ = ∑x=02n−1 αx |x⟩
Here, |x⟩ denotes a computational-basis state, αₓ is its complex amplitude, and the normalization condition is:
∑x=02n−1 |αx|² = 1
The probability of observing basis state |x⟩ is |αₓ|². This description applies to an ideal pure state before measurement. Measurement converts quantum information into classical data and generally changes the state. Consequently, a quantum algorithm normally consists of repeated circuit executions, called shots, rather than one execution that reveals the complete state.
A typical workflow has six stages:
Problem formulation: Express a business, scientific, or engineering problem in a form suitable for a quantum algorithm.
Encoding: Map variables or data to qubits.
Circuit construction: Prepare a state and apply gates.
Execution: Run the circuit on a simulator or quantum processor.
Measurement and estimation: Convert counts into probabilities, expectation values, or objective estimates.
Classical control: Optimise parameters, interpret results, and decide whether another quantum execution is required.
The quantum processor is therefore often a specialised component inside a larger classical software system.
2. Programming Models and Circuit Construction
2.1 Gates, registers, and measurements
A qubit can be initialised in |0⟩. Common single-qubit gates include the Pauli gates X, Y, and Z, the Hadamard gate H, and rotation gates such as Rₓ(θ), Rᵧ(θ), and R_z(θ). The X gate changes |0⟩ to |1⟩, while H creates superposition:
H|0⟩ = (|0⟩ + |1⟩)/√2
The two-qubit controlled-NOT (CNOT) applies X to a target qubit when the control qubit is |1⟩. Applying H to one qubit followed by CNOT can create an entangled Bell state:
|Φ⁺⟩ = (|00⟩ + |11⟩)/√2
Measuring both qubits in the computational basis gives 00 or 11, ideally with probability 1/2 each. The outcomes are correlated even though each individual outcome is unpredictable.
A circuit description must specify qubit order, gate order, measurement basis, and classical-bit mapping. These details matter because software libraries use different conventions for displaying bit strings and indexing qubits.
2.2 A minimal circuit example
Consider a circuit with two qubits:
initialise q₀ and q₁ in |00⟩;
apply H to q₀;
apply CNOT with q₀ as control and q₁ as target;
measure both qubits.
The ideal output distribution is P(00) = 0.5 and P(11) = 0.5. With N independent shots, the expected number of 00 outcomes is N/2, although the observed count fluctuates. If k observations are 00, the empirical probability is:
p̂(00) = k/N
The estimate becomes more stable as N increases. Finite-shot variation is not necessarily hardware failure; it is a statistical feature of measurement.
2.3 Circuit depth and compilation
A hardware device usually supports only a limited gate set and a particular connectivity graph. A compiler therefore transforms a logical circuit into native operations, maps logical qubits to physical qubits, and may insert SWAP operations. This can increase circuit depth and expose the computation to more noise.
Important engineering measures include:
qubit count: number of logical or physical qubits;
gate count: total operations;
depth: length of the longest sequential path;
two-qubit-gate count: often strongly associated with error accumulation;
measurement count: number of measured qubits and repetitions;
transpilation overhead: additional operations introduced for hardware compatibility.
A circuit with fewer qubits is not automatically better. An application must balance representation quality, depth, sampling cost, and hardware noise.
3. Simulators, Emulators, and Cloud Platforms
3.1 Simulation methods
A state-vector simulator stores the full ideal amplitude vector. Its memory requirement grows exponentially with qubit count: n qubits require 2ⁿ complex amplitudes. This makes state-vector simulation excellent for small circuits and algorithm development but unsuitable for arbitrarily large systems.
A shot-based simulator samples measurement outcomes from an ideal or noisy model. A density-matrix simulator represents mixed states and noise more explicitly, but usually requires greater computational resources. Tensor-network and stabilizer simulators can handle selected circuit families efficiently, although they do not efficiently represent every quantum computation.
3.2 Cloud execution
Cloud quantum platforms provide access to simulators and, in some cases, real quantum processing units (QPUs). A practical submission typically includes:
a circuit or executable quantum program;
target backend and supported instruction set;
number of shots;
authentication and project information;
optional error-mitigation or measurement-calibration settings.
The returned object may contain counts, expectation values, metadata, queue information, timing, and execution status. Professional software should record the backend name, software versions, circuit hash, shot count, random seeds where applicable, and calibration information.
Environment
Strength
Main limitation
Ideal simulator
Fast conceptual testing and debugging
Omits hardware imperfections
Noisy simulator
Controlled experiments with specified errors
Noise model may not match the device
Cloud QPU
Real hardware behaviour
Queue time, cost, noise, and changing calibration
Local emulation
Reproducible development
Limited scale and hardware realism
3.3 A disciplined development cycle
A sound process is:
test the circuit on paper for one or two qubits;
run an ideal simulator;
run a noisy simulator with documented assumptions;
transpile for the intended hardware;
execute a small number of validation jobs;
compare distributions or expectation values;
increase shots only when the result justifies the additional cost.
This sequence separates logical errors from compilation errors, statistical variation, and hardware noise.
4. Expectation Values and Variational Algorithms
Many useful quantum algorithms do not seek a complete bit string directly. Instead, they estimate an expectation value. For an observable O and state |ψ(θ)⟩, the expectation is:
⟨O⟩_θ = ⟨ψ(θ)|O|ψ(θ)⟩
The symbol θ denotes a vector of adjustable circuit parameters. If O is decomposed into measurable Pauli terms,
O = ∑ᵢ cᵢ Pᵢ
where cᵢ are real coefficients and Pᵢ are Pauli strings, then:
⟨O⟩_θ = ∑ᵢ cᵢ ⟨Pᵢ⟩_θ
This decomposition assumes that each term can be measured using an appropriate basis transformation and that the coefficients and observable definition are known. Terms may sometimes be grouped to reduce the number of circuit executions.
For a measurement outcome represented by a random variable X with variance Var(X), the standard error of the sample mean from N independent shots is approximately:
SE(X̄) = √(Var(X)/N)
For a Pauli measurement with outcomes ±1, Var(X) = 1 − ⟨P⟩². Thus, increasing shots reduces sampling error approximately in proportion to 1/√N, not 1/N.
4.1 Variational Quantum Eigensolver
VQE estimates the minimum eigenvalue of a Hamiltonian H. In quantum chemistry, H may represent the energy operator of a molecule after mapping fermionic modes to qubits. The variational principle states that for any normalized trial state |ψ(θ)⟩,
E(θ) = ⟨ψ(θ)|H|ψ(θ)⟩ ≥ E₀
where E₀ is the ground-state energy. The algorithm seeks parameters θ* that minimise E(θ):
θ* = arg min_θ E(θ)
The inequality assumes H is Hermitian and |ψ(θ)⟩ is normalized. It is a bound on the ground-state energy, not a guarantee that a finite-depth ansatz can reach the exact ground state.
The VQE loop is:
choose an ansatz circuit |ψ(θ)⟩;
prepare and measure the required Pauli terms;
combine estimates to obtain E(θ);
send E(θ) to a classical optimizer;
receive new parameters;
repeat until a stopping criterion is met.
Common stopping criteria include a small change in energy, a small parameter change, a maximum number of iterations, or a computational budget. A useful ansatz should express relevant physics without creating excessive depth.
4.2 QAOA
QAOA addresses combinatorial optimisation by alternating a cost Hamiltonian H_C and a mixer Hamiltonian H_M. Starting from an initial state |s⟩, a depth-p state can be written as:
|γ,β⟩ = ∏ₗ₌₁ᵖ e^(−iβₗHM)e^(−iγₗHC)|s⟩
Here γₗ and βₗ are classical parameters and ℏ is taken as 1 in the conventional expression. The objective is to minimise or maximise the expected cost, depending on the problem encoding. The order of operators is important: the rightmost operation acts first.
For a maximisation problem, one may maximise:
F(γ,β) = ⟨γ,β|HC|γ,β⟩
The computational-basis samples can also be ranked by their classical objective value. QAOA does not automatically guarantee the optimal bit string; performance depends on the encoding, depth, optimiser, initial parameters, sampling, and hardware noise.
4.3 Comparing VQE and QAOA
Feature
VQE
QAOA
Typical target
Ground-state energy
Combinatorial objective
Core operator
Problem Hamiltonian
Cost and mixer Hamiltonians
Output
Energy estimate and state samples
Candidate bit strings and objective values
Classical task
Minimise energy
Optimise alternating-circuit parameters
Main design issue
Ansatz and measurement cost
Encoding, mixer, and circuit depth
5. Classical Optimisation and Workflow Engineering
The classical optimiser receives noisy objective evaluations. Gradient-free methods, such as COBYLA or Nelder–Mead, can be useful when gradients are unavailable or unreliable. Gradient-based methods can be efficient when parameter-shift or other gradient estimates are affordable. No single optimiser is universally best.
A parameter-shift estimate for a suitable rotation parameter θ has the form:
∂f/∂θ = [f(θ + π/2) − f(θ − π/2)]/2
This relation applies to gates and generators satisfying the required two-eigenvalue condition, commonly used for standard single-parameter Pauli rotations. It requires two additional objective evaluations per parameter and is itself affected by shot noise.
A professional hybrid workflow should separate:
data preparation: validation, scaling, feature selection, and encoding;
circuit generation: parameter binding and measurement-basis selection;
execution service: simulator or QPU submission;
result normalisation: conversion of counts into estimates;
optimisation service: parameter updates and stopping logic;
experiment tracking: metadata, costs, versions, and reproducibility;
classical post-processing: ranking, prediction, or business action.
Hybrid quantum classical workflow
Figure: Hybrid quantum classical workflow
Figure: A hybrid workflow in which classical software controls repeated quantum executions.
6. Data Pipelines and Artificial Intelligence
Quantum circuits can be integrated into conventional data pipelines, but the integration does not remove the need for data engineering. A pipeline may extract records from a database, validate them, transform features, encode a small selected subset into quantum states, execute a circuit, and store the resulting features or predictions.
Data encoding is often the dominant practical constraint. Amplitude encoding can represent 2ⁿ values using n qubits in principle, but state preparation may be costly. Angle encoding uses rotations whose angles represent features and is usually simpler, though it may require many qubits or repeated layers. Basis encoding maps binary or categorical information to computational-basis states. Encoding choice must be judged by preparation cost, noise sensitivity, interpretability, and the size of the available dataset.
In quantum machine-learning experiments, a quantum circuit may act as:
a feature map followed by a classical classifier;
a trainable layer in a hybrid neural network;
a kernel evaluator;
a generative model component;
a feature extractor for a downstream classical model.
Claims of quantum advantage require rigorous comparison with strong classical baselines. A small quantum model that performs well on a toy dataset does not establish superiority for production-scale AI. Data leakage, inappropriate train–test splitting, repeated hyperparameter search, and unreported simulator assumptions can produce misleading results.
This is a fictional illustrative case. A university laboratory operates three instruments and must schedule six experiments. Each experiment has a duration, a deadline, and a compatibility constraint. The laboratory wants to reduce late completion while avoiding simultaneous use of an instrument.
Background and problem
The scheduling problem can be represented with binary variables xᵢ, where xᵢ = 1 indicates selection of a candidate schedule and xᵢ = 0 indicates rejection. Constraints and penalties are combined into a quadratic objective. The resulting binary quadratic model can be mapped to an Ising or QUBO cost Hamiltonian for QAOA.
Analysis
The team first builds a classical integer-programming baseline. It then limits the quantum experiment to a reduced instance with six binary decision variables, because the available device has limited connectivity and noise. Penalty coefficients are chosen large enough to discourage constraint violations, but not so large that the objective becomes numerically ill-conditioned.
Approach
Generate feasible and near-feasible candidate schedules classically.
Construct the QUBO objective and verify its values by exhaustive enumeration.
Map binary variables to qubits.
Use a mixer that preserves the relevant constraints where possible.
Run shallow QAOA circuits on an ideal simulator, noisy simulator, and cloud QPU.
Decode samples and evaluate every schedule using the original scheduling rules.
Compare the best feasible quantum sample with the classical baseline.
Outcome
The quantum experiment produces feasible candidate schedules but does not outperform the classical solver on the reduced instance. It is nevertheless useful as an integration exercise: the team validates encoding, cloud submission, result tracking, and feasibility checking. The experiment also reveals that measurement noise and transpilation increase the frequency of infeasible samples.
Learning points
The case demonstrates that a meaningful quantum project requires problem reduction, an independently verified classical baseline, explicit feasibility checks, and realistic accounting for execution cost. A quantum result should be judged by solution quality, runtime, sampling cost, reproducibility, and operational usefulness—not by the existence of a circuit alone.
8. Noise, Validation, and Reproducibility
Real devices experience gate errors, readout errors, decoherence, crosstalk, leakage, and calibration drift. A short circuit may still produce biased estimates. Error mitigation techniques, such as measurement calibration, zero-noise extrapolation, and symmetry verification, can sometimes improve estimates, but they add sampling and modelling overhead and do not equal full error correction.
Validation should include:
unit tests for circuit construction and qubit ordering;
exact results for small instances where classical enumeration is possible;
distributional comparison using repeated runs;
sensitivity analysis for shots, noise, and initial parameters;
comparison with classical heuristics and optimisers;
recording of all software, hardware, and calibration metadata.
Reproducibility is more difficult on cloud QPUs because device calibration changes. A complete experiment record should include the problem instance, encoding, circuit source, transpiled circuit, backend, date, shots, random seeds, optimiser settings, stopping criteria, and raw results.
9. Professional, Ethical, and Governance Considerations
Quantum cloud services may process sensitive data outside an organisation’s physical boundary. Designers must examine confidentiality, data-retention policies, authentication, access control, encryption, and contractual obligations. Sensitive raw data should generally be minimised or transformed before transmission, but transformation must not make the computation invalid.
Responsible evaluation also requires:
honest reporting of negative or inconclusive results;
clear distinction between experimental evidence and marketing claims;
fairness testing when quantum components affect people;
traceability of data, model versions, and decisions;
human oversight for high-impact applications;
awareness that quantum computing does not automatically improve privacy or security.
Quantum software can also depend on third-party libraries and cloud APIs. Licence compliance, dependency management, vulnerability scanning, and supplier continuity are part of professional practice.
10. Contemporary Developments and Best Practices
Current development is moving toward error mitigation, modular quantum systems, better compilation, dynamic circuits, resource estimation, and integration with classical accelerators. Fault-tolerant quantum computing remains a long-term engineering objective, while present-day noisy devices are mainly valuable for research, education, prototyping, and carefully bounded experiments.
Best practices for diploma-level projects include:
formulate a small, measurable problem;
establish a classical baseline before building the quantum solution;
verify encodings by exhaustive testing on small instances;
use the simplest circuit that expresses the intended computation;
track qubit order, units, shots, and backend metadata;
separate logical, statistical, and hardware errors;
budget cloud time and repeated measurements;
report limitations and unsuccessful trials;
protect sensitive data and credentials;
evaluate operational value rather than circuit novelty.
Chapter Summary
Quantum programming is best understood as a hybrid process joining classical software and quantum circuits. Circuits prepare states, apply gates, and measure outcomes; classical code prepares data, estimates objectives, optimises parameters, and interprets results. Simulators support debugging and controlled experiments, while cloud QPUs expose programs to real noise, compilation constraints, queueing, and calibration drift.
Expectation values are central to variational algorithms. VQE minimises the energy of a parameterised trial state under the variational principle. QAOA alternates cost and mixer operations to search for good solutions to encoded combinatorial problems. Both require careful ansatz or encoding design, classical optimisation, repeated sampling, and validation against classical baselines.
Successful professional workflows document circuits, data, parameters, backends, shots, and results. They also address noise, reproducibility, privacy, security, fairness, and realistic claims about quantum advantage.
Key Terms
Qubit: The basic unit of quantum information.
Quantum circuit: An ordered sequence of quantum gates, measurements, and often classical operations.
Amplitude: A complex number whose squared magnitude gives a measurement probability.
Superposition: A quantum state formed from a linear combination of basis states.
Entanglement: Nonclassical correlation between quantum systems.
Shot: One repeated execution of a circuit followed by measurement.
Observable: A measurable Hermitian operator.
Expectation value: The statistical mean associated with an observable and quantum state.
Hamiltonian: An operator representing energy or a problem objective.
Ansatz: A parameterised family of trial quantum states.
VQE: A hybrid algorithm for estimating a Hamiltonian’s ground-state energy.
QAOA: A variational algorithm using alternating cost and mixer operations.
Transpilation: Compilation of a logical circuit into hardware-compatible operations.
Circuit depth: The maximum number of sequential gate layers.
Noise model: A mathematical description of imperfections affecting execution.
Error mitigation: Techniques intended to reduce the influence of errors without full error correction.
Parameter-shift rule: A method for estimating certain circuit derivatives using shifted evaluations.
Hybrid workflow: A process in which classical and quantum computations repeatedly interact.
Quantum processing unit: Hardware that executes quantum circuits.
Review Questions
5 Short Answer Questions
Why are quantum circuits commonly executed for many shots rather than once?
What is the role of a transpiler?
State the variational principle used by VQE.
What are the two types of operators alternated in QAOA?
Give two items that should be recorded for reproducible cloud execution.
5 Long Answer Questions
Explain the stages of a hybrid quantum–classical workflow and the responsibilities of each stage.
Compare state-vector simulation, noisy simulation, and execution on a cloud QPU.
Describe VQE, including state preparation, measurement, classical optimisation, and stopping criteria.
Explain how data encoding choices affect quantum machine-learning workflows.
Discuss why a classical baseline is necessary when evaluating a proposed quantum application.
3 Analytical / Application Questions
Design a validation plan for a two-qubit circuit whose measured distribution differs from its ideal simulation. Identify tests that distinguish logical, statistical, compilation, and hardware causes.
A scheduling problem produces many infeasible QAOA samples. Analyse at least three possible causes and propose corresponding improvements.
Propose an architecture for integrating a variational quantum circuit into a classical data pipeline. Include data protection, experiment tracking, cost control, and model evaluation.
Multiple Choice Questions with Answers
Question 1
For a normalized n-qubit state, what does |αₓ|² represent?
A. The probability of measuring basis state |x⟩
B. The number of gates in the circuit
C. The circuit depth
D. The number of qubits
Correct Answer: A. The probability of measuring basis state |x⟩
Question 2
What is the ideal output distribution of a Bell-state circuit producing (|00⟩ + |11⟩)/√2?
A. 00 and 01 only
B. 01 and 10 only
C. 00 and 11, each with probability 1/2
D. All four outcomes with probability 1/4
Correct Answer: C. 00 and 11, each with probability 1/2
Question 3
Why are multiple shots used in a quantum experiment?
A. To increase the number of qubits
B. To estimate probabilities and expectation values statistically
C. To eliminate the need for measurement
D. To guarantee the optimal circuit parameters
Correct Answer: B. To estimate probabilities and expectation values statistically
Question 4
What is the principal objective of VQE?
A. Maximise circuit depth
B. Find the minimum eigenvalue of a Hamiltonian
C. Remove all classical computation
D. Encode every classical datum into one qubit
Correct Answer: B. Find the minimum eigenvalue of a Hamiltonian
Question 5
In QAOA, which operations are alternated?
A. Readout and reset operations
B. Cost and mixer operations
C. Fourier and sorting operations
D. Training and validation operations
Correct Answer: B. Cost and mixer operations
Question 6
If a Pauli measurement has expectation value 0 and uses 100 shots, its approximate standard error is what?
A. 0
B. 0.01
C. 0.1
D. 10
Correct Answer: C. 0.1
Question 7
What is a major purpose of transpilation?
A. Converting a logical circuit into hardware-compatible operations
B. Increasing the number of input records
C. Proving that a quantum algorithm is optimal
D. Replacing all measurements with classical guesses
Correct Answer: A. Converting a logical circuit into hardware-compatible operations
Question 8
Which practice most directly supports reproducibility on a cloud QPU?
A. Recording only the final answer
B. Changing the backend after every shot
C. Recording the backend, circuit, shots, parameters, and software versions
D. Avoiding classical baselines
Correct Answer: C. Recording the backend, circuit, shots, parameters, and software versions
Question 9
Why is data encoding important in quantum machine learning?
A. It determines how classical information is represented by quantum states
B. It guarantees quantum advantage
C. It removes the need for training data
D. It prevents all hardware noise
Correct Answer: A. It determines how classical information is represented by quantum states
Question 10
What is the purpose of a classical baseline in a quantum application study?
A. To ensure that quantum hardware is always used
B. To provide a meaningful comparison for quality and cost
C. To increase circuit depth
D. To avoid validating the encoding
Correct Answer: B. To provide a meaningful comparison for quality and cost