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

New algorithm edit #60

Merged
merged 3 commits into from
Jun 16, 2024
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
156 changes: 156 additions & 0 deletions docs/source/example_bernstein_vazirani.ipynb

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions docs/source/example_simon.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"source": [
"from qlasskit import qlassf, Qint\n",
"\n",
"\n",
"@qlassf\n",
"def f(a: Qint[4]) -> Qint[4]:\n",
" return (a >> 3) + 1"
Expand Down
1 change: 1 addition & 0 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ quantum annealers, ising machines, simulators, etc.
example_grover_factors.ipynb
example_simon.ipynb
example_deutsch_jozsa.ipynb
example_bernstein_vazirani.ipynb
example_unitary_of_f.ipynb
example_big_circuit.ipynb

Expand Down
1 change: 1 addition & 0 deletions qlasskit/algorithms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@
from .grover import Grover # noqa: F401, E402
from .simon import Simon # noqa: F401, E402
from .deutschjozsa import DeutschJozsa # noqa: F401, E402
from .bernsteinvazirani import BernsteinVazirani, secret_oracle # noqa: F401, E402
82 changes: 82 additions & 0 deletions qlasskit/algorithms/bernsteinvazirani.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Copyright 2023-2024 Davide Gessa

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import List, Tuple, Union

from ..qcircuit import QCircuit
from ..qlassfun import QlassF
from ..types import Qtype, interpret_as_qtype
from .qalgorithm import QAlgorithm


def secret_oracle(isize, secret):
"""Create an oracle embedding a secret for Bernstein-Vazirani"""
f = f"def oracle(x: Qint[{isize}]) -> bool:\n"
f += f" s=Qint{isize}({secret})\n"
f += " return ("
f += "^".join(f"(x[{i}]&s[{i}])" for i in range(isize))
f += ")"

return QlassF.from_function(f)


class BernsteinVazirani(QAlgorithm):
def __init__(
self,
f: QlassF,
):
"""
Args:
f (QlassF): our f(x) -> bool
"""
if len(f.args) != 1:
raise Exception("f should receive exactly one parameter")
if f.returns.ttype != bool:
raise Exception("f should returns bool")

self.f: QlassF = f
self.search_space_size = len(f.args[0])
self._qcircuit = QCircuit(self.f.num_qubits, name=f"deutsch_{f.name}")

self._f_circuit = self.f.circuit()

# State preparation
self._qcircuit.barrier(label="s")
for i in range(self.search_space_size):
self._qcircuit.h(i)
self._qcircuit.h(self._f_circuit["_ret"])
self._qcircuit.z(self._f_circuit["_ret"])

# Prepare and add the f
self._qcircuit.barrier(label="f")
self._qcircuit += self._f_circuit

# State preparation out
self._qcircuit.barrier(label="s")
for i in range(self.search_space_size):
self._qcircuit.h(i)

# @override
@property
def output_qubits(self) -> List[int]:
"""Returns the list of output qubits"""
len_a = len(self.f.args[0])
return list(range(len_a))

# @override
def decode_output(
self, istr: Union[str, int, List[bool]]
) -> Union[Tuple[str, int], Qtype, str]:
return interpret_as_qtype(istr, self.f.args[0].ttype, len(self.f.args[0]))
# return istr[-len(self.f.args[0]) :][::-1]
57 changes: 57 additions & 0 deletions test/algo/test_bernstein_vazirani.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Copyright 2023-2024 Davide Gessa

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

from parameterized import parameterized, parameterized_class

from qlasskit import QlassF
from qlasskit.algorithms import BernsteinVazirani, secret_oracle

from ..utils import ENABLED_COMPILERS, qiskit_measure_and_count


@parameterized_class(("compiler"), ENABLED_COMPILERS)
class TestAlgoBernsteinVazirani(unittest.TestCase):
def test_secret_oracle(self):
isize = 4
secret = 12

f = f"def oracle(x: Qint[{isize}]) -> bool:\n"
f += f" s=Qint{isize}({secret})\n"
f += " return ("
f += "^".join(f"(x[{i}]&s[{i}])" for i in range(isize))
f += ")"

qf = QlassF.from_function(f)
qf2 = secret_oracle(isize, secret)
self.assertEqual(qf.export("qasm"), qf2.export("qasm"))

@parameterized.expand(
[
(4, 14),
(4, 12),
(4, 15),
(8, 122),
]
)
def test_bernstein_vazirani_secret(self, isize, secret):
algo = BernsteinVazirani(secret_oracle(isize, secret))

qc_algo = algo.circuit().export("circuit", "qiskit")
counts = qiskit_measure_and_count(qc_algo, shots=1024)
counts_readable = algo.decode_counts(counts)

self.assertTrue(secret in counts_readable)
self.assertEqual(counts_readable[secret], 1024)
2 changes: 1 addition & 1 deletion test/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@

import sympy
from sympy.logic.boolalg import And, Not, Or, is_cnf, is_dnf, is_nnf

# from sympy.logic.boolalg import to_anf
from sympy.logic.utilities.dimacs import load

import qlasskit
from qlasskit.qcircuit import exporter_qasm
from qlasskit.qlassfun import qlassf

from qlasskit.tools import utils

dummy_script = """
Expand Down
Loading