Exemplo n.º 1
0
    def test_measurement_error_mitigation_with_vqe_ignis(self, config):
        """measurement error mitigation test with vqe"""
        fitter_str, mit_pattern = config
        algorithm_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        fitter_cls = (
            CompleteMeasFitter_IG if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter_IG
        )
        backend = Aer.get_backend("aer_simulator")
        quantum_instance = QuantumInstance(
            backend=backend,
            seed_simulator=167,
            seed_transpiler=167,
            noise_model=noise_model,
            measurement_error_mitigation_cls=fitter_cls,
            mit_pattern=mit_pattern,
        )

        h2_hamiltonian = (
            -1.052373245772859 * (I ^ I)
            + 0.39793742484318045 * (I ^ Z)
            - 0.39793742484318045 * (Z ^ I)
            - 0.01128010425623538 * (Z ^ Z)
            + 0.18093119978423156 * (X ^ X)
        )
        optimizer = SPSA(maxiter=200)
        ansatz = EfficientSU2(2, reps=1)

        vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance)
        with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"):
            result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian)
        self.assertGreater(quantum_instance.time_taken, 0.0)
        quantum_instance.reset_execution_results()
        self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05)
Exemplo n.º 2
0
    def test_with_aer_statevector(self):
        """Test VQE with Aer's statevector_simulator."""
        backend = Aer.get_backend("aer_simulator_statevector")
        wavefunction = self.ry_wavefunction
        optimizer = L_BFGS_B()

        quantum_instance = QuantumInstance(
            backend,
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
        )
        vqe = VQE(
            ansatz=wavefunction,
            optimizer=optimizer,
            max_evals_grouped=1,
            quantum_instance=quantum_instance,
        )

        result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
        self.assertAlmostEqual(result.eigenvalue.real,
                               self.h2_energy,
                               places=6)
    def test_custom_pass_manager(self, backend):
        """Test quantum kernel with a custom pass manager."""

        quantum_instance = QuantumInstance(
            backend,
            shots=100,
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
            pass_manager=level_1_pass_manager(
                PassManagerConfig(basis_gates=["u3", "cx"])),
            bound_pass_manager=level_1_pass_manager(
                PassManagerConfig(basis_gates=["u3", "cx"])),
        )

        kernel = QuantumKernel(feature_map=self.feature_map,
                               quantum_instance=quantum_instance)

        svc = SVC(kernel=kernel.evaluate)
        svc.fit(self.sample_train, self.label_train)
        score = svc.score(self.sample_test, self.label_test)

        self.assertEqual(score, 0.5)
Exemplo n.º 4
0
    def test_with_aer_qasm(self):
        """Test VQE with Aer's qasm_simulator."""
        backend = Aer.get_backend("aer_simulator")
        optimizer = SPSA(maxiter=200, last_avg=5)
        wavefunction = self.ry_wavefunction

        quantum_instance = QuantumInstance(
            backend,
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
        )

        vqe = VQE(
            ansatz=wavefunction,
            optimizer=optimizer,
            expectation=PauliExpectation(),
            quantum_instance=quantum_instance,
        )

        result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)

        self.assertAlmostEqual(result.eigenvalue.real, -1.86305, places=2)
    def setUp(self):
        super().setUp()

        self.random_seed = 10598

        self.statevector_simulator = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'),
            shots=1,
            seed_simulator=self.random_seed,
            seed_transpiler=self.random_seed)

        self.feature_map = ZZFeatureMap(feature_dimension=2, reps=2)

        self.sample_train = np.asarray([[3.07876080, 1.75929189],
                                        [6.03185789, 5.27787566],
                                        [6.22035345, 2.70176968],
                                        [0.18849556, 2.82743339]])
        self.label_train = np.asarray([0, 0, 1, 1])

        self.sample_test = np.asarray([[2.199114860, 5.15221195],
                                       [0.50265482, 0.06283185]])
        self.label_test = np.asarray([0, 1])
