-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathtest_models_encodings.py
191 lines (152 loc) · 6.43 KB
/
test_models_encodings.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
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
"""Tests for qibo.models.encodings"""
import math
from itertools import product
import numpy as np
import pytest
from scipy.optimize import curve_fit
from qibo.models.encodings import (
comp_basis_encoder,
phase_encoder,
unary_encoder,
unary_encoder_random_gaussian,
)
def gaussian(x, a, b, c):
"""Gaussian used in the `unary_encoder_random_gaussian test"""
return np.exp(a * x**2 + b * x + c)
@pytest.mark.parametrize(
"basis_element", [5, "101", ["1", "0", "1"], [1, 0, 1], ("1", "0", "1"), (1, 0, 1)]
)
def test_comp_basis_encoder(backend, basis_element):
with pytest.raises(TypeError):
circuit = comp_basis_encoder(2.3)
with pytest.raises(ValueError):
circuit = comp_basis_encoder("0b001")
with pytest.raises(ValueError):
circuit = comp_basis_encoder("001", nqubits=2)
with pytest.raises(TypeError):
circuit = comp_basis_encoder("001", nqubits=3.1)
with pytest.raises(ValueError):
circuit = comp_basis_encoder(3)
zero = np.array([1, 0], dtype=complex)
one = np.array([0, 1], dtype=complex)
target = np.kron(one, np.kron(zero, one))
target = backend.cast(target, dtype=target.dtype)
if isinstance(basis_element, int):
state = comp_basis_encoder(basis_element, nqubits=3)
else:
state = comp_basis_encoder(basis_element)
state = backend.execute_circuit(state).state()
backend.assert_allclose(state, target)
@pytest.mark.parametrize("kind", [None, list])
@pytest.mark.parametrize("rotation", ["RX", "RY", "RZ"])
def test_phase_encoder(backend, rotation, kind):
sampler = np.random.default_rng(1)
nqubits = 3
dims = 2**nqubits
with pytest.raises(TypeError):
data = sampler.random((nqubits, nqubits))
data = backend.cast(data, dtype=data.dtype)
phase_encoder(data, rotation=rotation)
with pytest.raises(TypeError):
data = sampler.random(nqubits)
data = backend.cast(data, dtype=data.dtype)
phase_encoder(data, rotation=True)
with pytest.raises(ValueError):
data = sampler.random(nqubits)
data = backend.cast(data, dtype=data.dtype)
phase_encoder(data, rotation="rzz")
phases = np.random.rand(nqubits)
if rotation in ["RX", "RY"]:
functions = list(product([np.cos, np.sin], repeat=nqubits))
target = []
for row in functions:
elem = 1.0
for phase, func in zip(phases, row):
elem *= func(phase / 2)
if rotation == "RX" and func.__name__ == "sin":
elem *= -1.0j
target.append(elem)
else:
target = [np.exp(-0.5j * sum(phases))] + [0.0] * (dims - 1)
target = np.array(target, dtype=complex)
target = backend.cast(target, dtype=target.dtype)
if kind is not None:
phases = kind(phases)
state = phase_encoder(phases, rotation=rotation)
state = backend.execute_circuit(state).state()
backend.assert_allclose(state, target)
@pytest.mark.parametrize("kind", [None, list])
@pytest.mark.parametrize("architecture", ["tree", "diagonal"])
@pytest.mark.parametrize("nqubits", [8])
def test_unary_encoder(backend, nqubits, architecture, kind):
sampler = np.random.default_rng(1)
with pytest.raises(TypeError):
data = sampler.random((nqubits, nqubits))
data = backend.cast(data, dtype=data.dtype)
unary_encoder(data, architecture=architecture)
with pytest.raises(TypeError):
data = sampler.random(nqubits)
data = backend.cast(data, dtype=data.dtype)
unary_encoder(data, architecture=True)
with pytest.raises(ValueError):
data = sampler.random(nqubits)
data = backend.cast(data, dtype=data.dtype)
unary_encoder(data, architecture="semi-diagonal")
if architecture == "tree":
with pytest.raises(ValueError):
data = sampler.random(nqubits + 1)
data = backend.cast(data, dtype=data.dtype)
unary_encoder(data, architecture=architecture)
# sampling random data in interval [-1, 1]
sampler = np.random.default_rng(1)
data = 2 * sampler.random(nqubits) - 1
data = data.tolist() if kind is not None else backend.cast(data, dtype=data.dtype)
print(type(data), type(data[0]))
# if kind is not None:
# data = kind(data)
circuit = unary_encoder(data, architecture=architecture)
state = backend.execute_circuit(circuit).state()
indexes = np.flatnonzero(state)
state = np.real(state[indexes])
backend.assert_allclose(
state,
backend.cast(data, dtype=backend.dtype) / backend.calculate_norm(data, order=2),
)
@pytest.mark.parametrize("seed", [None, 10, np.random.default_rng(10)])
@pytest.mark.parametrize("nqubits", [8])
def test_unary_encoder_random_gaussian(backend, nqubits, seed):
"""Tests if encoded vector are random variables sampled from
Gaussian distribution with 0.0 mean and variance close to the norm
of the random Gaussian vector that was encoded."""
with pytest.raises(TypeError):
unary_encoder_random_gaussian("1", seed=seed)
with pytest.raises(ValueError):
unary_encoder_random_gaussian(-1, seed=seed)
with pytest.raises(ValueError):
unary_encoder_random_gaussian(3, seed=seed)
with pytest.raises(TypeError):
unary_encoder_random_gaussian(nqubits, architecture=True, seed=seed)
with pytest.raises(NotImplementedError):
unary_encoder_random_gaussian(nqubits, architecture="diagonal", seed=seed)
with pytest.raises(TypeError):
unary_encoder_random_gaussian(nqubits, seed="seed")
samples = int(1e2)
local_state = np.random.default_rng(seed) if seed in [None, 10] else seed
amplitudes = []
for _ in range(samples):
circuit = unary_encoder_random_gaussian(nqubits, seed=local_state)
state = backend.execute_circuit(circuit).state()
indexes = np.flatnonzero(state)
state = np.real(state[indexes])
amplitudes += [float(elem) for elem in list(state)]
y, x = np.histogram(amplitudes, bins=50, density=True)
x = (x[:-1] + x[1:]) / 2
params, _ = curve_fit(gaussian, x, y)
stddev = np.sqrt(-1 / (2 * params[0]))
mean = stddev**2 * params[1]
theoretical_norm = (
math.sqrt(2) * math.gamma((nqubits + 1) / 2) / math.gamma(nqubits / 2)
)
theoretical_norm = 1.0 / theoretical_norm
backend.assert_allclose(0.0, mean, atol=1e-1)
backend.assert_allclose(stddev, theoretical_norm, atol=1e-1)