Пример #1
0
    def test_particle_hole(self, atom, charge=0, spin=0, basis='sto3g', hf_method=HFMethodType.RHF):
        """ particle hole test """
        try:
            driver = PySCFDriver(atom=atom,
                                 unit=UnitsType.ANGSTROM,
                                 charge=charge,
                                 spin=spin,
                                 basis=basis,
                                 hf_method=hf_method)
        except QiskitChemistryError:
            self.skipTest('PYSCF driver does not appear to be installed')

        config = '{}, charge={}, spin={}, basis={}, {}'.format(atom, charge,
                                                               spin, basis,
                                                               hf_method.value)

        molecule = driver.run()
        fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)

        ph_fer_op, ph_shift = fer_op.particle_hole_transformation([molecule.num_alpha,
                                                                   molecule.num_beta])

        # ph_shift should be the electronic part of the hartree fock energy
        self.assertAlmostEqual(-ph_shift,
                               molecule.hf_energy - molecule.nuclear_repulsion_energy, msg=config)

        # Energy in original fer_op should same as ph transformed one added with ph_shift
        jw_op = fer_op.mapping('jordan_wigner')
        result = NumPyMinimumEigensolver(jw_op).run()

        ph_jw_op = ph_fer_op.mapping('jordan_wigner')
        ph_result = NumPyMinimumEigensolver(ph_jw_op).run()

        self.assertAlmostEqual(result.eigenvalue.real,
                               ph_result.eigenvalue.real - ph_shift, msg=config)
Пример #2
0
 def test_tsp(self):
     """ TSP test """
     algo = NumPyMinimumEigensolver(self.qubit_op)
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     order = tsp.get_tsp_solution(x)
     np.testing.assert_array_equal(order, [1, 2, 0])
Пример #3
0
    def test_deprecated_qft(self):
        """Test the QPE algorithm on the deprecated QFT component."""
        qubit_op = self._dict['QUBIT_OP_SIMPLE']
        exact_eigensolver = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()
        ref_eigenval = results.eigenvalue
        ref_eigenvec = results.eigenstate
        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)

        warnings.filterwarnings('ignore', category=DeprecationWarning)
        iqft = Standard(5)
        qpe = QPE(qubit_op,
                  state_in,
                  iqft,
                  num_time_slices=1,
                  num_ancillae=5,
                  expansion_mode='suzuki',
                  expansion_order=2,
                  shallow_circuit_concat=True)

        backend = BasicAer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend,
                                           shots=100,
                                           seed_transpiler=1,
                                           seed_simulator=1)

        # run qpe
        result = qpe.run(quantum_instance)
        warnings.filterwarnings('always', category=DeprecationWarning)
        self.assertAlmostEqual(result.eigenvalue.real,
                               ref_eigenval.real,
                               delta=2e-2)
Пример #4
0
    def test_docplex_constant_and_quadratic_terms_in_object_function(self):
        """ Docplex Constant and Quadratic terms in Object function test """
        # Create an Ising Hamiltonian with docplex
        laplacian = np.array([[-3., 1., 1., 1.], [1., -2., 1., -0.],
                              [1., 1., -3., 1.], [1., -0., 1., -2.]])

        mdl = Model()
        # pylint: disable=unsubscriptable-object
        n = laplacian.shape[0]
        bias = [0] * 4
        x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(n)}
        couplers_func = mdl.sum(2 * laplacian[i, j] * (2 * x[i] - 1) *
                                (2 * x[j] - 1) for i in range(n - 1)
                                for j in range(i, n))
        bias_func = mdl.sum(float(bias[i]) * x[i] for i in range(n))
        ising_func = couplers_func + bias_func
        mdl.minimize(ising_func)
        qubit_op, offset = docplex.get_operator(mdl)

        e_e = NumPyMinimumEigensolver(qubit_op)
        result = e_e.run()

        expected_result = -22

        # Compare objective
        self.assertAlmostEqual(result.eigenvalue.real + offset,
                               expected_result)
