CHSH Bell test
A complete Clauser-Horne-Shimony-Holt (CHSH) Bell-inequality test: an Entangled Source distributes polarisation-entangled pairs to two spatially separated measurement stations, conventionally called Alice and Bob, each equipped with a rotatable half-wave plate, a polarising beam splitter, and two single-photon detectors.
The circuit does two things:
generates synthetic coincidence-count data for the four analyser-setting combinations the CHSH protocol requires, and
combines that data into the CHSH statistic \(S\), reporting whether the simulated system violates the Bell-CHSH inequality.
Unlike Beam splitter, which reads a single number off one run, this example runs the simulation four times - once per analyser-setting pair - and the result is the combination of all four.
1. The theory
1.1 The CHSH inequality
For any local hidden-variable theory, correlations between outcomes recorded at two separated stations, using one of two possible settings at each station, must satisfy
where \(E(x, y)\) is the correlation coefficient between Alice’s and Bob’s outcomes for settings \(x\) and \(y\). Quantum mechanics permits entangled states to violate this bound, up to the Tsirelson bound \(\lvert S \rvert \leq 2\sqrt{2} \approx 2.828\).
An observation of \(\lvert S \rvert > 2\) certifies that the measured correlations cannot be reproduced by any local-realistic model - that the source produces genuine entanglement rather than merely classical correlation.
Note
This is the sharpest test in the examples section of whether the simulator is doing real quantum state evolution. A model that assigned each photon a hidden polarisation at birth and then flipped independent coins at the detectors could not exceed \(\lvert S \rvert = 2\), no matter how it was tuned.
1.2 Optimal analyser angles
The script uses the angle set that maximises \(S\) for a maximally entangled polarisation state. The four values are separated by 22.5° increments and are expected to yield \(S \approx 2\sqrt{2}\) for an ideal, noiseless state.
Symbol |
Role |
Analyser value |
|---|---|---|
\(a\) |
Alice, setting 1 |
0.0° |
\(a'\) |
Alice, setting 2 |
45.0° |
\(b\) |
Bob, setting 1 |
22.5° |
\(b'\) |
Bob, setting 2 |
67.5° |
Every pair in the \(S\) expression is separated by 22.5°, and for a maximally entangled state \(E = \cos(2 \times 22.5°) = 0.7071\), so four terms give \(4 \times 0.7071 = 2.828\).
1.3 The correlation coefficient
For each pair of settings, four joint-detection (coincidence) outcomes are possible: HH, HV, VH, and VV, where H denotes a horizontally polarised detection and V a vertically polarised one. The correlation coefficient is the normalised difference between “same-basis” and “different-basis” outcomes:
\(E = +1\) is perfect same-basis correlation, \(E = -1\) perfect anti-correlation, and \(E = 0\) the complete absence of correlation between the two arms.
2. The circuit
┌──▶ AliceDetectorHorizontal
EPS ──0──▶ HWP(a) ──▶ PBS_A ──────────┤
│ └──▶ AliceDetectorVertical
│
│ ┌──▶ BobDetectorHorizontal
└──1──▶ HWP(b) ──▶ PBS_B ────────────┤
└──▶ BobDetectorVertical
The signal-flow graph mirrors a physical tabletop CHSH experiment, and is rebuilt independently for each of the four analyser-setting configurations.
2.1 Component roles
Component |
Purpose |
|---|---|
|
Discrete-event simulation clock and scheduler ( |
|
Tracks and evolves the joint polarisation state of each photon pair as it propagates through the optical components. |
Emits correlated signal/idler pairs via SPDC, each pair sharing an entangled polarisation state. |
|
Rotates the polarisation basis by twice its physical angle. Implements the analyser’s choice of measurement setting. |
|
Routes horizontally polarised photons to one output port and vertically polarised photons to the other, realising a projective polarisation measurement. |
|
Single-photon detector with dead time, timing jitter, dark counts, detection efficiency, and coupling efficiency. |
|
Photon propagation, including fibre attenuation, core refractive index, and physical length. |
2.2 Detector parameters
DETECTOR_PARAMETERS = dict(
dead_time=40e-9, # 40 ns recovery time after each click
jitter=55e-12, # 55 ps timing uncertainty
mean_response_time=2e-9, # 2 ns average latency
coupling_eff=0.95, # 95 % fibre-to-detector coupling
dark_count_rate=100, # 100 dark counts per second
det_eff=0.90 # 90 % intrinsic quantum efficiency
)
These model a realistic single-photon detector - a superconducting nanowire or avalanche photodiode device - rather than the ideal detectors used in the other examples. They directly affect the achievable \(S\): dark counts and finite efficiency introduce noise that pulls \(\lvert S \rvert\) down from \(2\sqrt{2}\).
2.3 Channel parameters
FIBER_CHANNEL_PARAMETERS = dict(
length=1, # metres, source → analyser station
alpha=0.2, # 0.2 dB/km attenuation
n_core=1.5 # fibre core refractive index
)
The script overrides length = 0 for every channel internal to a
station (half-wave plate → polarising beam splitter → detector), since
those represent free-space optics on an optical bench rather than a fibre
run. Only the two source-to-station links carry the fibre parameters.
Note
length is in metres, so length=1 is a one-metre patch cord
with a transmittance of about 0.99995 - effectively lossless. To study
the effect of a real link distance, raise it to kilometre scales:
length=10000 at the same alpha transmits about 63 %. See
Quantum channels.
3. The script
from QNS.components import *
from QNS.channels import *
from QNS.StateEvaluation import *
import numpy as np
# --- Detector parameters:
DETECTOR_PARAMETERS = dict(
dead_time=40e-9,
jitter=55e-12,
mean_response_time=2e-9,
coupling_eff=0.95,
dark_count_rate=100,
det_eff=0.90
)
# --- Channel parameters:
FIBER_CHANNEL_PARAMETERS = dict(
length=1,
alpha=0.2,
n_core=1.5
)
# --- CHSH analyzer settings (optimal Bell angles, degrees) ---
ALICE_SETTING_1 = 0.0 # commonly labeled "a"
ALICE_SETTING_2 = 45.0 # commonly labeled "a'"
BOB_SETTING_1 = 22.5 # commonly labeled "b"
BOB_SETTING_2 = 67.5 # commonly labeled "b'"
RUNTIME_SECONDS = 0.05
measurement_configurations = [
("correlation_alice1_bob1", ALICE_SETTING_1, BOB_SETTING_1),
("correlation_alice1_bob2", ALICE_SETTING_1, BOB_SETTING_2),
("correlation_alice2_bob1", ALICE_SETTING_2, BOB_SETTING_1),
("correlation_alice2_bob2", ALICE_SETTING_2, BOB_SETTING_2),
]
correlation_results = {}
for config_label, alice_angle_deg, bob_angle_deg in measurement_configurations:
# Half-wave plate rotates polarization by 2x its angle, so divide requested
# analyzer angle by 2 to get the physical HWP setting
alice_hwp_angle = (alice_angle_deg / 2.0) % 360
bob_hwp_angle = (-bob_angle_deg / 2.0) % 360
tl = Timeline()
state_manager = StateManager("StateManager")
entangled_source = EntangledPhotonSource("EntangledSource", tl.env, state_manager)
alice_half_waveplate = HalfWavePlate(
"AliceHalfWavePlate", tl.env, state_manager, angle=alice_hwp_angle
)
alice_polarizing_splitter = PolarisingBeamSplitter(
"AlicePolarizingBeamSplitter", tl.env, state_manager
)
alice_detector_horizontal = Detector(
"AliceDetectorHorizontal", tl.env, state_manager, **DETECTOR_PARAMETERS
)
alice_detector_vertical = Detector(
"AliceDetectorVertical", tl.env, state_manager, **DETECTOR_PARAMETERS
)
bob_half_waveplate = HalfWavePlate(
"BobHalfWavePlate", tl.env, state_manager, angle=bob_hwp_angle
)
bob_polarizing_splitter = PolarisingBeamSplitter(
"BobPolarizingBeamSplitter", tl.env, state_manager
)
bob_detector_horizontal = Detector(
"BobDetectorHorizontal", tl.env, state_manager, **DETECTOR_PARAMETERS
)
bob_detector_vertical = Detector(
"BobDetectorVertical", tl.env, state_manager, **DETECTOR_PARAMETERS
)
channel_links = [
(entangled_source, 0, alice_half_waveplate, 0),
(entangled_source, 1, bob_half_waveplate, 0),
(alice_half_waveplate, 0, alice_polarizing_splitter, 0),
(bob_half_waveplate, 0, bob_polarizing_splitter, 0),
(alice_polarizing_splitter, 0, alice_detector_horizontal, 0),
(alice_polarizing_splitter, 1, alice_detector_vertical, 0),
(bob_polarizing_splitter, 0, bob_detector_horizontal, 0),
(bob_polarizing_splitter, 1, bob_detector_vertical, 0),
]
for link_index, (source_node, source_port, dest_node, dest_port) in enumerate(channel_links):
channel_parameters = dict(FIBER_CHANNEL_PARAMETERS)
if source_node is not entangled_source:
channel_parameters['length'] = 0 # internal free-space optics, not the fiber run
channel = QuantumOpticalChannel(
f"OpticalChannel_{link_index}", tl.env, **channel_parameters
)
channel.connect_channel([source_node, source_port], [dest_node, dest_port])
detector_list = [
alice_detector_horizontal, alice_detector_vertical,
bob_detector_horizontal, bob_detector_vertical
]
run_result = tl.run(
runtime=RUNTIME_SECONDS,
laser_list=[entangled_source],
detector_list=detector_list
# coincidence_window left as None -> ground-truth same-pulse pairing
)
print("\n" + "="*70)
print("PHOTON NUMBER DISTRIBUTION")
print("="*70)
for n_pairs, count in sorted(entangled_source.my_dict.items(), key=lambda x: int(x[0])):
n_pairs = int(n_pairs)
total_photons = 2 * n_pairs
print(
f"{n_pairs} pair(s) | "
f"{n_pairs} signal + {n_pairs} idler | "
f"{total_photons} total photons | "
f"{count} events"
)
coincidence_counts = run_result['coincidences']
alice_h_id, alice_v_id = alice_detector_horizontal.get_id(), alice_detector_vertical.get_id()
bob_h_id, bob_v_id = bob_detector_horizontal.get_id(), bob_detector_vertical.get_id()
coincidence_by_outcome = {
"horizontal_horizontal": coincidence_counts[(alice_h_id, bob_h_id)],
"horizontal_vertical": coincidence_counts[(alice_h_id, bob_v_id)],
"vertical_horizontal": coincidence_counts[(alice_v_id, bob_h_id)],
"vertical_vertical": coincidence_counts[(alice_v_id, bob_v_id)],
}
total_coincidences = sum(coincidence_by_outcome.values())
correlation_value = (
(coincidence_by_outcome["horizontal_horizontal"]
+ coincidence_by_outcome["vertical_vertical"]
- coincidence_by_outcome["horizontal_vertical"]
- coincidence_by_outcome["vertical_horizontal"])
/ total_coincidences
if total_coincidences > 0 else 0.0
)
correlation_results[config_label] = correlation_value
print(f"{config_label}: Alice={alice_angle_deg:+.1f} deg, Bob={bob_angle_deg:+.1f} deg | "
f"HH={coincidence_by_outcome['horizontal_horizontal']} "
f"HV={coincidence_by_outcome['horizontal_vertical']} "
f"VH={coincidence_by_outcome['vertical_horizontal']} "
f"VV={coincidence_by_outcome['vertical_vertical']} "
f"total={total_coincidences} | E={correlation_value:+.6f}")
chsh_statistic = (
correlation_results["correlation_alice1_bob1"]
- correlation_results["correlation_alice1_bob2"]
+ correlation_results["correlation_alice2_bob1"]
+ correlation_results["correlation_alice2_bob2"]
)
print(f"\nCHSH statistic S = {chsh_statistic:+.6f}")
print(f"|S| = {abs(chsh_statistic):.6f}")
print("Bell-CHSH inequality violated." if abs(chsh_statistic) > 2 else "No Bell-CHSH violation.")
4. How each run works
For each of the four (Alice angle, Bob angle) pairs in
measurement_configurations, the script performs a complete and
independent simulation, in six stages.
4.1 Half-wave-plate angle conversion
A half-wave plate rotates polarisation by twice its physical angle, so to achieve an analyser angle \(\theta\) the plate is set to \(\theta/2\):
alice_hwp_angle = (alice_angle_deg / 2.0) % 360
bob_hwp_angle = (-bob_angle_deg / 2.0) % 360
Bob’s plate additionally uses a negated angle, the standard convention compensating for the opposite propagation and measurement handedness between the two arms of the entangled source.
4.2 Component instantiation
A fresh Timeline, StateManager, entangled source, and complete set
of Alice- and Bob-side optics and detectors are created for each
configuration. No quantum state or simulation history carries over between
the four runs.
4.3 Wiring
All components are linked with QuantumOpticalChannel instances
according to the connectivity in Section 2, forming the source-to-detector
path for both stations.
4.4 Run
tl.run(...) executes the simulation for RUNTIME_SECONDS = 0.05 s
(50 ms) of simulated time, driving the pair source and logging detections
on all four detectors.
No explicit coincidence_window is supplied, so the simulator uses
ground-truth pairing: a coincidence is counted only when two detections
originate from the same emitted photon pair, rather than being windowed in
real time. This isolates the polarisation-correlation physics from
timing-jitter and accidental-coincidence effects. See
Timeline for the two coincidence-counting modes.
4.5 Reporting
Each run prints the photon-number distribution, the four coincidence counts (HH, HV, VH, VV), and the correlation coefficient \(E\) for that setting pair. Section 6 covers how to read them.
4.6 Aggregation
After all four configurations have run, the four \(E\) values are combined:
chsh_statistic = (
correlation_results["correlation_alice1_bob1"]
- correlation_results["correlation_alice1_bob2"]
+ correlation_results["correlation_alice2_bob1"]
+ correlation_results["correlation_alice2_bob2"]
)
and the script reports \(S\), its magnitude, and the verdict on whether \(\lvert S \rvert > 2\).
5. Building it in the Circuit Builder
The table below gives the exact half-wave-plate settings for each of the
four runs. These are the literal values to enter into each station’s
HalfWavePlate component - no sign inversion or modulo arithmetic is
needed at the point of use.
Run |
Analyser pair |
Alice HWP angle |
Bob HWP angle |
|---|---|---|---|
1 |
\(E(a, b)\) |
0.0° |
168.75° |
2 |
\(E(a, b')\) |
0.0° |
146.25° |
3 |
\(E(a', b)\) |
22.5° |
168.75° |
4 |
\(E(a', b')\) |
22.5° |
146.25° |
Alice’s angles are half the analyser angle (0.0° → 0.0°, 45.0° → 22.5°), while Bob’s are 180° minus half the analyser angle (22.5° → 168.75°, 67.5° → 146.25°).
Note
The 180° formulation is physically identical to the mirrored-angle
convention the script computes ((-θ/2) % 360, giving 348.75° and
326.25°), because a half-wave plate’s Jones matrix
is periodic in \(\theta\) with period 180°: \(348.75° - 180° =
168.75°\) and \(326.25° - 180° = 146.25°\) give element-for-element
identical matrices. Every angle is a plain, non-negative value inside the component’s 0 … 360
range.
5.1 Per-run procedure
Instantiate a fresh timeline, state manager, entangled photon source, and a complete set of Alice- and Bob-side optics and detectors. Carry no state between runs.
Set Alice’s half-wave plate to the Alice HWP angle for that run, and Bob’s to the Bob HWP angle.
Connect the components in the sequence source → half-wave plate → polarising beam splitter → detectors, for both stations.
Run for the configured runtime with detection events logged at all four detectors, using ground-truth pairing.
Record the four coincidence counts (HH, HV, VH, VV) and compute \(E\) for that configuration.
Once all four runs are complete, combine the four coefficients into \(S\) and compare \(\lvert S \rvert\) against the classical and quantum bounds.
6. Reading the output
6.1 Photon-number distribution
N pair(s) | N signal + N idler | 2N total photons | count events
This reports how often the source emitted \(N\) simultaneous entangled pairs in a single pulse. In an ideal single-pair source only \(N = 1\) events contribute valid CHSH statistics; \(N \geq 2\) events - multi-pair emission - are a known noise mechanism in physical SPDC sources and, if present in significant numbers, reduce the achievable \(\lvert S \rvert\). See Entangled Source for why multi-pair emission happens and how its probability scales with pump power.
6.2 Per-configuration result line
correlation_aliceX_bobY: Alice=±θ deg, Bob=±θ deg | HH=.. HV=.. VH=.. VV=.. total=.. | E=+0.707
Field |
Meaning |
|---|---|
|
Raw coincidence counts for each of the four joint-detection outcomes. |
|
Sum of all four - the total number of valid, paired coincidence events for this setting combination. |
|
The normalised correlation coefficient of Section 1.3, bounded within \([-1, +1]\). |
6.3 Final CHSH result
CHSH statistic S = +2.767625
|S| = 2.767625
Bell-CHSH inequality violated.
\(\lvert S \rvert\) range |
Interpretation |
|---|---|
\(\lvert S \rvert \leq 2\) |
Consistent with a local hidden-variable theory; no entanglement certified. Typically indicates excessive noise, incorrect angle calibration, insufficient statistics, or a non-entangled/mixed source state. |
\(2 < \lvert S \rvert \leq 2\sqrt{2}\) |
Inequality violated. The correlations cannot be explained by local realism - the source behaves as a genuinely entangled quantum source. Values closer to \(2\sqrt{2}\) indicate a lower-noise, higher-fidelity simulated experiment. |
\(\lvert S \rvert > 2\sqrt{2}\) |
Exceeds the Tsirelson bound. For a correct simulation of quantum
correlations this should not happen; it signals a statistical
fluctuation (too few coincidences, or |
The sample value above is 97.9 % of the Tsirelson bound: the shortfall from 2.828 is the detector imperfection budget of Section 2.2 (90 % detection efficiency, 95 % coupling, 100 dark counts/s) plus multi-pair emission from the source.
Important
Each of the four \(E\) values is estimated from a finite number of
coincidences, so \(S\) carries statistical uncertainty. Increasing
RUNTIME_SECONDS increases the number of emitted pairs and hence the
coincidence statistics, reducing that uncertainty and stabilising
\(S\) closer to its expectation value for the modelled source and
detector parameters. If a run lands just either side of 2, get more
statistics before drawing any conclusion from it.
7. Turning the knobs
More statistics. RUNTIME_SECONDS = 0.05 is the first thing to raise
if \(S\) moves noticeably between repeat runs. Statistical scatter, not
physics, is the usual reason a run lands below 2.
Detector quality. Set det_eff=1, coupling_eff=1 and
dark_count_rate=0 to recover the near-ideal case, and watch
\(\lvert S \rvert\) climb towards \(2\sqrt{2}\). Reintroducing the
dark counts alone shows how quickly uncorrelated clicks dilute \(E\).
Channel length. Raise length from 1 m to kilometre scales on the
two source-to-station links. Loss costs coincidences quadratically - both
photons must survive - so this degrades the statistics faster than it
degrades \(E\) itself.
Wrong angles. Set all four analyser angles equal and \(S\) collapses towards 2 or below. This is a useful sanity check that the violation depends on the 22.5° structure rather than on anything accidental in the wiring.
Coincidence mode. Supply a coincidence_window to tl.run instead
of leaving it None, and accidental coincidences enter the counts the
way they do in a real experiment - \(\lvert S \rvert\) drops
accordingly.