Repository navigation
Expand file tree
/
Copy pathtest_process_matrix.py
More file actions
486 lines (363 loc) · 16.8 KB
/
Copy pathtest_process_matrix.py
File metadata and controls
486 lines (363 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
"""
Tests for Gap 1: ProcessMatrix type and Morimae MBQC process matrix.
Covers:
- ProcessMatrix construction and validation
- identity_process and from_unitary factory functions
- MeasurementPattern.process_matrix() (Morimae formula)
- causal_inequality_value() for the 2-party qubit case
"""
import numpy as np
import pytest
from qrl.causal import ProcessMatrix, identity_process, from_unitary
from qrl.mbqc.measurement_pattern import MeasurementPattern, Measurement
# ------------------------------------------------------------------ #
# Helpers #
# ------------------------------------------------------------------ #
def _make_valid_2party_W() -> np.ndarray:
"""Build a simple valid 2-party qubit process matrix (16×16)."""
# Use the identity process: W = (1/4) I_16
return np.eye(16, dtype=complex) * (4.0 / 16.0)
# ------------------------------------------------------------------ #
# Construction and dimension validation #
# ------------------------------------------------------------------ #
def test_process_matrix_construction():
"""Basic construction with correct dimensions succeeds."""
W = np.eye(4, dtype=complex) * 0.5 # d_in=1, d_out=2 → total=2; wait 1*2=2, 2×2=4
# 1 party, d_in=2, d_out=2 → total_dim = 4
pm = ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2])
assert pm.total_dim == 4
assert pm.W.shape == (4, 4)
def test_process_matrix_wrong_input_dims_raises():
W = np.eye(4, dtype=complex)
with pytest.raises(ValueError, match="input_dims"):
ProcessMatrix(W=W, parties=["A"], input_dims=[2, 2], output_dims=[2])
def test_process_matrix_wrong_output_dims_raises():
W = np.eye(4, dtype=complex)
with pytest.raises(ValueError, match="output_dims"):
ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2, 2])
def test_process_matrix_wrong_W_shape_raises():
# Correct total_dim for 1 party d_in=2, d_out=2 is 4; supply wrong shape
W = np.eye(8, dtype=complex)
with pytest.raises(ValueError, match="must be"):
ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2])
def test_total_dim_single_qubit():
W = np.eye(4, dtype=complex) * 0.5
pm = ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2])
assert pm.total_dim == 4 # 1 party × (2_in * 2_out)
def test_total_dim_two_qubit_parties():
W = _make_valid_2party_W()
pm = ProcessMatrix(W=W, parties=["A", "B"], input_dims=[2, 2], output_dims=[2, 2])
assert pm.total_dim == 16 # 2 parties × (2_in * 2_out) each
def test_total_dim_state_preparation():
# d_in=1 means "no external input" (state preparation mode)
W = np.eye(4, dtype=complex) * 2.0 # 2 parties, d_in=1, d_out=2 → total=4
pm = ProcessMatrix(W=W, parties=["Q0", "Q1"], input_dims=[1, 1], output_dims=[2, 2])
assert pm.total_dim == 4 # (1*2)^2 = 4
# ------------------------------------------------------------------ #
# PSD check #
# ------------------------------------------------------------------ #
def test_psd_true_for_identity():
W = np.eye(4, dtype=complex) * 0.5
pm = ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2])
assert pm.is_positive_semidefinite()
def test_psd_false_for_non_psd():
W = np.eye(4, dtype=complex) * 0.5
W[0, 0] = -0.1 # introduce negative eigenvalue
pm = ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2],
description="deliberately invalid")
assert not pm.is_positive_semidefinite()
def test_psd_true_for_rank1_projector():
# |ψ⟩ = (1,0,0,0), W = 2 |ψ⟩⟨ψ|: positive and normalised, but not a process.
# If A outputs |1⟩ the probabilities sum to 0, so it fails the no-loop
# condition: a single party's valid processes are ρ_{A_I} ⊗ 1_{A_O}.
W = np.zeros((4, 4), dtype=complex)
W[0, 0] = 2.0
pm = ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2])
assert pm.is_positive_semidefinite()
assert pm.is_normalized()
assert not pm.satisfies_no_loop_condition()
assert not pm.is_valid()
def test_single_party_state_times_identity_is_valid():
rho = np.array([[0.7, 0.2], [0.2, 0.3]], dtype=complex)
pm = ProcessMatrix(W=np.kron(rho, np.eye(2)), parties=["A"],
input_dims=[2], output_dims=[2])
assert pm.is_valid()
def test_causal_loop_is_not_valid():
# A wire from A's output back to A's input (the "grandfather" process):
# positive, Tr W = d_{A_O}, but A can make probabilities inconsistent.
v = np.array([1, 0, 0, 1], dtype=complex)
pm = ProcessMatrix(W=np.outer(v, v.conj()), parties=["A"],
input_dims=[2], output_dims=[2])
assert pm.is_positive_semidefinite() and pm.is_normalized()
assert not pm.is_valid()
def test_two_way_signalling_is_not_valid():
# Identity wires A_O -> B_I and B_O -> A_I at once: a causal loop.
def wire():
return np.array([1, 0, 0, 1], dtype=complex)
w = np.einsum("ab,cd->acdb", wire().reshape(2, 2), wire().reshape(2, 2)) # A_I A_O B_I B_O
w = w.reshape(16)
pm = ProcessMatrix(W=np.outer(w, w.conj()), parties=["A", "B"],
input_dims=[2, 2], output_dims=[2, 2])
assert np.isclose(np.trace(pm.W).real, 4.0)
assert not pm.is_valid()
def test_library_processes_are_valid():
from qrl.causal import definite_order_process, quantum_switch_process_matrix
from qrl.switch_witness import switch_process
for pm in (definite_order_process("AB"), definite_order_process("BA"),
quantum_switch_process_matrix(), switch_process(), switch_process(3)):
assert pm.is_valid(), pm.description
# ------------------------------------------------------------------ #
# Trace normalisation #
# ------------------------------------------------------------------ #
def test_normalized_true():
# 1 party, d_in=2, d_out=2: expected trace = 2
W = np.eye(4, dtype=complex) * 0.5 # Tr = 2
pm = ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2])
assert pm.is_normalized()
def test_normalized_false_wrong_trace():
W = np.eye(4, dtype=complex) # Tr = 4, but expected = 2
pm = ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2],
description="over-traced")
assert not pm.is_normalized()
def test_normalized_two_parties():
# 2 parties, d_in=2, d_out=2: expected trace = 4
W = _make_valid_2party_W() # Tr = (4/16)*16 = 4
pm = ProcessMatrix(W=W, parties=["A", "B"], input_dims=[2, 2], output_dims=[2, 2])
assert pm.is_normalized()
# ------------------------------------------------------------------ #
# is_valid #
# ------------------------------------------------------------------ #
def test_is_valid_identity_process():
pm = identity_process(n_parties=1)
assert pm.is_valid()
def test_is_valid_two_party_identity():
pm = identity_process(n_parties=2)
assert pm.is_valid()
def test_is_valid_false_non_psd():
W = np.eye(4, dtype=complex) * 0.5
W[0, 0] = -0.1
pm = ProcessMatrix(W=W, parties=["A"], input_dims=[2], output_dims=[2])
assert not pm.is_valid()
# ------------------------------------------------------------------ #
# identity_process factory #
# ------------------------------------------------------------------ #
def test_identity_process_single_party():
pm = identity_process(n_parties=1)
assert len(pm.parties) == 1
assert pm.input_dims == [2]
assert pm.output_dims == [2]
assert pm.W.shape == (4, 4)
assert np.isclose(np.trace(pm.W).real, 2.0)
def test_identity_process_two_parties():
pm = identity_process(n_parties=2)
assert len(pm.parties) == 2
assert pm.W.shape == (16, 16)
assert np.isclose(np.trace(pm.W).real, 4.0)
assert pm.is_valid()
def test_identity_process_d4():
pm = identity_process(n_parties=1, d_in=4, d_out=4)
assert pm.total_dim == 16
assert np.isclose(np.trace(pm.W).real, 4.0)
assert pm.is_valid()
def test_identity_process_is_proportional_to_identity():
pm = identity_process(n_parties=2)
expected = np.eye(16) * (4.0 / 16.0)
assert np.allclose(pm.W, expected)
# ------------------------------------------------------------------ #
# from_unitary factory #
# ------------------------------------------------------------------ #
def test_from_unitary_identity_gate():
I2 = np.eye(2, dtype=complex)
pm = from_unitary(I2)
assert pm.is_valid()
assert pm.W.shape == (4, 4)
assert pm.parties == ["A", "B"]
assert pm.input_dims == [1, 2] and pm.output_dims == [2, 1]
assert np.isclose(np.trace(pm.W).real, 2.0)
# For U=I: W = |1>><<1| on A_O B_I
expected = np.array([
[1, 0, 0, 1],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 1],
], dtype=complex)
assert np.allclose(pm.W, expected)
def test_from_unitary_hadamard():
H = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
pm = from_unitary(H)
assert pm.is_valid()
assert np.isclose(np.trace(pm.W).real, 2.0)
def test_from_unitary_pauli_x():
X = np.array([[0, 1], [1, 0]], dtype=complex)
pm = from_unitary(X)
assert pm.is_valid()
# For X: W = |X>><<X|, |X>> = sum_i |i> (x) X|i>
result = np.kron(np.eye(2), X) @ np.array([1, 0, 0, 1])
expected = np.outer(result, result.conj())
assert np.allclose(pm.W, expected)
def test_from_unitary_gives_channel_probabilities():
# A prepares |psi> (transposed Choi: conj|psi><psi|), B tests |phi>:
# probability |<phi|U|psi>|^2.
rng = np.random.default_rng(5)
z = rng.normal(size=(2, 2)) + 1j * rng.normal(size=(2, 2))
U, _ = np.linalg.qr(z)
pm = from_unitary(U)
for _ in range(5):
psi = rng.normal(size=2) + 1j * rng.normal(size=2); psi /= np.linalg.norm(psi)
phi = rng.normal(size=2) + 1j * rng.normal(size=2); phi /= np.linalg.norm(phi)
M = np.kron(np.outer(psi, psi.conj()).conj(), np.outer(phi, phi.conj()))
assert np.isclose(np.trace(M @ pm.W).real, abs(phi.conj() @ U @ psi) ** 2)
def test_from_unitary_two_qubit():
CNOT = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
], dtype=complex)
pm = from_unitary(CNOT)
assert pm.is_valid()
assert pm.W.shape == (16, 16)
assert np.isclose(np.trace(pm.W).real, 4.0)
def test_from_unitary_custom_party_name():
I2 = np.eye(2, dtype=complex)
pm = from_unitary(I2, party_names=["Alice", "Bob"])
assert pm.parties == ["Alice", "Bob"]
with pytest.raises(ValueError, match="sender"):
from_unitary(I2, party_names=["Alice"])
def test_from_unitary_non_square_raises():
U = np.ones((2, 3), dtype=complex)
with pytest.raises(ValueError, match="square"):
from_unitary(U)
def test_from_unitary_non_unitary_raises():
not_unitary = np.array([[1, 1], [0, 1]], dtype=complex)
with pytest.raises(ValueError, match="unitary"):
from_unitary(not_unitary)
# ------------------------------------------------------------------ #
# MeasurementPattern.process_matrix() (Morimae formula) #
# ------------------------------------------------------------------ #
def _cluster_pattern(n_qubits: int) -> MeasurementPattern:
"""Build a linear cluster state pattern with no measurements."""
edges = [(i, i + 1) for i in range(n_qubits - 1)]
return MeasurementPattern(
preparation=list(range(n_qubits)),
entanglement=edges,
measurements=[],
output_qubits=list(range(n_qubits)),
description=f"{n_qubits}-qubit linear cluster",
)
def test_pattern_pm_2qubit_cluster_is_valid():
pm = _cluster_pattern(2).process_matrix()
assert pm.is_valid()
def test_pattern_pm_2qubit_shape():
pm = _cluster_pattern(2).process_matrix()
assert pm.W.shape == (4, 4)
def test_pattern_pm_2qubit_trace():
pm = _cluster_pattern(2).process_matrix()
assert np.isclose(np.trace(pm.W).real, 1.0) # = prod of output dims (all 1)
def test_pattern_pm_2qubit_rank_one():
"""W = |G⟩⟨G| is rank-1 (one nonzero eigenvalue, equal to 1)."""
pm = _cluster_pattern(2).process_matrix()
eigs = pm.eigenvalues()
nonzero = eigs[eigs > 1e-10]
assert len(nonzero) == 1
assert np.isclose(nonzero[0], 1.0)
def test_pattern_pm_3qubit_cluster():
pm = _cluster_pattern(3).process_matrix()
assert pm.is_valid()
assert pm.W.shape == (8, 8)
assert np.isclose(np.trace(pm.W).real, 1.0)
def test_pattern_pm_parties_match_preparation():
pattern = _cluster_pattern(2)
pm = pattern.process_matrix()
assert pm.parties == ["Q0", "Q1"]
def test_pattern_pm_input_dims_are_two():
"""Each party receives its qubit of the graph state."""
pm = _cluster_pattern(2).process_matrix()
assert all(d == 2 for d in pm.input_dims)
def test_pattern_pm_output_dims_are_one():
"""Each party measures; nothing is sent on."""
pm = _cluster_pattern(2).process_matrix()
assert all(d == 1 for d in pm.output_dims)
def test_pattern_pm_2qubit_graph_state_values():
"""Verify |G⟩ = CZ|++⟩ = (|00⟩+|01⟩+|10⟩-|11⟩)/2."""
pm = _cluster_pattern(2).process_matrix()
# Expected graph state for 2-qubit cluster:
g = np.array([1, 1, 1, -1], dtype=complex) / 2.0
expected_W = np.outer(g, g.conj())
assert np.allclose(pm.W, expected_W)
def test_pattern_pm_with_measurements():
"""Pattern with actual measurements still produces valid process matrix."""
pattern = MeasurementPattern(
preparation=[0, 1],
entanglement=[(0, 1)],
measurements=[Measurement(qubit=0, angle=0.0)],
output_qubits=[1],
description="Bell pair (measure qubit 0)",
)
pm = pattern.process_matrix()
assert pm.is_valid()
assert pm.W.shape == (4, 4)
def test_pattern_pm_no_entanglement():
"""Single qubit, no entanglement: W = |+⟩⟨+|."""
pattern = MeasurementPattern(
preparation=[0],
entanglement=[],
measurements=[],
output_qubits=[0],
description="single |+⟩",
)
pm = pattern.process_matrix()
assert pm.is_valid()
plus = np.array([1.0, 1.0]) / np.sqrt(2)
expected_W = np.outer(plus, plus.conj())
assert np.allclose(pm.W, expected_W)
# ------------------------------------------------------------------ #
# causal_inequality_value #
# ------------------------------------------------------------------ #
def test_causal_inequality_returns_none_single_party():
pm = identity_process(n_parties=1)
assert pm.causal_inequality_value() is None
def test_causal_inequality_returns_none_wrong_dims():
# d_in = d_out = 4 → not the qubit case
pm = identity_process(n_parties=1, d_in=4, d_out=4)
assert pm.causal_inequality_value() is None
def test_causal_inequality_identity_below_causal_bound():
"""Maximally mixed 2-party process: P_win = 1/2 ≤ 3/4 (causal bound)."""
pm = identity_process(n_parties=2, d_in=2, d_out=2)
val = pm.causal_inequality_value()
assert val is not None
assert val <= 0.75 + 1e-10
def test_causal_inequality_identity_equals_half():
"""P_win for maximally mixed process = 1/2 (uniform over all outcomes)."""
pm = identity_process(n_parties=2, d_in=2, d_out=2)
val = pm.causal_inequality_value()
assert np.isclose(val, 0.5, atol=1e-8)
def test_causal_inequality_identity_is_causally_separable():
pm = identity_process(n_parties=2)
assert pm.is_causally_separable()
def test_causal_inequality_state_prep_is_causally_separable():
"""Processes with d_in=1 are state preparations and always separable."""
pm = _cluster_pattern(2).process_matrix()
assert pm.is_causally_separable()
# ------------------------------------------------------------------ #
# eigenvalues and repr #
# ------------------------------------------------------------------ #
def test_eigenvalues_non_negative_for_valid_pm():
pm = identity_process(n_parties=2)
eigs = pm.eigenvalues()
assert np.all(eigs >= -1e-10)
def test_eigenvalues_rank1():
pm = _cluster_pattern(2).process_matrix()
eigs = pm.eigenvalues()
# W = |G><G|: one eigenvalue = 1, rest ≈ 0
sorted_eigs = np.sort(np.abs(eigs))[::-1]
assert np.isclose(sorted_eigs[0], 1.0, atol=1e-8)
assert np.all(sorted_eigs[1:] < 1e-8)
def test_repr_contains_parties():
pm = identity_process(n_parties=2)
r = repr(pm)
assert "P0" in r
assert "P1" in r
def test_repr_contains_valid_flag():
pm = identity_process(n_parties=1)
assert "valid=True" in repr(pm)