Exemplo n.º 6
0
    def test_vqe_optimizer(self):
        """Test running same VQE twice to re-use optimizer, then switch optimizer"""
        vqe = VQE(
            optimizer=SLSQP(),
            quantum_instance=QuantumInstance(
                BasicAer.get_backend("statevector_simulator")),
        )

        def run_check():
            result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
            self.assertAlmostEqual(result.eigenvalue.real,
                                   -1.85727503,
                                   places=5)

        run_check()

        with self.subTest("Optimizer re-use"):
            run_check()

        with self.subTest("Optimizer replace"):
            vqe.optimizer = L_BFGS_B()
            run_check()
    def test_qaoa_initial_point(self, w, solutions, init_pt):
        """ Check first parameter value used is initial point as expected """
        aqua_globals.random_seed = 10598
        optimizer = COBYLA()
        qubit_op, _ = max_cut.get_operator(w)

        first_pt = []

        def cb_callback(eval_count, parameters, mean, std):
            nonlocal first_pt
            if eval_count == 1:
                first_pt = list(parameters)

        quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'),
            seed_simulator=aqua_globals.random_seed,
            seed_transpiler=aqua_globals.random_seed)
        qaoa = QAOA(optimizer,
                    initial_point=init_pt,
                    callback=cb_callback,
                    quantum_instance=quantum_instance)

        result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)

        with self.subTest('Initial Point'):
            # If None the preferred random initial point of QAOA variational form
            if init_pt is None:
                np.testing.assert_almost_equal([-0.2398, 0.3378],
                                               first_pt,
                                               decimal=4)
            else:
                self.assertListEqual(init_pt, first_pt)

        with self.subTest('Solution'):
            self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                          solutions)
Exemplo n.º 8
0
    def test_h2_bopes_sampler_with_factory(self):
        """Test BOPES Sampler with Factory"""
        quantum_instance = QuantumInstance(
            backend=qiskit.Aer.get_backend("aer_simulator_statevector"),
            seed_simulator=self.seed,
            seed_transpiler=self.seed,
        )
        # Molecule
        distance1 = partial(Molecule.absolute_distance, atom_pair=(1, 0))
        molecule = Molecule(
            geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 0.6])],
            degrees_of_freedom=[distance1],
        )

        driver = ElectronicStructureMoleculeDriver(
            molecule, driver_type=ElectronicStructureDriverType.PYSCF)
        problem = ElectronicStructureProblem(driver)
        converter = QubitConverter(ParityMapper())
        solver = GroundStateEigensolver(converter,
                                        VQEUCCFactory(quantum_instance))
        sampler = BOPESSampler(solver,
                               bootstrap=True,
                               num_bootstrap=None,
                               extrapolator=None)

        result = sampler.sample(problem, list(np.linspace(0.6, 0.8, 4)))

        ref_points = [0.6, 0.6666666666666666, 0.7333333333333334, 0.8]
        ref_energies = [
            -1.1162853926251162,
            -1.1327033478688526,
            -1.137302817836066,
            -1.1341458916990401,
        ]
        np.testing.assert_almost_equal(result.points, ref_points, decimal=3)
        np.testing.assert_almost_equal(result.energies,
                                       ref_energies,
                                       decimal=3)
Exemplo n.º 9
0
    def test_gradient_wrapper(self, backend):
        """Test the gradient wrapper for probability gradients
        dp0/da = cos(a)sin(b) / 2
        dp1/da = - cos(a)sin(b) / 2
        dp0/db = sin(a)cos(b) / 2
        dp1/db = - sin(a)cos(b) / 2
        """
        method = 'param_shift'
        a = Parameter('a')
        b = Parameter('b')
        params = [a, b]

        q = QuantumRegister(1)
        qc = QuantumCircuit(q)
        qc.h(q)
        qc.rz(params[0], q[0])
        qc.rx(params[1], q[0])

        op = CircuitStateFn(primitive=qc, coeff=1.)

        shots = 8000
        backend = BasicAer.get_backend(backend)
        q_instance = QuantumInstance(backend=backend, shots=shots)
        if method == 'fin_diff':
            np.random.seed(8)
            prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.)).gradient_wrapper(
                operator=op, bind_params=params, backend=q_instance)
        else:
            prob_grad = Gradient(grad_method=method).gradient_wrapper(operator=op,
                                                                      bind_params=params,
                                                                      backend=q_instance)
        values = [[np.pi / 4, 0], [np.pi / 4, np.pi / 4], [np.pi / 2, np.pi]]
        correct_values = [[[0, 0], [1 / (2 * np.sqrt(2)), - 1 / (2 * np.sqrt(2))]],
                          [[1 / 4, -1 / 4], [1 / 4, - 1 / 4]],
                          [[0, 0], [- 1 / 2, 1 / 2]]]
        for i, value in enumerate(values):
            result = prob_grad(value)
            np.testing.assert_array_almost_equal(result, correct_values[i], decimal=1)