Пример #5
0
    def test_ee(self):
        """ EE test """
        dummy_operator = MatrixOperator([[1]])
        ee = NumPyMinimumEigensolver()
        output = ee.compute_minimum_eigenvalue(self.qubit_op)

        self.assertAlmostEqual(output.eigenvalue, -1.85727503)
Пример #6
0
 def test_partition(self):
     """ Partition test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     if x[0] != 0:
         x = np.logical_not(x) * 1
     np.testing.assert_array_equal(x, [0, 1, 0])
Пример #7
0
 def test_set_packing(self):
     """ set packing test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     ising_sol = set_packing.get_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 1])
     oracle = self._brute_force()
     self.assertEqual(np.count_nonzero(ising_sol), oracle)
Пример #8
0
 def test_vertex_cover(self):
     """ Vertex Cover test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     sol = vertex_cover.get_graph_solution(x)
     np.testing.assert_array_equal(sol, [0, 0, 1])
     oracle = self._brute_force()
     self.assertEqual(np.count_nonzero(sol), oracle)
 def test_portfolio(self):
     """ portfolio test """
     algo = NumPyMinimumEigensolver(self.qubit_op)
     result = algo.run()
     selection = sample_most_likely(result.eigenstate)
     value = portfolio.portfolio_value(selection, self.muu, self.sigma,
                                       self.risk, self.budget, self.penalty)
     np.testing.assert_array_equal(selection, [0, 1, 1, 0])
     self.assertAlmostEqual(value, -0.00679917)
Пример #10
0
 def test_tsp(self):
     """ TSP test """
     algo = NumPyMinimumEigensolver(self.qubit_op)
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     # print(self.qubit_op.to_opflow().eval(result.eigenstate).adjoint().eval(result.eigenstate))
     order = tsp.get_tsp_solution(x)
     np.testing.assert_equal(tsp.tsp_value(order, self.ins.w),
                             tsp.tsp_value([1, 2, 0], self.ins.w))
    def test_mapping(self):
        """ mapping test """
        qubit_op = self.bos_op.mapping('direct', threshold=1e-5)
        algo = NumPyMinimumEigensolver(
            qubit_op,
            filter_criterion=self.bos_op.direct_mapping_filtering_criterion)
        result = algo.run()
        gs_energy = np.real(result['eigenvalue'])

        self.assertAlmostEqual(gs_energy, self.reference_energy, places=4)
Пример #12
0
 def test_graph_partition(self):
     """ Graph Partition test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     # check against the oracle
     ising_sol = graph_partition.get_graph_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 0, 1])
     oracle = self._brute_force()
     self.assertEqual(graph_partition.objective_value(x, self.w), oracle)
