Simulation, Programming and Experimental AnalyticsIntroductionQuantum computing becomes an engineering discipline when abstract states and operators are represented in software, compiled into circuits, executed by simulators or quantum processors, and interpreted through data. A programmer must therefore understand more than gate notation. The practical workflow includes state preparation, circuit construction, backend selection, measurement, statistical analysis, visualization, and diagnosis of discrepancies between ideal theory and experiment. A quantum program is not normally a single deterministic calculation. A circuit prepares a quantum state, applies transformations, and produces classical samples when measured. Repeating the circuit produces a distribution of outcomes. The central analytical task is to determine whether observed differences from theoretical probabilities arise from finite sampling or from hardware imperfections such as gate errors, readout errors, decoherence, and unwanted coupling. This chapter uses Python-style pseudocode and concepts common to software development kits such as Qiskit, Cirq, and equivalent platforms. API names change across versions; the underlying principles remain stable. Learning objectivesBy the end of this chapter, you should be able to: - represent single- and multi-qubit states with state vectors and probability distributions;
- construct, simulate, measure, and visualize small quantum circuits;
- distinguish state-vector simulation from shot-based simulation;
- execute a small experiment on a real or cloud-accessible quantum processor;
- calculate empirical probabilities and sampling uncertainty;
- identify signatures of sampling variation and hardware noise;
- document reproducible quantum experiments responsibly.
1. Quantum states as computational objectsFor one qubit, the computational basis states are |0⟩ and |1⟩. A pure state is |ψ⟩ = α|0⟩ + β|1⟩ where α and β are generally complex amplitudes satisfying |α|² + |β|² = 1 The squared magnitudes are probabilities in a computational-basis measurement: P(0) = |α|² and P(1) = |β|². Amplitudes themselves are not probabilities; their phases affect interference. For n qubits, the state vector has 2n complex amplitudes: |ψ⟩ = ∑x=02n−1 ax|x⟩, ∑x |ax|² = 1 Here x labels a computational-basis bit string and ax is its amplitude. State-vector simulation stores these amplitudes explicitly, so memory grows exponentially. A rough lower-bound storage requirement using double-precision complex numbers is 16×2n bytes, ignoring software overhead. Consequently, state-vector simulation is excellent for small circuits but becomes impractical as n grows. A measurement does not reveal the complete state vector. It samples an outcome. If the probability of outcome x is px = |ax|², then a run returns one bit string according to the distribution {px}. State representations used in software| Representation | Meaning | Typical use |
|---|
| State vector | Complex amplitudes for a pure state | Ideal analysis, debugging | | Probability distribution | Non-negative outcome probabilities summing to one | Prediction and visualization | | Counts | Integer frequency for each observed bit string | Experimental results | | Density matrix | Operator describing pure or mixed states | Noise and open-system simulation |
A density matrix ρ satisfies ρ = ρ†, Tr(ρ)=1, and is positive semidefinite. For a pure state, ρ = |ψ⟩⟨ψ|. Density matrices are more expensive than state vectors but can represent classical uncertainty and environmental noise. 2. From circuit description to executable programA practical quantum program has several layers: - Specification: state the experiment, expected distribution, and success metric.
- Circuit: arrange qubit initialisation, gates, barriers if useful, and measurements.
- Compilation: map logical qubits and gates to the target device’s supported operations and connectivity.
- Execution: run either an ideal simulator, a noisy simulator, or real hardware.
- Data analysis: convert counts to probabilities, calculate uncertainty, and compare with a model.
- Reporting: record software versions, backend, shots, circuit, calibration context, and random seeds where relevant.
A circuit can be represented as a directed acyclic graph. Qubit wires carry quantum information, while classical wires carry measurement results. A measurement terminates the quantum use of a qubit in the ordinary circuit model: after measurement, the result can be stored, processed, or used for classical control. A basic programming patternThe following pseudocode is intentionally SDK-neutral: circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
compiled = compile(circuit, backend)
result = run(compiled, shots=2000)
counts = result.counts()
plot_histogram(counts) The Hadamard gate creates a superposition on qubit 0, and the controlled-NOT correlates qubit 1 with it. Ideally, measurement produces only 00 and 11, each with probability one-half. The actual printed bit order is SDK-dependent, so programmers must check whether the leftmost displayed bit corresponds to the highest-index qubit. Never infer bit order from a graph without consulting the tool’s convention. Gates and matrix verificationA gate is a unitary transformation U satisfying U†U = I where U† is the conjugate transpose and I is the identity matrix. If |ψ⟩ is the input state, the output is U|ψ⟩. For a circuit containing gates U1, U2, …, Uk, the total transformation is their matrix product in execution order, with the rightmost operation acting first under the usual column-vector convention. For two qubits, a controlled-NOT maps |a,b⟩ → |a,b⊕a⟩, where ⊕ denotes XOR. Such definitions are useful for checking a circuit independently of a library. 3. Simulation modesIdeal state-vector simulationAn ideal state-vector simulator applies exact or floating-point unitary operations and can return amplitudes or probabilities. It answers: “What would this circuit do under the mathematical model, without noise?” It is valuable for debugging gate order, basis conventions, and expected output. Shot-based ideal simulationEven when the state is calculated exactly, measurements can be sampled. If a circuit predicts P(0)=0.7, a 100-shot simulation will not usually return exactly 70 zeros. Shot-based simulation reproduces the statistical form of an experiment without hardware imperfections. For N independent shots and an outcome with probability p, the count K follows a binomial distribution for a binary event: K ~ Binomial(N,p) The empirical probability is p̂ = K/N. Its standard deviation is σp̂ = √[p(1−p)/N] This formula assumes independent identically distributed shots and a fixed probability p. In practice, p is unknown, so p̂ is often substituted for planning or approximate error bars. The largest standard deviation occurs near p=0.5, where σp̂ ≤ 1/(2√N). Noisy simulationA noisy simulator inserts a model of errors. Common models include: - depolarising errors after gates;
- bit-flip or phase-flip errors;
- amplitude damping, representing energy relaxation;
- phase damping, representing loss of phase coherence;
- measurement assignment errors;
- correlated or crosstalk errors.
A noise model is not automatically a faithful model of a particular device. It is a hypothesis whose predictions should be compared with calibration data and experiments. Hardware executionA real processor introduces effects not fully captured by an ideal circuit. Logical gates must be decomposed into native gates, qubits must satisfy coupling constraints, and scheduling determines exposure to relaxation and dephasing. Compilation may add SWAP gates, increasing circuit depth and error opportunity. 4. Measurement data and visualisationSuppose 1,000 shots of a circuit produce the counts shown below. | Outcome | Count | Empirical probability |
|---|
| 00 | 482 | 0.482 | | 01 | 19 | 0.019 | | 10 | 22 | 0.022 | | 11 | 477 | 0.477 | | Total | 1,000 | 1.000 |
A histogram communicates the empirical distribution, but it should not be mistaken for the underlying probability distribution. Counts are random observations. A useful visualization normally includes the full relevant outcome space, including zero-count outcomes, and clearly identifies the number of shots. For an expected distribution {px} and observed counts [[MATH{k_x}]], the empirical distribution is p̂x=kx/N. A simple goodness-of-fit measure is the total variation distance: DTV(p̂,p) = ½∑x |p̂x − px| It ranges from 0 for identical distributions to 1 for maximally disjoint distributions. It is descriptive rather than a complete statistical test. When expected counts are sufficiently large, a Pearson statistic may be used: χ² = ∑x (kx − Npx)²/(Npx) The approximation requires care: expected counts should not be too small, outcomes should be independent, and the model should be specified before inspecting the data. Combining rare categories may be preferable. Confidence intervalsFor a binary outcome, a quick approximate 95% interval is p̂ ± 1.96√[p̂(1−p̂)/N] This normal approximation can perform poorly for small N or probabilities near 0 or 1. Wilson or exact binomial intervals are preferable in software intended for reliable reporting. An interval quantifies sampling uncertainty; it does not include systematic hardware error unless the experimental model explicitly does so. 5. Distinguishing sampling variation from noiseThis distinction is central to experimental analytics. Sampling variation occurs because a finite number of shots is collected from a fixed distribution. It decreases approximately as 1/√N. Running four times as many shots reduces the standard error by about one-half. Noise changes the distribution itself. It may produce forbidden outcomes, bias one outcome toward another, reduce interference visibility, or make results depend on qubit choice, gate sequence, time, and calibration. The following diagnostic procedure is effective: - Calculate the ideal distribution from the circuit or an ideal simulator.
- Run an ideal shot-based simulation using the same shot count.
- Compare hardware results with the ideal shot distribution.
- Repeat with larger shot counts. Sampling fluctuations should shrink; persistent bias will not.
- Run calibration circuits such as preparation-and-measurement tests, identity circuits, and randomized or repeated-gate circuits.
- Compare multiple qubits, compilation layouts, and execution times.
- Use a noisy simulation only after documenting its assumptions.
A single non-ideal histogram cannot identify the physical cause. For example, an unexpected 01 result in an entanglement experiment might arise from sampling? In an ideal Bell experiment, 01 has probability zero, so any occurrence indicates either hardware noise, simulator noise, state-preparation error, measurement error, or a circuit/bit-ordering mistake. The histogram alone cannot distinguish them. Correlation and parity metricsFor a two-qubit Bell experiment, the same-bit probability is Psame = P(00)+P(11) and the parity expectation, assigning +1 to equal bits and −1 to unequal bits, is ⟨Z⊗Z⟩ = P(00)+P(11)−P(01)−P(10) For the ideal state (|00⟩+|11⟩)/√2, ⟨Z⊗Z⟩=1. These metrics compress a distribution into a physically interpretable quantity, but compression can hide important errors; counts should still be retained. 6. Worked example: an ideal Bell-state experimentConsider the circuit: q0: ──H────■────M──
│
q1: ───────X────M──Starting from |00⟩, the Hadamard produces |00⟩ → (|00⟩+|10⟩)/√2 The controlled-NOT then produces (|00⟩+|11⟩)/√2 Therefore, ideal computational-basis probabilities are P(00)=0.5, P(11)=0.5, and zero for 01 and 10. Suppose 1,000 hardware shots give the table above. Then P̂same = (482+477)/1000 = 0.959 and ⟨Z⊗Z⟩ = (482+477−19−22)/1000 = 0.918 The ideal value of ⟨Z⊗Z⟩ is 1. The observed reduction is much larger than ordinary sampling variation expected around an ideal probability of one for the “same” event, suggesting errors or imperfect preparation and readout. However, further calibration experiments are needed before attributing the reduction to a particular gate or qubit. 7. Applied case: diagnosing a small cloud-hardware experimentThis is an illustrative case. A student team is asked to compare a two-qubit Bell circuit on an ideal simulator and a cloud-accessible processor. Background and problemThe team expects only 00 and 11. On hardware, their first 500-shot run gives 00: 226, 01: 34, 10: 29, and 11: 211. They initially conclude that the entanglement circuit “failed.” AnalysisThe same circuit is run on an ideal shot simulator with 500 shots. A typical result is close to 00: 250 and 11: 250, but finite sampling alone does not explain 63 opposite-bit outcomes in the hardware run. The team next checks whether the displayed bit strings are reversed. Reversal changes labels 01 and 10 but does not remove their total frequency, so bit order is not the main issue. They execute preparation-and-measurement calibration circuits. Preparing |0⟩ sometimes yields a reported 1, while preparing |1⟩ sometimes yields a reported 0. They also compare two qubit pairs. One pair has substantially more opposite-bit outcomes than the other, indicating device- and layout-dependent effects. Approach and solutionThe team records the backend name, calibration date, compiler mapping, native-gate circuit, shot count, and software version. They repeat the experiment at 500, 2,000, and 8,000 shots. The proportions remain near the original biased distribution, while the random scatter decreases. This pattern supports a systematic error contribution rather than sampling variation alone. They then compare a short circuit with a longer version containing additional gates. The longer circuit performs worse, consistent with accumulated gate and decoherence errors. A readout calibration is applied cautiously, and the corrected distribution moves closer to the ideal prediction. The team reports both raw and corrected results rather than presenting correction as a recovery of the exact unknown state. OutcomeThe final report concludes that the experiment successfully generated a correlated state, but hardware and readout errors reduced the observed correlation. It does not claim that every discrepancy was caused by one mechanism. The report includes uncertainty estimates, raw counts, calibration information, and limitations. Learning points- A simulator is a control experiment, not proof of hardware performance.
- Increasing shots diagnoses statistical precision but does not remove systematic bias.
- Compilation and qubit selection affect results.
- Raw data must be retained when mitigation is applied.
- Reproducibility requires circuit, backend, software, shot count, and timing information.
8. Best practices for quantum software experimentsValidate incrementallyBegin with basis-state preparation and measurement, then test single-qubit gates, two-qubit gates, and finally the complete algorithm. This isolates faults. Use assertions such as probability sums being approximately one and counts summing exactly to the requested number of shots. Separate logical and physical layersKeep the logical circuit distinct from compiled output. Save both. A logical circuit expresses intent; the compiled circuit determines what the hardware actually executes. Control randomness and preserve metadataSet a seed when a simulator supports reproducible sampling, but do not imply that a seed controls hardware randomness. Store counts, probabilities, circuit diagrams, backend identifiers, compiler options, timestamps, and calibration references. Use appropriate statisticsDo not attach error bars to a single deterministic simulator probability as if it were experimental data. Do attach sampling intervals to shot-based estimates. Avoid overinterpreting differences smaller than the relevant uncertainty, and avoid treating repeated shots as independent if the platform batches or correlates them in a way that violates the assumed model. Treat error mitigation cautiouslyReadout correction, zero-noise extrapolation, probabilistic error cancellation, and related methods can improve estimates under assumptions. They can also amplify statistical uncertainty, produce values outside physical probability ranges before post-processing, or fail when the noise model is inaccurate. Report the raw result, method, assumptions, and additional sampling cost. 9. Limitations, governance and contemporary practiceQuantum software stacks evolve rapidly. A circuit that runs under one SDK version may require changes under another. Reproducibility therefore means preserving an executable environment where possible, not merely naming a library. Cloud hardware introduces governance concerns: credentials must be protected, proprietary circuits should not be uploaded without authorization, and experiment data may be subject to institutional or commercial restrictions. Claims about quantum advantage require especially careful benchmarking against strong classical baselines, equivalent precision, and transparent resource accounting. A noisy small circuit is not evidence of practical superiority over classical computation. Artificial intelligence can assist with circuit optimization, parameter search, anomaly detection, and experiment scheduling. It should not replace physical validation. A learned model may reproduce historical calibration patterns while failing after a device update. Human review remains necessary for model assumptions, leakage, uncertainty, and scientific interpretation. Chapter SummaryQuantum software represents states through amplitudes, probabilities, counts, or density matrices. State-vector simulation tests ideal circuit logic, while shot-based simulation reveals the finite-sample character of measurement. Real hardware adds gate, readout, decoherence, connectivity, compilation, and calibration effects. Reliable experimental analytics compares ideal predictions, ideal shot simulations, noisy models, and hardware results. Sampling uncertainty decreases with the square root of the number of shots, whereas systematic noise changes the distribution and may persist as shots increase. Histograms, confidence intervals, total variation distance, parity expectations, and carefully chosen calibration circuits help diagnose performance. Professional practice requires incremental validation, explicit metadata, preservation of raw data, cautious error mitigation, and reproducible reporting. Key TermsState vector: Complex-amplitude representation of a pure quantum state. Amplitude: Complex coefficient whose squared magnitude determines measurement probability. Density matrix: Representation of pure or mixed quantum states, including noise and classical uncertainty. Shot: One execution of a circuit followed by the specified measurements. Counts: Integer frequencies of classical outcomes collected from shots. State-vector simulation: Ideal simulation that explicitly evolves complex amplitudes. Shot-based simulation: Sampling outcomes from a calculated probability distribution. Noisy simulation: Simulation incorporating a specified model of physical errors. Compilation: Transformation of a logical circuit into operations supported by a target backend. Native gate: Gate directly supported or efficiently implemented by a quantum device. Readout error: Incorrect classical assignment of a measured quantum state. Sampling variation: Random fluctuation caused by observing a finite number of shots. Sampling standard error: Estimated uncertainty of an empirical probability due to finite sampling. Total variation distance: Half the sum of absolute differences between two probability distributions. Parity expectation: Signed average indicating agreement or disagreement of measured bits. Calibration: Measurement or device information used to characterize hardware performance. Error mitigation: Procedure intended to reduce bias in estimates without fully correcting the physical process. Reproducibility: Ability to repeat an analysis using recorded circuits, settings, software, and data. Review QuestionsShort Answer Questions- Why are quantum amplitudes not themselves measurement probabilities?
- What is the principal difference between state-vector and shot-based simulation?
- Why does sampling uncertainty decrease approximately as 1/√N?
- Name two sources of error introduced by real quantum hardware.
- Why should raw counts be retained after error mitigation?
Long Answer Questions- Explain the complete workflow from logical circuit design to hardware result analysis.
- Compare state vectors, probability distributions, counts, and density matrices.
- Explain how compilation can change the performance of a logically unchanged circuit.
- Describe a method for distinguishing sampling variation from systematic noise.
- Discuss the advantages and limitations of readout-error mitigation.
Analytical / Application Questions- A binary outcome occurs 240 times in 400 shots. Calculate its empirical probability and approximate standard error using √[p̂(1−p̂)/N].
- An ideal Bell circuit predicts only 00 and 11, but hardware produces many 01 and 10 outcomes. Design three tests that would help distinguish readout error, gate error, and sampling variation.
- Design a reproducible software-and-hardware experiment comparing two qubit layouts. Specify the circuit, controls, shot counts, metrics, metadata, and criteria for interpreting the result.
Multiple Choice Questions with AnswersQuestion 1For a one-qubit state |ψ⟩ = α|0⟩ + β|1⟩, which condition is required for normalization? A. |α| + |β| = 1 B. |α|² + |β|² = 1 C. α + β = 1 D. αβ = 1 Correct Answer: B. |α|² + |β|² = 1 Question 2What does a shot represent in a quantum experiment? A. One complex amplitude in a state vector B. One compilation pass C. One circuit execution producing the specified classical measurement result D. One calibration parameter Correct Answer: C. One circuit execution producing the specified classical measurement result Question 3If an ideal binary outcome has probability 0.5, what happens approximately to its sampling standard error when the number of shots is increased from 100 to 400? A. It doubles B. It is unchanged C. It is reduced by half D. It becomes zero Correct Answer: C. It is reduced by half Question 4Which representation is most directly suited to modelling mixed states and environmental noise? A. A density matrix B. A circuit diagram only C. A count label D. A single classical bit Correct Answer: A. A density matrix Question 5An ideal Bell-state circuit predicts only 00 and 11. Persistent 01 and 10 outcomes on hardware most directly suggest what? A. Only finite sampling variation B. A possible hardware, preparation, readout, or circuit error C. That probabilities need not sum to one D. That the Hadamard gate is non-unitary Correct Answer: B. A possible hardware, preparation, readout, or circuit error Question 6What is the purpose of compilation? A. To convert measurement counts into amplitudes B. To map a logical circuit to operations and connectivity supported by a target backend C. To eliminate all hardware noise D. To guarantee equal outcome probabilities Correct Answer: B. To map a logical circuit to operations and connectivity supported by a target backend Question 7For counts 482, 19, 22, and 477 in 1,000 shots for 00, 01, 10, and 11 respectively, what is the empirical same-bit probability? A. 0.041 B. 0.477 C. 0.918 D. 0.959 Correct Answer: D. 0.959 Question 8Which observation most strongly indicates systematic noise rather than sampling variation? A. Different histograms from two small ideal simulations B. Reduced random scatter when shots are increased while the bias remains C. A count total equal to the requested shot count D. A probability distribution whose entries sum to one Correct Answer: B. Reduced random scatter when shots are increased while the bias remains Question 9What is the ideal value of ⟨Z⊗Z⟩ for the state (|00⟩+|11⟩)/√2? A. −1 B. 0 C. 1/2 D. 1 Correct Answer: D. 1 Question 10Which item is essential for reproducible reporting of a cloud-hardware experiment? A. Only the final histogram image B. Only the number of qubits on the device C. Circuit, backend, software settings, shot count, and raw results D. A claim that all errors were removed Correct Answer: C. Circuit, backend, software settings, shot count, and raw results
|