Beispiel #1
0
def parityCircuitCheating(cheating=False, cheatingType=0):

    if cheating:
        # Cheating operator
        c1 = cheatingMatrices()[cheatingType]
    else:
        c1 = np.identity(2)

    id_op = Operator(c1)

    truthtable = "10011001"
    oracle = TruthTableOracle(truthtable)
    or_cx = oracle.construct_circuit()
    # print(oracle.output_register)
    v = oracle.variable_register
    o = oracle.output_register

    cr1 = ClassicalRegister(3)
    cr2 = ClassicalRegister(1)

    cx_circ = QuantumCircuit(v, cr2)

    or_cx.add_register(cr1)
    cx_circ.h(v[1])
    cx_circ.cx(v[1], v[0])

    cx_circ.unitary(id_op, v[cheatingType+1:cheatingType+2], label='idop')


    total_cx = cx_circ + or_cx
    total_cx.measure(v, cr1)
    total_cx.measure(o, cr2)

    return total_cx
def create_grover(oracle_type, oracle_method):
    # Build the circuit
    if oracle_method=="log":
        algorithm = Grover(LogicalExpressionOracle(oracle_type),num_iterations=num_iterations)
        oracle_circuit = Grover(LogicalExpressionOracle(oracle_type)).construct_circuit()
    else:
        algorithm = Grover(TruthTableOracle(oracle_type),num_iterations=num_iterations)
        oracle_circuit = Grover(TruthTableOracle(oracle_type)).construct_circuit()

    display(oracle_circuit.draw(output="mpl"))
    display(algorithm)
    return(algorithm)
    def test_simon(self, simon_input, mct_mode, optimization, simulator):
        """ Simon test """
        # find the two keys that have matching values
        nbits = int(math.log(len(simon_input[0]), 2))
        vals = list(zip(*simon_input))[::-1]

        def find_pair():
            for i, val in enumerate(vals):
                for j in range(i + 1, len(vals)):
                    if val == vals[j]:
                        return i, j
            return 0, 0

        k_1, k_2 = find_pair()
        hidden = np.binary_repr(k_1 ^ k_2, nbits)

        backend = BasicAer.get_backend(simulator)
        oracle = TruthTableOracle(simon_input,
                                  optimization=optimization,
                                  mct_mode=mct_mode)
        algorithm = Simon(oracle)
        quantum_instance = QuantumInstance(backend)
        result = algorithm.run(quantum_instance=quantum_instance)
        # print(result['circuit'].draw(line_length=10000))
        self.assertEqual(result['result'], hidden)
Beispiel #4
0
def get_circuit(**kwargs):
    oracle_string = kwargs[
        "oracle"]  # input is binary String of a truth table, like '1000': A & B = 0 => f(x*) = 1

    oracle = TruthTableOracle(oracle_string)
    grover = Grover(oracle)
    grover_circuit = grover.construct_circuit(measurement=True)
    return grover_circuit
def get_circuit(**kwargs):
    oracle_string = kwargs[
        "s"]  # input is binary String of a truth table, like '1000'

    oracle = TruthTableOracle(oracle_string)
    simon = Simon(oracle)
    simon_circuit = simon.construct_circuit(measurement=True)
    return simon_circuit
Beispiel #6
0
def grover_general_truthtable_qiskit(oracle_string: str) -> QuantumCircuit:      
    from qiskit.aqua.algorithms import Grover
    from qiskit.aqua.components.oracles import TruthTableOracle

    # input is binary String of a truth table, like '1000': A & B = 0 => f(x*) = 1
    oracle = TruthTableOracle(oracle_string)
    grover = Grover(oracle)
    grover_circuit = grover.construct_circuit(measurement=True)
    return grover_circuit
Beispiel #7
0
 def test_deutschjozsa(self, dj_input, mct_mode, optimization='off'):
     backend = BasicAer.get_backend('qasm_simulator')
     oracle = TruthTableOracle(dj_input, optimization=optimization, mct_mode=mct_mode)
     algorithm = DeutschJozsa(oracle)
     result = algorithm.run(backend)
     # print(result['circuit'].draw(line_length=10000))
     if sum([int(i) for i in dj_input]) == len(dj_input) / 2:
         self.assertTrue(result['result'] == 'balanced')
     else:
         self.assertTrue(result['result'] == 'constant')
 def test_with_pass_manager(self):
     """ Test Bernstein Vazirani using PassManager """
     quantum_instance = QuantumInstance(
         BasicAer.get_backend('qasm_simulator'),
         pass_manager=level_0_pass_manager(
             PassManagerConfig(basis_gates=['cx', 'u1', 'u2', 'u3'])))
     alg = BernsteinVazirani(oracle=TruthTableOracle(bitmaps="01100110"),
                             quantum_instance=quantum_instance)
     result = alg.run()
     self.assertEqual(result['result'], '011')