Exemplo n.º 10
0
    def test_excitation_preserving(self):
        """Test the excitation preserving wavefunction on a chemistry example."""

        driver = HDF5Driver(
            self.get_resource_path('test_driver_hdf5.hdf5', 'drivers/hdf5d'))

        converter = QubitConverter(ParityMapper())

        problem = ElectronicStructureProblem(driver)

        _ = problem.second_q_ops()

        num_particles = (problem.molecule_data_transformed.num_alpha,
                         problem.molecule_data_transformed.num_beta)

        num_spin_orbitals = problem.molecule_data_transformed.num_molecular_orbitals * 2

        optimizer = SLSQP(maxiter=100)

        initial_state = HartreeFock(num_spin_orbitals, num_particles,
                                    converter)

        wavefunction = ExcitationPreserving(num_spin_orbitals)
        wavefunction.compose(initial_state, front=True, inplace=True)

        solver = VQE(ansatz=wavefunction,
                     optimizer=optimizer,
                     quantum_instance=QuantumInstance(
                         BasicAer.get_backend('statevector_simulator'),
                         seed_simulator=algorithm_globals.random_seed,
                         seed_transpiler=algorithm_globals.random_seed))

        gsc = GroundStateEigensolver(converter, solver)

        result = gsc.solve(problem)
        self.assertAlmostEqual(result.total_energies[0],
                               self.reference_energy,
                               places=4)
Exemplo n.º 11
0
    def test_custom_minimum_eigensolver(self):
        """Test custom MES"""
        class CustomFactory(VQEUCCFactory):
            """A custom MES Factory"""
            def get_solver(self, problem, qubit_converter):
                particle_number = cast(
                    ParticleNumber,
                    problem.grouped_property_transformed.get_property(
                        ParticleNumber),
                )
                num_spin_orbitals = particle_number.num_spin_orbitals
                num_particles = (particle_number.num_alpha,
                                 particle_number.num_beta)

                initial_state = HartreeFock(num_spin_orbitals, num_particles,
                                            qubit_converter)
                ansatz = UCC(
                    qubit_converter=qubit_converter,
                    num_particles=num_particles,
                    num_spin_orbitals=num_spin_orbitals,
                    excitations="d",
                    initial_state=initial_state,
                )
                vqe = VQE(
                    ansatz=ansatz,
                    quantum_instance=self.minimum_eigensolver.quantum_instance,
                    optimizer=L_BFGS_B(),
                )
                return vqe

        solver = CustomFactory(quantum_instance=QuantumInstance(
            BasicAer.get_backend("statevector_simulator")))

        calc = AdaptVQE(self.qubit_converter, solver)
        res = calc.solve(self.problem)
        self.assertAlmostEqual(res.electronic_energies[0],
                               self.expected,
                               places=6)
    def test_vqe_uvccsd_with_callback(self):
        """Test VQE UVCCSD with callback."""
        def cb_callback(nfev, parameters, energy, stddev):
            print(f"iterations {nfev}: energy: {energy}")

        optimizer = COBYLA(maxiter=5000)
        solver = VQEUVCCFactory(
            QuantumInstance(Aer.get_backend("aer_simulator_statevector")),
            optimizer=optimizer,
            callback=cb_callback,
        )
        gsc = GroundStateEigensolver(self.qubit_converter, solver)
        esc = QEOM(gsc, "sd")
        with contextlib.redirect_stdout(io.StringIO()) as out:
            results = esc.solve(self.vibrational_problem)
        for idx, energy in enumerate(self.reference_energies):
            self.assertAlmostEqual(results.computed_vibrational_energies[idx],
                                   energy,
                                   places=1)
        for idx, line in enumerate(out.getvalue().split("\n")):
            if line.strip():
                self.assertTrue(
                    line.startswith(f"iterations {idx+1}: energy: "))
