-
Notifications
You must be signed in to change notification settings - Fork 0
/
ceshi_common.py
57 lines (48 loc) · 1.92 KB
/
ceshi_common.py
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
def assert_equivalent_unitary(U, V):
try:
import cirq
cirq.testing.assert_allclose_up_to_global_phase(U, V, atol=1e-5)
except ModuleNotFoundError:
from unisys.utils.operations import is_equiv_unitary
assert is_equiv_unitary(U, V)
def ceshi_decompose(g, decomp_func):
from unisys.utils.operations import tensor_slots, controlled_unitary_matrix
from functools import reduce
import numpy as np
n = g.num_qregs
qregs_sorted = sorted(g.qregs)
qregs_rewiring = {p: q for p, q in zip(qregs_sorted, range(n))}
qregs_rewired = [qregs_rewiring[q] for q in g.qregs]
if g.n_qubits > int(np.log2(g.data.shape[0])) == 1:
data = reduce(np.kron, [g.data] * g.n_qubits)
else:
data = g.data
if g.cqs:
U = controlled_unitary_matrix(data, len(g.cqs))
U = tensor_slots(U, n, qregs_rewired)
else:
U = tensor_slots(data, n, qregs_rewired)
circ = decomp_func(g)
print(circ)
print(circ.qubits)
assert_equivalent_unitary(U, circ.unitary())
def ceshi_mapping(circ, device=None, device_fname=None):
if device is None and device_fname is None:
raise ValueError('Either device or device_fname should be specified')
if device is None:
from unisys.utils.arch import read_device_topology
device = read_device_topology(device_fname)
from unisys.mapping.heuristic import sabre_search
from unisys.utils.arch import verify_mapped_circuit
print(device)
print(device.nodes)
print(device.edges)
mapped_circ, init_mapping, final_mapping = sabre_search(circ, device)
print('Initial mapping:', init_mapping)
print('Final mapping:\t', final_mapping)
print('Original circuit:', circ)
print(circ.to_cirq())
print('Mapped circuit:', mapped_circ)
print(mapped_circ.to_cirq())
assert verify_mapped_circuit(circ, mapped_circ, init_mapping, final_mapping)
print('Mapping correct!')