Beispiel #9
0
def test_aqua_algorithm() -> None:
    backends: List[Backend] = [AerBackend(), AerStateBackend()]
    if use_qulacs:
        backends.append(QulacsBackend())
    for b in backends:
        for comp in (None, b.default_compilation_pass()):
            if use_qulacs and type(b) == QulacsBackend and comp is None:
                continue
            tb = TketBackend(b, comp)
            ora = TruthTableOracle(bitmaps="01100110")
            alg = BernsteinVazirani(oracle=ora, quantum_instance=tb)
            result = alg.run()
            assert result["result"] == "011"
            alg = DeutschJozsa(oracle=ora, quantum_instance=tb)
            result = alg.run()
            assert result["result"] == "balanced"
            ora = TruthTableOracle(bitmaps="11111111")
            alg = DeutschJozsa(oracle=ora, quantum_instance=tb)
            result = alg.run()
            assert result["result"] == "constant"
Beispiel #10
0
 def test_deutsch_jozsa(self, dj_input, mct_mode, optimization, simulator):
     """ Deutsch Jozsa test """
     backend = BasicAer.get_backend(simulator)
     oracle = TruthTableOracle(dj_input, optimization=optimization, mct_mode=mct_mode)
     algorithm = DeutschJozsa(oracle)
     quantum_instance = QuantumInstance(backend)
     result = algorithm.run(quantum_instance=quantum_instance)
     # print(result['circuit'].draw(line_length=10000))
     if sum([int(i) for i in dj_input]) == len(dj_input) / 2:
         self.assertTrue(result['result'] == 'balanced')
     else:
         self.assertTrue(result['result'] == 'constant')
Beispiel #11
0
    def test_bernsteinvazirani(self, bv_input, mct_mode, optimization='off'):
        nbits = int(math.log(len(bv_input), 2))
        # compute the ground-truth classically
        parameter = ""
        for i in reversed(range(nbits)):
            bit = bv_input[2 ** i]
            parameter += bit

        backend = get_aer_backend('qasm_simulator')
        oracle = TruthTableOracle(bv_input, optimization=optimization, mct_mode=mct_mode)
        algorithm = BernsteinVazirani(oracle)
        result = algorithm.run(backend)
        # print(result['circuit'].draw(line_length=10000))
        self.assertEqual(result['result'], parameter)
Beispiel #12
0
def parityCircuit(theta1=0, theta2=0):

    # Noise rotation matrix.
    n1 = rotationMatrix(theta1)
    n2 = rotationMatrix(theta2)
    n = np.kron(n1, n2)



    # Noise operator
    id_op = Operator(n)

    truthtable = "10011001"
    oracle = TruthTableOracle(truthtable)
    or_cx = oracle.construct_circuit()
    # print(oracle.output_register)
    v = oracle.variable_register
    o = oracle.output_register

    cr1 = ClassicalRegister(3)
    cr2 = ClassicalRegister(1)

    cx_circ = QuantumCircuit(v, cr2)

    or_cx.add_register(cr1)
    cx_circ.h(v[1])
    cx_circ.cx(v[1], v[0])

    cx_circ.unitary(id_op, v[1:3], label='idop')


    total_cx = cx_circ + or_cx
    total_cx.measure(v, cr1)
    total_cx.measure(o, cr2)

    return total_cx
