示例#1
0
def grover_with_custom_circuit(number_of_qibits):
    """
    This function is used to run the minimum search with grover's algorithm. It does everything but work. It creates a
    reversible boolean oracle function using the same function that the grover_with_logical_expression but for some
    reason the CustomCircuitOracle never marks anything. Sometimes it will get luck and the top measure will be the
    smallest valued index but don't let that fool you.
    :param number_of_qibits: log_2(n) of the number of indexes in N
    :return: the results of the search
    """
    qreg = QuantumRegister(number_of_qibits)
    output = QuantumRegister(number_of_qibits)
    # qc = QuantumCircuit(qreg, output)
    # qc.z([0, 1, 2, 3])
    # qc.cz(0, 3)
    # qc.h([0, 1, 2, 3])
    # for i in range(number_of_qibits):
    #     qc.h(qreg[i])
    qc = QuantumCircuit(qreg, output, name='oracle')
    circuit_oracle = CustomCircuitOracle(variable_register=qreg,
                                         output_register=output,
                                         circuit=qc,
                                         evaluate_classically_callback=f_L)
    grover = Grover(oracle=circuit_oracle)
    draw: Figure = grover.grover_operator.draw(output='mpl')
    draw.savefig('custom_circuit_grover.png')
    result = grover.run(
        QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=2048))
    return result
示例#2
0
    def _get_oracle(self, qr_key_value):
        # Build negative value oracle O.
        qr_key_value = qr_key_value or QuantumRegister(self._num_key_qubits +
                                                       self._num_value_qubits)
        oracle_bit = QuantumRegister(1, "oracle")
        oracle_circuit = QuantumCircuit(qr_key_value, oracle_bit)
        oracle_circuit.z(self._num_key_qubits)  # recognize negative values.

        def evaluate_classically(self, measurement):
            """ evaluate classical """
            value = measurement[self._num_key_qubits:self._num_key_qubits +
                                self._num_value_qubits]
            assignment = [
                (var + 1) * (int(tf) * 2 - 1)
                for tf, var in zip(measurement, range(len(measurement)))
            ]
            evaluation = value[0] == '1'
            return evaluation, assignment

        oracle = CustomCircuitOracle(
            variable_register=qr_key_value,
            output_register=oracle_bit,
            circuit=oracle_circuit,
            evaluate_classically_callback=evaluate_classically)
        return oracle
 def test_using_grover_for_error(self):
     """ using grover without providing evaluate_classically callback """
     q_v = QuantumRegister(2, name='v')
     q_o = QuantumRegister(1, name='o')
     circuit = QuantumCircuit(q_v, q_o)
     oracle = CustomCircuitOracle(variable_register=q_v, output_register=q_o, circuit=circuit)
     with self.assertRaises(AquaError):
         _ = Grover(oracle)
示例#4
0
def QiskitDJ(n):
    # takes care of creating the oracle and calling qiskit's aqua Deutsch Jozsa, for the oracle finding the value 111...111
    (oracle_circuit, ctrls, target, ancillas) = makesOracleForQiskit(n)
    classical_eval = lambda measurement: (makesClassicalEval(
        (2 << n) - 1, n, measurement))
    oracle = CustomCircuitOracle(variable_register=ctrls,
                                 output_register=target,
                                 ancillary_register=ancillas,
                                 circuit=oracle_circuit,
                                 evaluate_classically_callback=classical_eval)
    dj = DeutschJozsa(oracle, quantum_instance=None)
    return dj
