← Blog

How to Build, Transpile, and Validate a Bell-State Experiment with Qiskit

M
MindPlot Research
2026-07-27
Share
quantum-computingQiskitBell-statetranspilationPython

Table of contents

Scientific introduction

A Bell-state experiment is one of the smallest workflows that demonstrates a genuinely quantum relationship between two qubits. The circuit begins in the computational basis state |00〉, applies a Hadamard gate to the first qubit, and then applies a controlled-X gate from the first qubit to the second. In the ideal circuit model, these operations create the state (|00〉 + |11〉)/√2. Measurement does not reveal a fractional state; each shot returns an ordinary bit string. Repeating the experiment therefore produces approximately half 00 and half 11, while the anticorrelated states 01 and 10 should have zero support in a noiseless statevector simulation.

This small example is scientifically useful because it joins several tasks that are often tested separately: circuit construction, seeded sampling, target-aware compilation, structured result export, and graphical inspection. A script can draw a plausible circuit while sampling the wrong object, or it can produce balanced counts without proving that compilation respected the requested instruction set and connectivity. A credible validation must connect the input specification to the constructed circuit, the sampler output, the compiled representation, and every retained deliverable.

The experiment described here uses Qiskit 1.2.4 and the local StatevectorSampler. IBM's documentation describes this primitive as a reference sampler implemented with full statevector simulation. It is suitable for a deterministic CPU test because it does not require a cloud account or quantum processor. That choice also defines the claim boundary: the result validates ideal circuit logic and software behavior, not hardware fidelity, calibration quality, readout mitigation, or quantum advantage.

Why Bell correlations are a strong software check

The Bell circuit has a compact expected distribution with a strict support condition. A weak check might merely confirm that two counts were returned. The stronger contract used here requires exactly 2,048 shots, positive counts only for 00 and 11, and an absolute deviation no greater than 0.08 from probability 0.5 for each expected state. These conditions detect incorrect qubit order, missing entangling gates, accidental independent superpositions, malformed measurement registers, and silent changes to the requested number of shots.

Seeded sampling matters even though the theoretical probabilities are symmetric. Finite-shot counts fluctuate around their expectations, and a fixed seed makes the observed table reproducible enough for regression testing. The seed is not evidence of physical determinism; it controls the pseudo-random sampling implementation. Another valid seed should give different counts that still satisfy the support and tolerance conditions. Recording both the seed and the tolerance prevents a future reader from mistaking one exact count vector for a universal physical result.

Circuit transpilation and the target contract

Quantum circuits are written using conceptual gates, but execution targets support particular instruction sets and coupling constraints. Qiskit's transpiler transforms a circuit into a representation that obeys a specified target while trying to control depth and complexity. The demo requests the basis gates rz, sx, x, and cx, a bidirectional two-qubit coupling map, optimization level 3, and a fixed transpiler seed. Retaining these inputs makes the compilation step auditable rather than treating transpilation as an opaque convenience.

For a two-qubit Bell circuit, connectivity is simple, yet checking it remains valuable. The same testing pattern scales to larger circuits where routing inserts swaps and compilation choices materially change depth. A production study should usually build a Target from a real backend and record its calibration context. This local example instead uses an explicit basis and coupling map so the test remains hardware-independent and can run on an ordinary Linux CPU.

Test progress

GateStatusEvidence
Package preflightPassed24 Python distributions, 152,257,778 retained download bytes
Managed installationPassedQiskit 1.2.4 environment retained for regression
Native key-feature executionPassedBell circuit, sampler, transpilation, CSV, JSON, PNG, and SVG checks
Real chat-directed executionPassedThe agent loaded the installed skill and authored a task-specific managed-runner program
Semantic artifact validationPassedCounts, support, probabilities, target inputs, image dimensions, and SVG substance checked
Publication evidencePassedFocused result capture plus two data-derived result visuals

The first fresh publication attempt exposed a schema mismatch in the validator. The generated result was scientifically correct, but it stored counts under simulation.counts rather than at the document root. Inspection confirmed 997 00 observations, 1,051 11 observations, zero anticorrelated outcomes, the requested 2,048-shot total, and the requested transpilation inputs. The validator was corrected to accept this semantically equivalent structured form, then rerun against the retained chat artifacts. No result value was edited or fabricated during that repair.