def call_grover(truth_map: str, num_vertices: int, shots=1024) -> dict:
    """Call the simulation for grover's algorithm with the truth map and time its execution

    :param truth_map: The string bitmap
    :param num_vertices: Number of vertices of the graph for documentation purposes
    :return: the GroverResult item
    """
    start = time()

    oracle = TruthTableOracle(truth_map)
    grover = Grover(oracle)  # Wow that's nice that this already exists
    result = grover.run(
        QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=shots))

    end = time()
    print('Grover\'s search on n = {} vertices:\nTime elapsed: {}s\n'.format(
        num_vertices, end - start))
    return result
    def test_bernstein_vazirani(self, bv_input, mct_mode, optimization,
                                simulator):
        """ Bernstein Vazirani test """
        nbits = int(math.log(len(bv_input), 2))
        # compute the ground-truth classically
        parameter = ""
        for i in reversed(range(nbits)):
            bit = bv_input[2**i]
            parameter += bit

        backend = BasicAer.get_backend(simulator)
        oracle = TruthTableOracle(bv_input,
                                  optimization=optimization,
                                  mct_mode=mct_mode)
        algorithm = BernsteinVazirani(oracle)
        quantum_instance = QuantumInstance(backend)
        result = algorithm.run(quantum_instance=quantum_instance)
        # print(result['circuit'].draw(line_length=10000))
        self.assertEqual(result['result'], parameter)
Beispiel #15
0
def make_oracle(qcount):
    bitmaps = [''] * qcount

    for raw_value in range(2**qcount):
        value = format(raw_value, '0{}b'.format(qcount))[::-1]
    
        for index in range(qcount):
            n = neighbours3(index, value)
    
            alive_count = 1 if n[0] == '1' else 0
            alive_count += 1 if n[2] == '1' else 0
    
            if n[1] == '0' and alive_count == 2:
                bitmaps[index] += '1'
            elif n[1] == '1' and alive_count == 1:
                bitmaps[index] += '1'
            else:
                bitmaps[index] += '0'

    return TruthTableOracle(bitmaps)
Beispiel #16
0
    def test_simon(self, simon_input, mct_mode, optimization='off'):
        # find the two keys that have matching values
        nbits = int(math.log(len(simon_input[0]), 2))
        vals = list(zip(*simon_input))[::-1]

        def find_pair():
            for i in range(len(vals)):
                for j in range(i + 1, len(vals)):
                    if vals[i] == vals[j]:
                        return i, j
            return 0, 0

        k1, k2 = find_pair()
        hidden = np.binary_repr(k1 ^ k2, nbits)

        backend = get_aer_backend('qasm_simulator')
        oracle = TruthTableOracle(simon_input, optimization=optimization, mct_mode=mct_mode)
        algorithm = Simon(oracle)
        result = algorithm.run(backend)
        # print(result['circuit'].draw(line_length=10000))
        self.assertEqual(result['result'], hidden)
Beispiel #17
0
    for i in ln:
        qc.cx(q1[i], q2[i])
        qc.cx(q2[i], q1[i])
        qc.cx(q1[i], q2[i])


s = ''
dat_file = open('data.txt', 'r')
temp = dat_file.readline()
for i in range(2**n):
    temp = dat_file.readline()
    s += list(temp.split("\t"))[1][:1]
dat_file.close()

print('Creating and Extracting oracle')
oracle = TruthTableOracle(s)
vr = oracle.variable_register
vr2 = QuantumRegister(len(vr))
anc = QuantumRegister(len(vr))
otr = oracle.output_register
qc1 = QuantumCircuit(vr, vr2, anc, otr)
qc1.h(vr)
qc1.x(otr)
qc1.h(otr)
qc1.barrier()

qc = oracle.circuit

qc2 = QuantumCircuit(vr, vr2, anc, otr)
qc2.h(vr)
swap(qc2, vr, vr2, anc)
Beispiel #18
0
import qiskit
from qiskit import IBMQ
IBMQ.load_account()
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.aqua import run_algorithm
from qiskit.aqua.algorithms import DeutschJozsa
from qiskit.aqua.components.oracles import TruthTableOracle

bitstr = '11110000'
oracle = TruthTableOracle(bitstr)

oracle.circuit.draw(output='mpl')

dj = DeutschJozsa(oracle)
backend = BasicAer.get_backend('qasm_simulator')
result = dj.run(QuantumInstance(backend, shots=1024))
print('The truth table {} represents a {} function.'.format(
    bitstr, result['result']))

bitstr = '11110000'
params = {
    'problem': {
        'name': 'functionevaluation',
    },
    'algorithm': {
        'name': 'DeutschJozsa'
    },
    'oracle': {
        'name': 'TruthTableOracle',
        'bitmaps': [bitstr]