Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify models.encodings.hamming_weight_encoder to upload data in the lexicographical order #1572

Merged
merged 4 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/qibo/models/encodings.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,13 @@ def hamming_weight_encoder(
initial_string = np.array([1] * weight + [0] * (nqubits - weight))
bitstrings, targets_and_controls = _ehrlich_algorithm(initial_string)

# sort data such that the encoding is performed in lexicographical order
lex_order = [int(string, 2) for string in bitstrings]
lex_order_sorted = np.sort(np.copy(lex_order))
lex_order = [np.where(lex_order_sorted == num)[0][0] for num in lex_order]
data = data[lex_order]
del lex_order, lex_order_sorted

# Calculate all gate phases necessary to encode the amplitudes.
_data = np.abs(data) if complex_data else data
thetas = _generate_rbs_angles(_data, nqubits, architecture="diagonal")
Expand Down
7 changes: 5 additions & 2 deletions tests/test_models_encodings.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ def test_unary_encoder_random_gaussian(backend, nqubits, seed):
backend.assert_allclose(stddev, theoretical_norm, atol=1e-1)


@pytest.mark.parametrize("seed", [10])
@pytest.mark.parametrize("optimize_controls", [False, True])
@pytest.mark.parametrize("complex_data", [False, True])
@pytest.mark.parametrize("full_hwp", [False, True])
Expand All @@ -229,6 +230,7 @@ def test_hamming_weight_encoder(
full_hwp,
complex_data,
optimize_controls,
seed,
):
n_choose_k = int(binom(nqubits, weight))
dims = 2**nqubits
Expand All @@ -237,15 +239,16 @@ def test_hamming_weight_encoder(
initial_string = np.array([1] * weight + [0] * (nqubits - weight))
indices = _ehrlich_algorithm(initial_string, False)
indices = [int(string, 2) for string in indices]
indices_lex = np.sort(np.copy(indices))

rng = np.random.default_rng(10)
rng = np.random.default_rng(seed)
data = rng.random(n_choose_k)
if complex_data:
data = data.astype(complex) + 1j * rng.random(n_choose_k)
data /= np.linalg.norm(data)

target = np.zeros(dims, dtype=dtype)
target[indices] = data
target[indices_lex] = data
target = backend.cast(target, dtype=target.dtype)

circuit = hamming_weight_encoder(
Expand Down