Пример #13
0
 def test_clique(self):
     """ Clique test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     ising_sol = clique.get_graph_solution(x)
     np.testing.assert_array_equal(ising_sol, [1, 1, 1, 1, 1])
     oracle = self._brute_force()
     self.assertEqual(clique.satisfy_or_not(ising_sol, self.w, self.k),
                      oracle)
Пример #14
0
 def test_stable_set(self):
     """ Stable set test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     self.assertAlmostEqual(result.eigenvalue.real, -29.5)
     self.assertAlmostEqual(result.eigenvalue.real + self.offset, -25.0)
     ising_sol = stable_set.get_graph_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 0, 1, 1, 1])
     self.assertEqual(stable_set.stable_set_value(x, self.w), (3.0, False))
    def test_iqpe(self, distance):
        """ iqpe test """
        self.log.debug('Testing End-to-End with IQPE on H2 with '
                       'inter-atomic distance %s.', distance)
        try:
            driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 {}'.format(distance),
                                 unit=UnitsType.ANGSTROM,
                                 charge=0,
                                 spin=0,
                                 basis='sto3g')
        except QiskitChemistryError:
            self.skipTest('PYSCF driver does not appear to be installed')
        molecule = driver.run()
        qubit_mapping = 'parity'
        fer_op = FermionicOperator(h1=molecule.one_body_integrals,
                                   h2=molecule.two_body_integrals)
        qubit_op = fer_op.mapping(map_type=qubit_mapping, threshold=1e-10)
        qubit_op = Z2Symmetries.two_qubit_reduction(qubit_op, 2)

        exact_eigensolver = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()
        reference_energy = results.eigenvalue.real
        self.log.debug('The exact ground state energy is: %s', results.eigenvalue.real)

        num_particles = molecule.num_alpha + molecule.num_beta
        two_qubit_reduction = True
        num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0)

        num_time_slices = 1
        num_iterations = 6
        state_in = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction)
        iqpe = IQPE(qubit_op, state_in, num_time_slices, num_iterations,
                    expansion_mode='suzuki', expansion_order=2,
                    shallow_circuit_concat=True)
        backend = qiskit.BasicAer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend, shots=100)

        result = iqpe.run(quantum_instance)

        self.log.debug('top result str label:     %s', result.top_measurement_label)
        self.log.debug('top result in decimal:    %s', result.top_measurement_decimal)
        self.log.debug('stretch:                  %s', result.stretch)
        self.log.debug('translation:              %s', result.translation)
        self.log.debug('final energy from QPE:    %s', result.eigenvalue.real)
        self.log.debug('reference energy:         %s', reference_energy)
        self.log.debug('ref energy (transformed): %s',
                       (reference_energy + result.translation) * result.stretch)
        self.log.debug('ref binary str label:     %s', decimal_to_binary(
            (reference_energy + result.translation) * result.stretch,
            max_num_digits=num_iterations + 3,
            fractional_part_only=True
        ))

        np.testing.assert_approx_equal(result.eigenvalue.real, reference_energy, significant=2)
    def test_iqpe(self, qubit_op, simulator, num_time_slices, num_iterations,
                  use_circuits):
        """ iqpe test """
        self.log.debug('Testing IQPE')
        qubit_op = self._dict[qubit_op]
        exact_eigensolver = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()

        ref_eigenval = results.eigenvalue
        ref_eigenvec = results.eigenstate
        self.log.debug('The exact eigenvalue is:       %s', ref_eigenval)
        self.log.debug('The corresponding eigenvector: %s', ref_eigenvec)

        if use_circuits:
            state_in = QuantumCircuit(qubit_op.num_qubits)
            state_in.initialize(ref_eigenvec.primitive.data, state_in.qubits)
        else:
            with warnings.catch_warnings():
                warnings.filterwarnings('ignore', category=DeprecationWarning)
                state_in = Custom(qubit_op.num_qubits,
                                  state_vector=ref_eigenvec)
        iqpe = IQPE(qubit_op,
                    state_in,
                    num_time_slices,
                    num_iterations,
                    expansion_mode='suzuki',
                    expansion_order=2,
                    shallow_circuit_concat=True)

        backend = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend, shots=100)

        result = iqpe.run(quantum_instance)
        self.log.debug('top result str label:         %s',
                       result.top_measurement_label)
        self.log.debug('top result in decimal:        %s',
                       result.top_measurement_decimal)
        self.log.debug('stretch:                      %s', result.stretch)
        self.log.debug('translation:                  %s', result.translation)
        self.log.debug('final eigenvalue from IQPE:   %s', result.eigenvalue)
        self.log.debug('reference eigenvalue:         %s', ref_eigenval)
        self.log.debug('ref eigenvalue (transformed): %s',
                       (ref_eigenval.real + result.translation) *
                       result.stretch)
        self.log.debug(
            'reference binary str label:   %s',
            decimal_to_binary(
                (ref_eigenval.real + result.translation) * result.stretch,
                max_num_digits=num_iterations + 3,
                fractional_part_only=True))

        np.testing.assert_approx_equal(result.eigenvalue.real,
                                       ref_eigenval.real,
                                       significant=2)