示例#5
0
    def encode(self, problem: QuadraticProgram) -> \
            Tuple[Custom, CustomCircuitOracle, Dict[Union[int, Tuple[int, int]], int]]:
        """A helper function that converts a QUBO into an oracle that recognizes negative numbers.

        Args:
            problem: The problem to be solved.

        Returns:
            A state preparation operator A, an oracle O that recognizes negative numbers, and
            a dictionary representation of the function coefficients, where the key -1 represents
            the constant.
        """

        # get linear part of objective
        linear_dict = problem.objective.linear.to_dict()
        linear_coeff = np.zeros(len(problem.variables))
        for i, v in linear_dict.items():
            linear_coeff[i] = v

        # get quadratic part of objective
        quadratic_coeff = problem.objective.quadratic.to_dict()

        constant = int(problem.objective.constant)

        # Get circuit requirements from input.
        self._num_key = len(linear_coeff)

        # Get the function dictionary.
        func = self._get_function(linear_coeff, quadratic_coeff, constant)
        logger.info("Function: %s\n", func)

        # Define state preparation operator A from function.
        a_operator_circuit = self._build_operator(func)
        a_operator = Custom(a_operator_circuit.width(),
                            circuit=a_operator_circuit)

        # Get registers from the A operator circuit.
        reg_map = {}
        for reg in a_operator_circuit.qregs:
            reg_map[reg.name] = reg
        key_val = reg_map["key_value"]

        # Build negative value oracle O.
        oracle_bit = QuantumRegister(1, "oracle")
        oracle_circuit = QuantumCircuit(key_val, oracle_bit)
        oracle_circuit.z(key_val[self._num_key])  # recognize negative values.
        oracle = CustomCircuitOracle(
            variable_register=key_val,
            output_register=oracle_bit,
            circuit=oracle_circuit,
            evaluate_classically_callback=self._evaluate_classically)

        return a_operator, oracle, func
 def test_using_grover_for_ccx(self):
     """ using grover correctly (with the evaluate_classically callback provided) """
     q_v = QuantumRegister(2, name='v')
     q_o = QuantumRegister(1, name='o')
     circuit = QuantumCircuit(q_v, q_o)
     circuit.ccx(q_v[0], q_v[1], q_o[0])
     oracle = CustomCircuitOracle(variable_register=q_v, output_register=q_o, circuit=circuit,
                                  evaluate_classically_callback=lambda m: (m == '11', [1, 2]))
     algorithm = Grover(oracle)
     result = algorithm.run(
         quantum_instance=QuantumInstance(BasicAer.get_backend('qasm_simulator')))
     self.assertEqual(result['result'], [1, 2])
    def test_using_dj_with_balanced_func(self):
        """ using dj with balanced func test """
        q_v = QuantumRegister(2, name='v')
        q_o = QuantumRegister(1, name='o')
        circuit = QuantumCircuit(q_v, q_o)
        circuit.cx(q_v[0], q_o[0])

        oracle = CustomCircuitOracle(variable_register=q_v, output_register=q_o, circuit=circuit)
        algorithm = DeutschJozsa(oracle)
        result = algorithm.run(
            quantum_instance=QuantumInstance(BasicAer.get_backend('qasm_simulator')))
        self.assertEqual(result['result'], 'balanced')
示例#8
0
 def test_post_processing(self):
     """Test post_processing"""
     # For the Oracle class
     q_v = QuantumRegister(2, name='v')
     q_o = QuantumRegister(1, name='o')
     circuit = QuantumCircuit(q_v, q_o)
     circuit.ccx(q_v[0], q_v[1], q_o[0])
     oracle = CustomCircuitOracle(variable_register=q_v, output_register=q_o, circuit=circuit,
                                  evaluate_classically_callback=lambda m: (m == '11', [1, 2]))
     grover = Grover(oracle)
     self.assertListEqual(grover.post_processing("11"), [1, 2])
     # For the specified post_processing
     oracle = QuantumCircuit(2)
     oracle.cz(0, 1)
     grover = Grover(oracle,
                     post_processing=lambda bitstr: [idx for idx, x_i in enumerate(bitstr)
                                                     if x_i == '1'])
     self.assertEqual(grover.post_processing("11"), [0, 1])
     # When Not specified
     grover = Grover(oracle)
     self.assertEqual(grover.post_processing("11"), "11")
    def test_using_dj_with_constant_func(self):
        qv = QuantumRegister(2, name='v')
        qo = QuantumRegister(1, name='o')
        circuit = QuantumCircuit(qv, qo)
        circuit.x(qo[0])

        oracle = CustomCircuitOracle(variable_register=qv,
                                     output_register=qo,
                                     circuit=circuit)
        algorithm = DeutschJozsa(oracle)
        result = algorithm.run(quantum_instance=QuantumInstance(
            BasicAer.get_backend('qasm_simulator')))
        self.assertTrue(result['result'] == 'constant')
示例#10
0
def QiskitGroverCstOracle(i, n):
    # takes care of creating the oracle and calling qiskit's aqua grover
    (oracle_circuit, ctrls, target, ancillas) = makesOracleForQiskit(i, n)
    classical_eval = lambda measurement: (makesClassicalEval(
        i, n, measurement))
    oracle = CustomCircuitOracle(variable_register=ctrls,
                                 output_register=target,
                                 ancillary_register=ancillas,
                                 circuit=oracle_circuit,
                                 evaluate_classically_callback=classical_eval)
    grover = Grover(oracle,
                    init_state=None,
                    incremental=False,
                    num_iterations=int(
                        np.floor(np.pi / 4.0 * np.sqrt(pow(2, n)))),
                    mct_mode='basic',
                    quantum_instance=None)
    return grover