Exemplo n.º 13
0
    def test_qaoa(self, w, prob, m, solutions, convert_to_matrix_op):
        """ QAOA test """
        seed = 0
        algorithm_globals.random_seed = seed
        self.log.debug('Testing %s-step QAOA with MaxCut on graph\n%s', prob,
                       w)

        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA()
        qubit_op, _ = self._get_operator(w)
        if convert_to_matrix_op:
            qubit_op = qubit_op.to_matrix_op()

        q_i = QuantumInstance(backend,
                              seed_simulator=seed,
                              seed_transpiler=seed)
        qaoa = QAOA(optimizer, prob, mixer=m, quantum_instance=q_i)

        result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
        x = self._sample_most_likely(result.eigenstate)
        graph_solution = self._get_graph_solution(x)
        self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                      solutions)
Exemplo n.º 14
0
    def test_qaoa_qc_mixer_no_parameters(self):
        """ QAOA test with a mixer as a parameterized circuit with zero parameters. """
        seed = 0
        algorithm_globals.random_seed = seed

        qubit_op, _ = self._get_operator(W1)

        num_qubits = qubit_op.num_qubits
        mixer = QuantumCircuit(num_qubits)
        # just arbitrary circuit
        mixer.rx(np.pi / 2, range(num_qubits))

        backend = BasicAer.get_backend('statevector_simulator')
        q_i = QuantumInstance(backend,
                              seed_simulator=seed,
                              seed_transpiler=seed)
        qaoa = QAOA(optimizer=COBYLA(),
                    reps=1,
                    mixer=mixer,
                    quantum_instance=q_i)
        result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
        # we just assert that we get a result, it is not meaningful.
        self.assertIsNotNone(result.eigenstate)
Exemplo n.º 15
0
def grover_with_logical_expression():
    """
    This function is used to run the minimum search with grover's algorithm with the logical expression oracle.
    This one does work sometimes.

    I noticed at one point that the inverse of the correct bits were getting marked
    i.e. if index 3(0011) was supposed to be marked, then 12(1100) was getting marked.
    I never figured out what was going on here which is the such as for 0011 to be marked as opposed to 1100.
    I dug down deep into qiskit oracle source code and found nothing that would suggest the order of the bits are
    expected to be flipped. Probably something small that I've look at 100 times and thought that it was correct.

    :param number_of_qibits: log_2(n) of the number of indexes in N
    :return: the results of the search
    """
    expression = get_boolean_functions_from_truth_table_logical_oracle()
    oracle = LogicalExpressionOracle(expression=expression,
                                     optimization=True,
                                     mct_mode='noancilla')
    grover = Grover(oracle=oracle)
    draw: Figure = grover.grover_operator.draw(output='mpl')
    draw.savefig('logical_expression_grover.png')
    return grover.run(
        QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=2048))
    def test_uccsd_hf_qUCCD0full(self):
        """ singlet full uccd test """
        optimizer = SLSQP(maxiter=100)

        initial_state = HartreeFock(self.num_spin_orbitals,
                                    self.num_particles,
                                    self.qubit_converter)

        # TODO: add `full` option
        ansatz = SUCCD(self.qubit_converter,
                       self.num_particles,
                       self.num_spin_orbitals,
                       initial_state=initial_state)

        solver = VQE(ansatz=ansatz, optimizer=optimizer,
                     quantum_instance=QuantumInstance(
                         backend=BasicAer.get_backend('statevector_simulator')))

        gsc = GroundStateEigensolver(self.qubit_converter, solver)

        result = gsc.solve(self.electronic_structure_problem)

        self.assertAlmostEqual(result.total_energies[0], self.reference_energy_UCCD0full, places=6)
Exemplo n.º 17
0
    def test_vqd_optimizer(self):
        """Test running same VQD twice to re-use optimizer, then switch optimizer"""
        vqd = VQD(
            k=2,
            optimizer=SLSQP(),
            quantum_instance=QuantumInstance(
                BasicAer.get_backend("statevector_simulator")),
        )

        def run_check():
            result = vqd.compute_eigenvalues(operator=self.h2_op)
            np.testing.assert_array_almost_equal(result.eigenvalues.real,
                                                 self.h2_energy_excited,
                                                 decimal=3)

        run_check()

        with self.subTest("Optimizer re-use"):
            run_check()

        with self.subTest("Optimizer replace"):
            vqd.optimizer = L_BFGS_B()
            run_check()