Пример #17
0
 def test_cme(self):
     """ Basic test """
     algo = NumPyMinimumEigensolver(self.qubit_op,
                                    aux_operators=self.aux_ops)
     result = algo.run()
     self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j)
     self.assertEqual(len(result.aux_operator_eigenvalues), 2)
     np.testing.assert_array_almost_equal(
         result.aux_operator_eigenvalues[0], [2, 0])
     np.testing.assert_array_almost_equal(
         result.aux_operator_eigenvalues[1], [0, 0])
Пример #18
0
    def test_qpe(self, qubit_op, simulator, num_time_slices, n_ancillae):
        """Test the QPE algorithm."""
        self.log.debug('Testing QPE')
        qubit_op = self._dict[qubit_op]
        exact_eigensolver = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()

        ref_eigenval = results.eigenvalue
        ref_eigenvec = results.eigenstate
        self.log.debug('The exact eigenvalue is:       %s', ref_eigenval)
        self.log.debug('The corresponding eigenvector: %s', ref_eigenvec)

        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)
        iqft = QFT(n_ancillae).inverse()

        qpe = QPE(qubit_op,
                  state_in,
                  iqft,
                  num_time_slices,
                  n_ancillae,
                  expansion_mode='suzuki',
                  expansion_order=2,
                  shallow_circuit_concat=True)

        backend = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend,
                                           shots=100,
                                           seed_transpiler=1,
                                           seed_simulator=1)

        # run qpe
        result = qpe.run(quantum_instance)

        # report result
        self.log.debug('top result str label:         %s',
                       result.top_measurement_label)
        self.log.debug('top result in decimal:        %s',
                       result.top_measurement_decimal)
        self.log.debug('stretch:                      %s', result.stretch)
        self.log.debug('translation:                  %s', result.translation)
        self.log.debug('final eigenvalue from QPE:    %s', result.eigenvalue)
        self.log.debug('reference eigenvalue:         %s', ref_eigenval)
        self.log.debug('ref eigenvalue (transformed): %s',
                       (ref_eigenval + result.translation) * result.stretch)
        self.log.debug(
            'reference binary str label:   %s',
            decimal_to_binary(
                (ref_eigenval.real + result.translation) * result.stretch,
                max_num_digits=n_ancillae + 3,
                fractional_part_only=True))

        self.assertAlmostEqual(result.eigenvalue.real,
                               ref_eigenval.real,
                               delta=2e-2)
Пример #19
0
 def test_exact_cover(self):
     """ Exact Cover test """
     algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[])
     result = algo.run()
     x = sample_most_likely(result.eigenstate)
     ising_sol = exact_cover.get_solution(x)
     np.testing.assert_array_equal(ising_sol, [0, 1, 1, 0])
     oracle = self._brute_force()
     self.assertEqual(
         exact_cover.check_solution_satisfiability(ising_sol,
                                                   self.list_of_subsets),
         oracle)
Пример #20
0
    def test_qpe(self, qubit_op, simulator, num_time_slices, n_ancillae):
        """ QPE test """
        self.log.debug('Testing QPE')
        tmp_qubit_op = qubit_op.copy()
        exact_eigensolver = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()

        ref_eigenval = results.eigenvalue
        ref_eigenvec = results.eigenstate
        self.log.debug('The exact eigenvalue is:       %s', ref_eigenval)
        self.log.debug('The corresponding eigenvector: %s', ref_eigenvec)

        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)
        iqft = Standard(n_ancillae)

        qpe = QPEMinimumEigensolver(qubit_op,
                                    state_in,
                                    iqft,
                                    num_time_slices,
                                    n_ancillae,
                                    expansion_mode='suzuki',
                                    expansion_order=2,
                                    shallow_circuit_concat=True)

        backend = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend, shots=100)

        # run qpe
        result = qpe.run(quantum_instance)

        # report result
        self.log.debug('top result str label:         %s',
                       result.top_measurement_label)
        self.log.debug('top result in decimal:        %s',
                       result.top_measurement_decimal)
        self.log.debug('stretch:                      %s', result.stretch)
        self.log.debug('translation:                  %s', result.translation)
        self.log.debug('final eigenvalue from QPE:    %s', result.eigenvalue)
        self.log.debug('reference eigenvalue:         %s', ref_eigenval)
        self.log.debug('ref eigenvalue (transformed): %s',
                       (ref_eigenval + result.translation) * result.stretch)
        self.log.debug(
            'reference binary str label:   %s',
            decimal_to_binary(
                (ref_eigenval.real + result.translation) * result.stretch,
                max_num_digits=n_ancillae + 3,
                fractional_part_only=True))

        np.testing.assert_approx_equal(result.eigenvalue.real,
                                       ref_eigenval.real,
                                       significant=2)
        self.assertEqual(tmp_qubit_op, qubit_op,
                         "Operator is modified after QPE.")