Demo user request

Use the installed qiskit skill and the input file circuit-spec.json to run a reproducible local Bell-state experiment. Write and execute a task-specific Python analysis program through the skill's managed environment. Build and measure the requested circuit, execute it with StatevectorSampler, transpile it to the requested basis gates and coupling map, and create qiskit-results.json, counts.csv, circuit PNG/SVG files, and histogram PNG/SVG files. Summarize the observed counts, Bell correlation, transpilation result, and every output path. Do not install another copy of Qiskit and do not fabricate results.

This is an agent-directed test rather than a hard-coded response test. The request states the scientific objective and deliverables, while the input file supplies the exact operations, shots, seeds, basis gates, coupling map, optimization level, expected support, and tolerance. The chat agent must load the skill, read the data, author its own analysis program, execute that program through the managed environment, and explain the actual generated results.

Demo data

The compact input is available as circuit-spec.json. It contains two qubits, an H gate on qubit 0, a controlled-X from qubit 0 to qubit 1, measurement of all qubits, 2,048 shots, seed 4,217, and an explicit transpilation contract. Keeping the scientific expectation in data rather than embedding it only in prose makes the run reviewable and allows validators to compare observed output against the same source used by the program.

Input fieldValueScientific role
Qubits2Defines the Hilbert-space and output bit-string width
OperationsH(0), CX(0→1)Creates the ideal Bell pair
Shots2,048Controls finite-sampling precision
Sampler seed4,217Makes the local regression repeatable
Expected support00, 11Rejects anticorrelated outcomes
Probability target0.5 eachEncodes the ideal symmetric distribution
Tolerance±0.08Allows finite-shot fluctuation
Basis gatesrz, sx, x, cxDefines the compilation instruction set
Coupling map0↔1Defines permitted two-qubit connectivity
Optimization level3Requests an optimization-oriented transpilation pass

Execution workflow

The package transaction was downloaded before installation and retained inside the skill's ignored test directory. Its 152.3 MB measured transfer is below the host policy's strict 500 MB limit. Installation then created an isolated Python 3.11 environment under the application tool root. A probe imported Qiskit and reported the pinned version before any scientific credit was assigned. This distinction matters because successful installation proves only that imports work; it does not prove circuit semantics, artifact correctness, or chat routing.

The deterministic native path constructed and sampled the circuit first. It asserted the complete count total, exact support, probability tolerance, and positive transpiled depth. It exported JSON and CSV, drew the circuit in PNG and SVG, and plotted measurement counts in PNG and SVG. The independent chat path then began from the same input but required the agent to write a separate program. The harness inspected tool messages to prove that the skill was loaded, a file was written, and the managed runner—not an unrelated system interpreter—executed the task.

python scripts/install.py
python scripts/tool.py probe
python scripts/tool.py run -- analysis_program.py

These commands document the reproducible interface, but users do not need to write or maintain the analysis program themselves in the interactive workflow. The scientific agent reads the request and data, writes the task-specific code, runs it in the managed environment, validates deliverables, and reports the result. Exposing the command boundary remains useful for auditing, automation, and debugging.

Results and artifacts

The observed count distribution passed every Bell-correlation assertion. Out of 2,048 shots, 00 appeared 997 times and 11 appeared 1,051 times. Their respective probabilities were 0.486816 and 0.513184. Both differ from 0.5 by only 0.013184, comfortably inside the declared 0.08 tolerance. The 01 and 10 rows were present in the CSV with zero counts, making the absence of anticorrelated support explicit rather than relying on omitted dictionary keys.

StateCountProbabilityExpected interpretation
009970.486816Bell-correlated outcome
0100.000000Must be absent in the ideal model
1000.000000Must be absent in the ideal model
111,0510.513184Bell-correlated outcome
Total2,0481.000000Exact requested shot count

The result JSON records circuit depth and gate counts before and after compilation, sampler seed, counts, probabilities, expected and observed support, maximum probability deviation, and all output paths. The compilation record shows a nonzero transpiled depth and gate counts limited to the requested basis plus measurement and barrier operations. The test also compares the recorded basis-gate list and coupling map with the input specification, preventing a visually correct but target-agnostic circuit from receiving credit.