Exemplo n.º 18
0
    def test_with_aer_statevector(self):
        """Test VQD with Aer's statevector_simulator."""
        backend = Aer.get_backend("aer_simulator_statevector")
        wavefunction = self.ry_wavefunction
        optimizer = L_BFGS_B()

        quantum_instance = QuantumInstance(
            backend,
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
        )
        vqd = VQD(
            k=2,
            ansatz=wavefunction,
            optimizer=optimizer,
            max_evals_grouped=1,
            quantum_instance=quantum_instance,
        )

        result = vqd.compute_eigenvalues(operator=self.h2_op)
        np.testing.assert_array_almost_equal(result.eigenvalues.real,
                                             self.h2_energy_excited,
                                             decimal=2)
    def test_eval_op_qasm(self):
        """Regression tests against https://github.com/Qiskit/qiskit-nature/issues/53."""
        solver = VQEUCCFactory(
            optimizer=SLSQP(maxiter=100),
            expectation=PauliExpectation(),
            quantum_instance=QuantumInstance(
                backend=BasicAer.get_backend("qasm_simulator"),
                seed_simulator=algorithm_globals.random_seed,
                seed_transpiler=algorithm_globals.random_seed,
            ),
        )
        calc = GroundStateEigensolver(self.qubit_converter, solver)
        res_qasm = calc.solve(self.electronic_structure_problem)

        hamiltonian, _ = self.electronic_structure_problem.second_q_ops()
        qubit_op = self.qubit_converter.map(hamiltonian)

        ansatz = solver.get_solver(self.electronic_structure_problem,
                                   self.qubit_converter).ansatz
        circuit = ansatz.assign_parameters(res_qasm.raw_result.optimal_point)
        mean = calc.evaluate_operators(circuit, qubit_op)

        self.assertAlmostEqual(res_qasm.eigenenergies[0], mean[0].real)
    def test_uccsd_hf_aer_qasm(self):
        """uccsd hf test with Aer qasm simulator."""

        backend = qiskit.providers.aer.Aer.get_backend("aer_simulator")

        ansatz = self._prepare_uccsd_hf(self.qubit_converter)

        optimizer = SPSA(maxiter=200, last_avg=5)
        solver = VQE(
            ansatz=ansatz,
            optimizer=optimizer,
            expectation=PauliExpectation(group_paulis=False),
            quantum_instance=QuantumInstance(
                backend=backend,
                seed_simulator=algorithm_globals.random_seed,
                seed_transpiler=algorithm_globals.random_seed,
            ),
        )

        gsc = GroundStateEigensolver(self.qubit_converter, solver)

        result = gsc.solve(self.electronic_structure_problem)
        self.assertAlmostEqual(result.total_energies[0], -1.131, places=2)
Exemplo n.º 21
0
    def test_basic_aer_statevector(self):
        """Test the VQE on BasicAer's statevector simulator."""
        wavefunction = self.ryrz_wavefunction
        vqe = VQE(self.h2_op, wavefunction, L_BFGS_B())

        result = vqe.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                            basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],
                            coupling_map=[[0, 1]],
                            seed_simulator=aqua_globals.random_seed,
                            seed_transpiler=aqua_globals.random_seed))

        with self.subTest(msg='test eigenvalue'):
            self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy)

        with self.subTest(msg='test dimension of optimal point'):
            self.assertEqual(len(result.optimal_point), 16)

        with self.subTest(msg='assert cost_function_evals is set'):
            self.assertIsNotNone(result.cost_function_evals)

        with self.subTest(msg='assert optimizer_time is set'):
            self.assertIsNotNone(result.optimizer_time)
    def test_uccsd_hf_qasm(self):
        """uccsd hf test with qasm simulator."""
        qubit_converter = QubitConverter(ParityMapper())
        ansatz = self._prepare_uccsd_hf(qubit_converter)

        backend = BasicAer.get_backend("qasm_simulator")

        optimizer = SPSA(maxiter=200, last_avg=5)
        solver = VQE(
            ansatz=ansatz,
            optimizer=optimizer,
            expectation=PauliExpectation(),
            quantum_instance=QuantumInstance(
                backend=backend,
                seed_simulator=algorithm_globals.random_seed,
                seed_transpiler=algorithm_globals.random_seed,
            ),
        )

        gsc = GroundStateEigensolver(qubit_converter, solver)

        result = gsc.solve(self.electronic_structure_problem)
        self.assertAlmostEqual(result.total_energies[0], -1.138, places=2)