Пример #21
0
    def _run_knapsack(values, weights, max_weight):
        qubit_op, _ = knapsack.get_operator(values, weights, max_weight)

        algo = NumPyMinimumEigensolver(qubit_op)
        result = algo.run()
        x = sample_most_likely(result.eigenstate)

        solution = knapsack.get_solution(x, values)
        value, weight = knapsack.knapsack_value_weight(solution, values,
                                                       weights)

        return solution, value, weight
Пример #22
0
    def setUp(self):
        super().setUp()
        try:
            self.molecule = "H 0.000000 0.000000 0.735000;H 0.000000 0.000000 0.000000"
            self.driver = PySCFDriver(atom=self.molecule,
                                      unit=UnitsType.ANGSTROM,
                                      charge=0,
                                      spin=0,
                                      basis='631g')
            self.qmolecule = self.driver.run()
            self.core = Hamiltonian(transformation=TransformationType.FULL,
                                    qubit_mapping=QubitMappingType.PARITY,
                                    two_qubit_reduction=True,
                                    freeze_core=True,
                                    orbital_reduction=[])
            self.qubit_op, _ = self.core.run(self.qmolecule)

            z2_symmetries = Z2Symmetries.find_Z2_symmetries(self.qubit_op)
            tapered_ops = z2_symmetries.taper(self.qubit_op)
            smallest_eig_value = 99999999999999
            smallest_idx = -1
            for idx, _ in enumerate(tapered_ops):
                ee = NumPyMinimumEigensolver(tapered_ops[idx])
                curr_value = ee.compute_minimum_eigenvalue().eigenvalue.real
                if curr_value < smallest_eig_value:
                    smallest_eig_value = curr_value
                    smallest_idx = idx
            self.the_tapered_op = tapered_ops[smallest_idx]

            self.reference_energy_pUCCD = -1.1434447924298028
            self.reference_energy_UCCD0 = -1.1476045878481704
            self.reference_energy_UCCD0full = -1.1515491334334347
            # reference energy of UCCSD/VQE with tapering everywhere
            self.reference_energy_UCCSD = -1.1516142309717594
            # reference energy of UCCSD/VQE when no tapering on excitations is used
            self.reference_energy_UCCSD_no_tap_exc = -1.1516142309717594
            # excitations for succ
            self.reference_singlet_double_excitations = [[0, 1, 4, 5],
                                                         [0, 1, 4, 6],
                                                         [0, 1, 4, 7],
                                                         [0, 2, 4, 6],
                                                         [0, 2, 4, 7],
                                                         [0, 3, 4, 7]]
            # groups for succ_full
            self.reference_singlet_groups = [[[0, 1, 4, 5]],
                                             [[0, 1, 4, 6], [0, 2, 4, 5]],
                                             [[0, 1, 4, 7], [0, 3, 4, 5]],
                                             [[0, 2, 4, 6]],
                                             [[0, 2, 4, 7], [0, 3, 4, 6]],
                                             [[0, 3, 4, 7]]]
        except QiskitChemistryError:
            self.skipTest('PYSCF driver does not appear to be installed')