Focused chat result report with validated Qiskit deliverables

The focused result capture presents the deliverables and validated fields inside the chat results surface. It deliberately excludes file explorers, unrelated sidebars, raw event logs, and unformatted JSON because those elements make scientific evidence harder to review. The table is the primary result, while the underlying files remain available for exact reproduction and machine checks.

Qiskit Bell circuit generated by the chat-directed analysis

The circuit image provides a direct visual check of the two-qubit preparation and measurement structure. A picture alone is insufficient evidence because it cannot prove which object was sampled or whether target constraints were applied. Here it is interpreted together with the structured JSON, count table, managed-runner trace, and semantic validator.

Validated Qiskit result fields derived from retained artifacts

This data-derived table is generated from the retained output documents rather than redrawn by hand. Its provenance manifest records the source report and file hash. That linkage helps reviewers distinguish scientific artifacts from decorative illustrations and allows later tests to detect accidental replacement or drift.

How to interpret the result

The test confirms that the software created the intended ideal Bell correlation. It does not by itself demonstrate nonlocality in the experimental-physics sense because no measurement-basis sweep or Bell-inequality analysis was performed. It also does not estimate hardware noise. The correct interpretation is narrower: given the declared circuit and local reference sampler, the observed finite-shot distribution matches the ideal correlated support and probability expectation.

Balanced counts are not the only success criterion. If the circuit produced 1,024 00 and 1,024 11 but the agent bypassed the managed environment, ignored the coupling map, or drew placeholder images, the E2E would fail. Conversely, exact equality is not required because sampling is finite. The tolerance expresses the scientific expectation while avoiding a brittle dependence on a single random outcome.

Reproducibility

Reproduction requires the input checksum, Qiskit version, Python version, package source, sampler seed, shot count, transpiler seed, basis gates, coupling map, optimization level, and generated program. The retained package distributions and managed environment reduce dependence on future package-index availability. JSON and CSV provide machine-readable evidence; PNG supports quick visual review; SVG preserves scalable vector output for publication and detailed inspection.

A robust extension should repeat the experiment with multiple seeds and report the distribution of deviations, then run an equivalent ISA circuit on a named backend with calibration metadata. Hardware runs should distinguish raw counts from mitigated counts and should never compare them to the ideal statevector result without acknowledging readout and gate errors. The local test is best treated as a software and workflow baseline before those more expensive experiments.

Common failure modes

Bit ordering is a frequent source of confusion. Qiskit displays and indexes classical bits according to conventions that can surprise users moving between circuit diagrams, arrays, and bit strings. This two-qubit symmetric Bell state is less sensitive to reversal than an asymmetric test, so future coverage should add a deliberately asymmetric circuit. Another failure mode is sampling an unmeasured circuit or reading the wrong classical register from a primitive result; explicit output-shape and count-total assertions help catch both.

Compilation can also appear successful while ignoring target details. Passing a basis list or coupling map in the input is not enough; the output must retain evidence that the requested values were used. Finally, image generation may fail because optional visualization dependencies are absent. That is why the package preflight includes the visualization extra and the validator checks that PNG dimensions are substantive and SVG files contain real vector markup.

Limitations

This demonstration is intentionally small and CPU-only. It does not access IBM Quantum hardware, characterize noise, perform tomography, test a Bell inequality, or compare compiler strategies across devices. StatevectorSampler is an ideal reference implementation and is incompatible with some workflows involving mid-circuit measurement. The pinned Qiskit 1.2.4 environment is appropriate for reproducing this test, but newer SDK versions may change primitive result schemas and recommended APIs.

The measured package transfer reflects Linux x86_64 and Python 3.11 wheels resolved on the test date. Other operating systems, architectures, Python versions, or package indexes can produce different transactions. The environment is retained to support repair and regression, but it should not be interpreted as a universal deployment guarantee. A separate platform validation is required before marking macOS or Windows as tested.

References

Try this workflow

MindPlot includes built-in support for this scientific workflow. You can describe the Bell-state experiment in ordinary language, attach the circuit specification, and ask the agent to generate, execute, validate, and explain the deliverables without writing the code yourself. The web experience is available at mindplot.ai, while the desktop version offers a more private local workflow and retained scientific environments.