Exemplo n.º 23
0
    def test_vqe_qasm(self):
        """Test the VQE on QASM simulator."""
        h2_op = (
            -1.052373245772859 * (I ^ I)
            + 0.39793742484318045 * (I ^ Z)
            - 0.39793742484318045 * (Z ^ I)
            - 0.01128010425623538 * (Z ^ Z)
            + 0.18093119978423156 * (X ^ X)
        )
        optimizer = SPSA(maxiter=300, last_avg=5)
        wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
        qasm_simulator = QuantumInstance(
            self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed
        )
        vqe = VQE(
            ansatz=wavefunction,
            optimizer=optimizer,
            max_evals_grouped=1,
            quantum_instance=qasm_simulator,
        )

        result = vqe.compute_minimum_eigenvalue(operator=h2_op)
        self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05)
def main(args):

    # Load the data
    data, __ = titanic()
    X_train, y_train, X_test, y_test = parse_data_train_vqc(
        data, split_ratio=args.split_ratio)

    quantum_instance = QuantumInstance(
        Aer.get_backend('statevector_simulator'), shots=100)
    optimizer = COBYLA(maxiter=100)
    feature_map = ZZFeatureMap(feature_dimension=X_train.shape[1], reps=1)
    ansatz = RealAmplitudes(num_qubits=feature_map._num_qubits, reps=1)

    qc = QuantumCircuit(feature_map._num_qubits)
    qc.compose(feature_map, inplace=True)
    qc.compose(ansatz, inplace=True)

    qnn = CircuitQNN(circuit=qc,
                     input_params=feature_map.parameters,
                     weight_params=ansatz.parameters,
                     sparse=False,
                     sampling=False,
                     interpret=parity,
                     output_shape=len(np.unique(y_train, axis=0)),
                     gradient=None,
                     quantum_instance=quantum_instance)

    cc = NeuralNetworkClassifier(neural_network=qnn, optimizer=optimizer)

    # Train the model
    cc.fit(X_train, y_train)

    # Model accuracy
    acc_train = cc.score(X_train, y_train)
    acc_test = cc.score(X_test, y_test)
    print("Accuracy on training dataset: {}.".format(acc_train))
    print("Accuracy on testing dataset: {}.".format(acc_test))
Exemplo n.º 25
0
    def test_usage_in_vqc(self):
        """Test using the circuit the a single VQC iteration works."""

        # specify quantum instance and random seed
        algorithm_globals.random_seed = 12345
        quantum_instance = QuantumInstance(
            Aer.get_backend("aer_simulator_statevector"),
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
        )

        # construct data
        num_samples = 10
        num_inputs = 4
        X = algorithm_globals.random.random(  # pylint: disable=invalid-name
            (num_samples, num_inputs))
        y = 1.0 * (np.sum(X, axis=1) <= 2)
        while len(np.unique(y, axis=0)) == 1:
            y = 1.0 * (np.sum(X, axis=1) <= 2)
        y = np.array([y, 1 - y]).transpose()

        feature_map = RawFeatureVector(feature_dimension=num_inputs)
        ansatz = RealAmplitudes(feature_map.num_qubits, reps=1)
        # classification may fail sometimes, so let's fix initial point
        initial_point = np.array([0.5] * ansatz.num_parameters)

        vqc = VQC(
            feature_map=feature_map,
            ansatz=ansatz,
            optimizer=COBYLA(maxiter=10),
            quantum_instance=quantum_instance,
            initial_point=initial_point,
        )

        vqc.fit(X, y)
        score = vqc.score(X, y)
        self.assertGreater(score, 0.5)
Exemplo n.º 26
0
    def test_good_state(self, backend_str, expect):
        """Test with a good state function."""
        def is_good_state(bitstr):
            return bitstr[1] == '1'

        # construct the estimation problem where the second qubit is ignored
        a_op = QuantumCircuit(2)
        a_op.ry(2 * np.arcsin(np.sqrt(0.2)), 0)

        # oracle only affects first qubit
        oracle = QuantumCircuit(2)
        oracle.z(0)

        # reflect only on first qubit
        q_op = GroverOperator(oracle, a_op, reflection_qubits=[0])

        # but we measure both qubits (hence both are objective qubits)
        problem = EstimationProblem(a_op,
                                    objective_qubits=[0, 1],
                                    grover_operator=q_op,
                                    is_good_state=is_good_state)

        # construct algo
        backend = QuantumInstance(BasicAer.get_backend(backend_str),
                                  seed_simulator=2,
                                  seed_transpiler=2)
        # cannot use rescaling with a custom grover operator
        fae = FasterAmplitudeEstimation(0.01,
                                        5,
                                        rescale=False,
                                        quantum_instance=backend)

        # run the algo
        result = fae.estimate(problem)

        # assert the result is correct
        self.assertAlmostEqual(result.estimation, expect, places=5)