Пример #23
0
 def test_no_symmetry(self):
     """ No symmetry reduction """
     core = Hamiltonian(transformation=TransformationType.FULL,
                        qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                        two_qubit_reduction=False,
                        freeze_core=False,
                        orbital_reduction=None,
                        z2symmetry_reduction=None)
     qubit_op, aux_ops = core.run(self.qmolecule)
     self.assertEqual(qubit_op.num_qubits, 12)
     npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops)
     result = core.process_algorithm_result(npme.compute_minimum_eigenvalue())
     self._validate_result(result, False)
Пример #24
0
 def test_given_symmetry(self):
     """ Supplied symmetry reduction """
     core = Hamiltonian(transformation=TransformationType.FULL,
                        qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                        two_qubit_reduction=False,
                        freeze_core=False,
                        orbital_reduction=None,
                        z2symmetry_reduction=[1, 1, 1, 1])
     qubit_op, aux_ops = core.run(self.qmolecule)
     self.assertEqual(qubit_op.num_qubits, 8)
     npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops)
     result = core.process_algorithm_result(npme.compute_minimum_eigenvalue())
     self._validate_result(result)
     self.assertEqual(core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values, [1, 1, 1, 1])
Пример #25
0
 def test_auto_ph_freeze_core_parity_2(self):
     """ Auto symmetry reduction, with freeze core, parity and two q reduction """
     core = Hamiltonian(transformation=TransformationType.PARTICLE_HOLE,
                        qubit_mapping=QubitMappingType.PARITY,
                        two_qubit_reduction=True,
                        freeze_core=True,
                        orbital_reduction=None,
                        z2symmetry_reduction='auto')
     qubit_op, aux_ops = core.run(self.qmolecule)
     self.assertEqual(qubit_op.num_qubits, 6)
     npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops)
     result = core.process_algorithm_result(npme.compute_minimum_eigenvalue())
     self._validate_result(result)
     self.assertEqual(core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values, [1, 1])
Пример #26
0
    def test_qpe(self, qubit_op, simulator, num_time_slices, n_ancillae, use_circuit_library):
        """ QPE test """
        self.log.debug('Testing QPE')
        qubit_op = self._dict[qubit_op]
        exact_eigensolver = NumPyMinimumEigensolver(qubit_op)
        results = exact_eigensolver.run()

        ref_eigenval = results.eigenvalue
        ref_eigenvec = results.eigenstate
        self.log.debug('The exact eigenvalue is:       %s', ref_eigenval)
        self.log.debug('The corresponding eigenvector: %s', ref_eigenvec)

        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)
        if use_circuit_library:
            iqft = QFT(n_ancillae).inverse()
        else:
            # ignore deprecation warnings from QFTs
            warnings.filterwarnings(action="ignore", category=DeprecationWarning)
            iqft = Standard(n_ancillae)

        qpe = QPE(qubit_op, state_in, iqft, num_time_slices, n_ancillae,
                  expansion_mode='suzuki', expansion_order=2,
                  shallow_circuit_concat=True)

        backend = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend, shots=100)

        # run qpe
        result = qpe.run(quantum_instance)

        # report result
        self.log.debug('top result str label:         %s', result.top_measurement_label)
        self.log.debug('top result in decimal:        %s', result.top_measurement_decimal)
        self.log.debug('stretch:                      %s', result.stretch)
        self.log.debug('translation:                  %s', result.translation)
        self.log.debug('final eigenvalue from QPE:    %s', result.eigenvalue)
        self.log.debug('reference eigenvalue:         %s', ref_eigenval)
        self.log.debug('ref eigenvalue (transformed): %s',
                       (ref_eigenval + result.translation) * result.stretch)
        self.log.debug('reference binary str label:   %s', decimal_to_binary(
            (ref_eigenval.real + result.translation) * result.stretch,
            max_num_digits=n_ancillae + 3,
            fractional_part_only=True
        ))

        np.testing.assert_approx_equal(result.eigenvalue.real, ref_eigenval.real, significant=2)

        if not use_circuit_library:
            warnings.filterwarnings(action="always", category=DeprecationWarning)
    def test_cme_filter_empty(self):
        """ Test with filter always returning False """

        # define filter criterion
        # pylint: disable=unused-argument
        def criterion(x, v, a_v):
            return False

        algo = NumPyMinimumEigensolver(self.qubit_op,
                                       aux_operators=self.aux_ops,
                                       filter_criterion=criterion)
        result = algo.run()
        self.assertEqual(result.eigenvalue, None)
        self.assertEqual(result.eigenstate, None)
        self.assertEqual(result.aux_operator_eigenvalues, None)
