Skip to content

Commit fb86fae

Browse files
committed
Fix decompose (see discopy#139)
1 parent 747a8f1 commit fb86fae

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

discopy/quantum/gates.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -459,9 +459,9 @@ def _decompose(self):
459459
return self
460460
src, tgt = (0, 1) if distance > 0 else (1, 0)
461461
perm = Circuit.permutation([src, *range(2, n_qubits), tgt])
462-
diagram = perm\
462+
diagram = perm[::-1]\
463463
>> type(self)(controlled) @ qubit ** (abs(distance) - 1)\
464-
>> perm[::-1]
464+
>> perm
465465
return diagram
466466

467467
def grad(self, var, **params):

test/quantum/circuit.py

+22
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# -*- coding: utf-8 -*-
22

3+
import pytest
4+
35
import numpy as np
46
import sympy
57
import torch
@@ -480,3 +482,23 @@ def test_circuit_chaining():
480482
Id(qubit).CRx(0.7, 1, 0)
481483
with raises(IndexError):
482484
Id(qubit ** 2).X(999)
485+
486+
487+
@pytest.mark.parametrize('x,y', [(0, 1), (0, 2), (1, 0), (2, 0), (5, 0)])
488+
def test_CX_decompose(x, y):
489+
n = abs(x - y) + 1
490+
binary_mat = np.eye(n, dtype=int)
491+
binary_mat[y] = np.bitwise_xor(binary_mat[x], binary_mat[y])
492+
493+
N = 1 << n
494+
unitary_mat = np.zeros(shape=(N, N))
495+
for i in range(N):
496+
bits = index2bitstring(i, n)
497+
v = bitstring2index(binary_mat @ bits % 2)
498+
unitary_mat[i][v] = 1
499+
500+
# take transpose because tensor axes follow diagrammatic order
501+
out = Id(n).CX(x, y).eval().array.reshape(N, N).T
502+
# but CX matrices are self transpose
503+
assert (out == out.T).all()
504+
assert (out == unitary_mat).all()

0 commit comments

Comments
 (0)