Exemplo n.º 27
0
    def test_change_operator_size(self):
        """ QAOA change operator size test """

        aqua_globals.random_seed = 0
        qubit_op, _ = max_cut.get_operator(
            np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]))
        q_i = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                              seed_simulator=aqua_globals.random_seed,
                              seed_transpiler=aqua_globals.random_seed)
        qaoa = QAOA(COBYLA(), 1, quantum_instance=q_i)
        result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)
        with self.subTest(msg='QAOA 4x4'):
            self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                          {'0101', '1010'})

        try:
            qubit_op, _ = max_cut.get_operator(
                np.array([
                    [0, 1, 0, 1, 0, 1],
                    [1, 0, 1, 0, 1, 0],
                    [0, 1, 0, 1, 0, 1],
                    [1, 0, 1, 0, 1, 0],
                    [0, 1, 0, 1, 0, 1],
                    [1, 0, 1, 0, 1, 0],
                ]))
        except Exception as ex:  # pylint: disable=broad-except
            self.fail("Failed to change operator. Error: '{}'".format(str(ex)))
            return

        result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)
        with self.subTest(msg='QAOA 6x6'):
            self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                          {'010101', '101010'})
Exemplo n.º 28
0
    def test_vqe_bootstrap(self):
        """Test with VQE and bootstrapping."""
        qubit_converter = QubitConverter(JordanWignerMapper())
        quantum_instance = QuantumInstance(
            backend=qiskit.providers.aer.Aer.get_backend(
                "aer_simulator_statevector"),
            seed_simulator=self.seed,
            seed_transpiler=self.seed,
        )
        solver = VQE(quantum_instance=quantum_instance)

        vqe_gse = GroundStateEigensolver(qubit_converter, solver)

        distance1 = partial(Molecule.absolute_distance, atom_pair=(1, 0))
        mol = Molecule(
            geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 0.6])],
            degrees_of_freedom=[distance1],
        )

        driver = ElectronicStructureMoleculeDriver(
            mol, driver_type=ElectronicStructureDriverType.PYSCF)
        es_problem = ElectronicStructureProblem(driver)
        points = list(np.linspace(0.6, 0.8, 4))
        bopes = BOPESSampler(vqe_gse,
                             bootstrap=True,
                             num_bootstrap=None,
                             extrapolator=None)
        result = bopes.sample(es_problem, points)
        ref_points = [0.6, 0.6666666666666666, 0.7333333333333334, 0.8]
        ref_energies = [
            -1.1162738,
            -1.1326904,
            -1.1372876,
            -1.1341292,
        ]
        np.testing.assert_almost_equal(result.points, ref_points)
        np.testing.assert_almost_equal(result.energies, ref_energies)
    def setUp(self):
        super().setUp()
        try:
            self.driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735',
                                      unit=UnitsType.ANGSTROM,
                                      charge=0,
                                      spin=0,
                                      basis='sto3g')
        except QiskitNatureError:
            self.skipTest('PYSCF driver does not appear to be installed')

        self.reference_energy = -1.137306

        self.transformation = \
            FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER)

        self.seed = 50
        self.quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'),
            shots=1,
            seed_simulator=self.seed,
            seed_transpiler=self.seed)

        self._vqe_uccsd_factory = VQEUCCSDFactory(self.quantum_instance)
Exemplo n.º 30
0
    def test_with_aer_qasm_snapshot_mode(self):
        """Test the VQE using Aer's qasm_simulator snapshot mode."""

        backend = Aer.get_backend("aer_simulator")
        optimizer = L_BFGS_B()
        wavefunction = self.ry_wavefunction

        quantum_instance = QuantumInstance(
            backend,
            shots=1,
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
        )
        vqe = VQE(
            ansatz=wavefunction,
            optimizer=optimizer,
            expectation=AerPauliExpectation(),
            quantum_instance=quantum_instance,
        )

        result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
        self.assertAlmostEqual(result.eigenvalue.real,
                               self.h2_energy,
                               places=6)