Пример #28
0
    def test_admm_maximization(self):
        """Tests a simple maximization problem using ADMM optimizer"""
        try:
            mdl = Model('simple-max')
            c = mdl.continuous_var(lb=0, ub=10, name='c')
            x = mdl.binary_var(name='x')
            mdl.maximize(c + x * x)
            op = QuadraticProgram()
            op.from_docplex(mdl)

            admm_params = ADMMParameters()

            qubo_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver())
            # qubo_optimizer = CplexOptimizer()
            continuous_optimizer = CplexOptimizer()

            solver = ADMMOptimizer(qubo_optimizer=qubo_optimizer,
                                   continuous_optimizer=continuous_optimizer,
                                   params=admm_params)
            solution = solver.solve(op)
            self.assertIsNotNone(solution)
            self.assertIsInstance(solution, ADMMOptimizationResult)

            self.assertIsNotNone(solution.x)
            np.testing.assert_almost_equal([10, 0], solution.x, 3)
            self.assertIsNotNone(solution.fval)
            np.testing.assert_almost_equal(10, solution.fval, 3)
            self.assertIsNotNone(solution.state)
            self.assertIsInstance(solution.state, ADMMState)
        except NameError as ex:
            self.skipTest(str(ex))
Пример #29
0
    def test_recursive_min_eigen_optimizer(self):
        """Test the recursive minimum eigen optimizer."""
        try:
            filename = 'op_ip1.lp'
            # get minimum eigen solver
            min_eigen_solver = NumPyMinimumEigensolver()

            # construct minimum eigen optimizer
            min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)
            recursive_min_eigen_optimizer = RecursiveMinimumEigenOptimizer(min_eigen_optimizer,
                                                                           min_num_vars=4)

            # load optimization problem
            problem = QuadraticProgram()
            problem.read_from_lp_file(self.resource_path + filename)

            # solve problem with cplex
            cplex = CplexOptimizer()
            cplex_result = cplex.solve(problem)

            # solve problem
            result = recursive_min_eigen_optimizer.solve(problem)

            # analyze results
            self.assertAlmostEqual(cplex_result.fval, result.fval)
        except RuntimeError as ex:
            msg = str(ex)
            if 'CPLEX' in msg:
                self.skipTest(msg)
            else:
                self.fail(msg)
Пример #30
0
    def test_converter_list(self):
        """Test converter list"""
        op = QuadraticProgram()
        op.integer_var(0, 3, "x")
        op.binary_var('y')

        op.maximize(linear={'x': 1, 'y': 2})
        op.linear_constraint(linear={
            'x': 1,
            'y': 1
        },
                             sense='LE',
                             rhs=3,
                             name='xy_leq')
        min_eigen_solver = NumPyMinimumEigensolver()
        # a single converter
        qp2qubo = QuadraticProgramToQubo()
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver,
                                                    converters=qp2qubo)
        result = min_eigen_optimizer.solve(op)
        self.assertEqual(result.fval, 4)
        # a list of converters
        ineq2eq = InequalityToEquality()
        int2bin = IntegerToBinary()
        penalize = LinearEqualityToPenalty()
        converters = [ineq2eq, int2bin, penalize]
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver,
                                                    converters=converters)
        self.assertEqual(result.fval, 4)
        with self.assertRaises(TypeError):
            invalid = [qp2qubo, "invalid converter"]
            MinimumEigenOptimizer(min_eigen_solver, converters=invalid)