Skip to content

Commit 0fb5d86

Browse files
authored
Merge pull request #1572 from qiboteam/lexicographical_order
Modify `models.encodings.hamming_weight_encoder` to upload data in the lexicographical order
2 parents 66b1a0f + cf99513 commit 0fb5d86

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/qibo/models/encodings.py

+7
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,13 @@ def hamming_weight_encoder(
371371
initial_string = np.array([1] * weight + [0] * (nqubits - weight))
372372
bitstrings, targets_and_controls = _ehrlich_algorithm(initial_string)
373373

374+
# sort data such that the encoding is performed in lexicographical order
375+
lex_order = [int(string, 2) for string in bitstrings]
376+
lex_order_sorted = np.sort(np.copy(lex_order))
377+
lex_order = [np.where(lex_order_sorted == num)[0][0] for num in lex_order]
378+
data = data[lex_order]
379+
del lex_order, lex_order_sorted
380+
374381
# Calculate all gate phases necessary to encode the amplitudes.
375382
_data = np.abs(data) if complex_data else data
376383
thetas = _generate_rbs_angles(_data, nqubits, architecture="diagonal")

tests/test_models_encodings.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ def test_unary_encoder_random_gaussian(backend, nqubits, seed):
217217
backend.assert_allclose(stddev, theoretical_norm, atol=1e-1)
218218

219219

220+
@pytest.mark.parametrize("seed", [10])
220221
@pytest.mark.parametrize("optimize_controls", [False, True])
221222
@pytest.mark.parametrize("complex_data", [False, True])
222223
@pytest.mark.parametrize("full_hwp", [False, True])
@@ -229,6 +230,7 @@ def test_hamming_weight_encoder(
229230
full_hwp,
230231
complex_data,
231232
optimize_controls,
233+
seed,
232234
):
233235
n_choose_k = int(binom(nqubits, weight))
234236
dims = 2**nqubits
@@ -237,15 +239,16 @@ def test_hamming_weight_encoder(
237239
initial_string = np.array([1] * weight + [0] * (nqubits - weight))
238240
indices = _ehrlich_algorithm(initial_string, False)
239241
indices = [int(string, 2) for string in indices]
242+
indices_lex = np.sort(np.copy(indices))
240243

241-
rng = np.random.default_rng(10)
244+
rng = np.random.default_rng(seed)
242245
data = rng.random(n_choose_k)
243246
if complex_data:
244247
data = data.astype(complex) + 1j * rng.random(n_choose_k)
245248
data /= np.linalg.norm(data)
246249

247250
target = np.zeros(dims, dtype=dtype)
248-
target[indices] = data
251+
target[indices_lex] = data
249252
target = backend.cast(target, dtype=target.dtype)
250253

251254
circuit = hamming_weight_encoder(

0 commit comments

Comments
 (0)