Ejemplo n.º 1
0
    def test_missing_attributesquantum_instance(self):
        """Test appropriate error is raised if the quantum instance is missing."""
        pvqd = PVQD(
            self.ansatz,
            self.initial_parameters,
            optimizer=L_BFGS_B(maxiter=1),
            expectation=self.expectation,
        )
        problem = EvolutionProblem(self.hamiltonian, time=0.01)

        attrs_to_test = [
            ("optimizer", L_BFGS_B(maxiter=1)),
            ("quantum_instance", self.qasm_backend),
        ]

        for attr, value in attrs_to_test:
            with self.subTest(msg=f"missing: {attr}"):
                # set attribute to None to invalidate the setup
                setattr(pvqd, attr, None)

                with self.assertRaises(ValueError):
                    _ = pvqd.evolve(problem)

                # set the correct value again
                setattr(pvqd, attr, value)

        with self.subTest(msg="all set again"):
            result = pvqd.evolve(problem)
            self.assertIsNotNone(result.evolved_state)
Ejemplo n.º 2
0
    def test_with_aer_statevector(self):
        """Test VQE with Aer's statevector_simulator."""
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit.providers.aer import Aer
        except Exception as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return
        backend = Aer.get_backend('statevector_simulator')
        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(var_form=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)
Ejemplo n.º 3
0
    def test_with_aer_qasm_snapshot_mode(self):
        """Test the VQE using Aer's qasm_simulator snapshot mode."""
        try:
            from qiskit.providers.aer import Aer
        except Exception as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return
        backend = Aer.get_backend('qasm_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)
Ejemplo n.º 4
0
    def test_basic_aer_statevector(self):
        """Test the VQE on BasicAer's statevector simulator."""
        wavefunction = self.ryrz_wavefunction
        vqe = VQE(var_form=wavefunction,
                  optimizer=L_BFGS_B(),
                  quantum_instance=QuantumInstance(
                      BasicAer.get_backend('statevector_simulator'),
                      basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],
                      coupling_map=[[0, 1]],
                      seed_simulator=algorithm_globals.random_seed,
                      seed_transpiler=algorithm_globals.random_seed))

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

        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)
Ejemplo n.º 5
0
    def test_with_aer_qasm_snapshot_mode(self):
        """Test the VQE using Aer's qasm_simulator snapshot mode."""
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
        except Exception as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return
        backend = Aer.get_backend('qasm_simulator')
        optimizer = L_BFGS_B()
        wavefunction = self.ry_wavefunction

        vqe = VQE(self.h2_op,
                  wavefunction,
                  optimizer,
                  expectation=AerPauliExpectation())

        quantum_instance = QuantumInstance(
            backend,
            shots=1,
            seed_simulator=aqua_globals.random_seed,
            seed_transpiler=aqua_globals.random_seed)
        result = vqe.run(quantum_instance)
        self.assertAlmostEqual(result.eigenvalue.real,
                               self.h2_energy,
                               places=6)
Ejemplo n.º 6
0
    def test_basic_aer_statevector(self):
        """Test the VQE on BasicAer's statevector simulator."""
        wavefunction = self.ryrz_wavefunction
        vqe = VQE(
            ansatz=wavefunction,
            optimizer=L_BFGS_B(),
            quantum_instance=QuantumInstance(
                BasicAer.get_backend("statevector_simulator"),
                basis_gates=["u1", "u2", "u3", "cx", "id"],
                coupling_map=[[0, 1]],
                seed_simulator=algorithm_globals.random_seed,
                seed_transpiler=algorithm_globals.random_seed,
            ),
        )

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

        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)
Ejemplo n.º 7
0
    def test_minibatching_gradient_based(self):
        """Test the minibatching option with a gradient-based optimizer."""
        n_dim = 2  # dimension of each data point
        _, training_input, test_input, _ = ad_hoc_data(training_size=4,
                                                       test_size=2,
                                                       n=n_dim,
                                                       gap=0.3,
                                                       plot_data=False)
        optimizer = L_BFGS_B(maxfun=30)
        data_preparation = self.data_preparation
        wavefunction = TwoLocal(2, ['ry', 'rz'],
                                'cz',
                                reps=1,
                                insert_barriers=True)

        vqc = VQC(optimizer,
                  data_preparation,
                  wavefunction,
                  training_input,
                  test_input,
                  minibatch_size=2)
        result = vqc.run(self.statevector_simulator)

        self.log.debug(result['testing_accuracy'])
        self.assertAlmostEqual(result['testing_accuracy'], 0.75, places=3)
Ejemplo n.º 8
0
            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
    def test_warm_start(self, config):
        """Test VQC with warm_start=True."""
        opt, q_i = config

        if q_i == "statevector":
            quantum_instance = self.sv_quantum_instance
        elif q_i == "qasm":
            quantum_instance = self.qasm_quantum_instance
        else:
            quantum_instance = None

        if opt == "bfgs":
            optimizer = L_BFGS_B(maxiter=5)
        elif opt == "cobyla":
            optimizer = COBYLA(maxiter=25)
        else:
            optimizer = None

        num_inputs = 2
        feature_map = ZZFeatureMap(num_inputs)
        ansatz = RealAmplitudes(num_inputs, reps=1)

        # Construct the data.
        num_samples = 10
        # pylint: disable=invalid-name
        X = algorithm_globals.random.random((num_samples, num_inputs))
        y = 1.0 * (np.sum(X, axis=1) <= 1)
        while len(np.unique(y)) == 1:
            X = algorithm_globals.random.random((num_samples, num_inputs))
            y = 1.0 * (np.sum(X, axis=1) <= 1)
        y = np.array([y, 1 - y
                      ]).transpose()  # VQC requires one-hot encoded input.

        # Initialize the VQC.
        classifier = VQC(
            feature_map=feature_map,
            ansatz=ansatz,
            optimizer=optimizer,
            warm_start=True,
            quantum_instance=quantum_instance,
        )

        # Fit the VQC to the first half of the data.
        num_start = num_samples // 2
        classifier.fit(X[:num_start, :], y[:num_start])
        first_fit_final_point = classifier._fit_result.x

        # Fit the VQC to the second half of the data with a warm start.
        classifier.fit(X[num_start:, :], y[num_start:])
        second_fit_initial_point = classifier._initial_point

        # Check the final optimization point from the first fit was used to start the second fit.
        np.testing.assert_allclose(first_fit_final_point,
                                   second_fit_initial_point)

        # Check score.
        score = classifier.score(X, y)
        self.assertGreater(score, 0.5)
Ejemplo n.º 10
0
 def test_set_optimizer_to_none(self):
     """Tests that setting the optimizer to None results in the default behavior"""
     vqe = VQE(
         ansatz=self.ryrz_wavefunction,
         optimizer=L_BFGS_B(),
         quantum_instance=self.statevector_simulator,
     )
     vqe.optimizer = None
     self.assertIsInstance(vqe.optimizer, SLSQP)
    def _create_optimizer(self, opt: str) -> Optional[Optimizer]:
        if opt == "bfgs":
            optimizer = L_BFGS_B(maxiter=5)
        elif opt == "cobyla":
            optimizer = COBYLA(maxiter=25)
        else:
            optimizer = None

        return optimizer
    def test_classifier_with_circuit_qnn_and_cross_entropy(self, config):
        """ Test Neural Network Classifier with Circuit QNN and Cross Entropy loss."""

        opt, q_i = config

        if q_i == 'statevector':
            quantum_instance = self.sv_quantum_instance
        else:
            quantum_instance = self.qasm_quantum_instance

        if opt == 'bfgs':
            optimizer = L_BFGS_B(maxiter=5)
        else:
            optimizer = COBYLA(maxiter=25)

        loss = CrossEntropyLoss()

        num_inputs = 2
        feature_map = ZZFeatureMap(num_inputs)
        ansatz = RealAmplitudes(num_inputs, reps=1)

        # construct circuit
        qc = QuantumCircuit(num_inputs)
        qc.append(feature_map, range(2))
        qc.append(ansatz, range(2))

        # construct qnn
        def parity(x):
            return '{:b}'.format(x).count('1') % 2

        output_shape = 2
        qnn = CircuitQNN(qc,
                         input_params=feature_map.parameters,
                         weight_params=ansatz.parameters,
                         sparse=False,
                         interpret=parity,
                         output_shape=output_shape,
                         quantum_instance=quantum_instance)

        # construct classifier - note: CrossEntropy requires eval_probabilities=True!
        classifier = NeuralNetworkClassifier(qnn,
                                             optimizer=optimizer,
                                             loss=loss,
                                             one_hot=True)

        # construct data
        num_samples = 5
        X = np.random.rand(num_samples, num_inputs)  # pylint: disable=invalid-name
        y = 1.0 * (np.sum(X, axis=1) <= 1)
        y = np.array([y, 1 - y]).transpose()

        # fit to data
        classifier.fit(X, y)

        # score
        score = classifier.score(X, y)
        self.assertGreater(score, 0.5)
Ejemplo n.º 13
0
 def test_set_ansatz_to_none(self):
     """Tests that setting the ansatz to None results in the default behavior"""
     vqd = VQD(
         k=1,
         ansatz=self.ryrz_wavefunction,
         optimizer=L_BFGS_B(),
         quantum_instance=self.statevector_simulator,
     )
     vqd.ansatz = None
     self.assertIsInstance(vqd.ansatz, RealAmplitudes)
    def test_batches_with_incomplete_labels(self, config):
        """Test VQC when some batches do not include all possible labels."""
        opt, q_i = config

        if q_i == "statevector":
            quantum_instance = self.sv_quantum_instance
        elif q_i == "qasm":
            quantum_instance = self.qasm_quantum_instance
        else:
            quantum_instance = None

        if opt == "bfgs":
            optimizer = L_BFGS_B(maxiter=5)
        elif opt == "cobyla":
            optimizer = COBYLA(maxiter=25)
        else:
            optimizer = None

        num_inputs = 2
        feature_map = ZZFeatureMap(num_inputs)
        ansatz = RealAmplitudes(num_inputs, reps=1)

        # Construct the data.
        features = algorithm_globals.random.random((15, num_inputs))
        target = np.asarray([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2])
        num_classes = len(np.unique(target))

        # One-hot encode the target.
        target_onehot = np.zeros((target.size, int(target.max() + 1)))
        target_onehot[np.arange(target.size), target.astype(int)] = 1

        # Initialize the VQC.
        classifier = VQC(
            feature_map=feature_map,
            ansatz=ansatz,
            optimizer=optimizer,
            warm_start=True,
            quantum_instance=quantum_instance,
        )

        classifier._get_interpret = self.get_num_classes(
            classifier._get_interpret)

        # Fit the VQC to the first third of the data.
        classifier.fit(features[:5, :], target_onehot[:5])

        # Fit the VQC to the second third of the data with a warm start.
        classifier.fit(features[5:10, :], target_onehot[5:10])

        # Fit the VQC to the third third of the data with a warm start.
        classifier.fit(features[10:, :], target_onehot[10:])

        # Check all batches assume the correct number of classes
        self.assertTrue(
            (np.asarray(self.num_classes_by_batch) == num_classes).all())
Ejemplo n.º 15
0
 def get_solver(self, transformation):
     num_orbitals = transformation.molecule_info['num_orbitals']
     num_particles = transformation.molecule_info['num_particles']
     initial_state = HartreeFock(num_orbitals, num_particles)
     var_form = UCCSD(num_orbitals,
                      num_particles,
                      initial_state=initial_state)
     vqe = VQE(var_form=var_form,
               quantum_instance=self._quantum_instance,
               optimizer=L_BFGS_B())
     return vqe
Ejemplo n.º 16
0
    def compile_unitary(
        self,
        target_matrix: np.ndarray,
        approximate_circuit: ApproximateCircuit,
        approximating_objective: ApproximatingObjective,
        initial_point: Optional[np.ndarray] = None,
    ) -> None:
        """
        Approximately compiles a circuit represented as a unitary matrix by solving an optimization
        problem defined by ``approximating_objective`` and using ``approximate_circuit`` as a
        template for the approximate circuit.

        Args:
            target_matrix: a unitary matrix to approximate.
            approximate_circuit: a template circuit that will be filled with the parameter values
                obtained in the optimization procedure.
            approximating_objective: a definition of the optimization problem.
            initial_point: initial values of angles/parameters to start optimization from.
        """
        matrix_dim = target_matrix.shape[0]
        # check if it is actually a special unitary matrix
        target_det = np.linalg.det(target_matrix)
        if not np.isclose(target_det, 1):
            su_matrix = target_matrix / np.power(target_det, (1 / matrix_dim))
            global_phase_required = True
        else:
            su_matrix = target_matrix
            global_phase_required = False

        # set the matrix to approximate in the algorithm
        approximating_objective.target_matrix = su_matrix

        optimizer = self._optimizer or L_BFGS_B(maxiter=1000)

        if initial_point is None:
            np.random.seed(self._seed)
            initial_point = np.random.uniform(
                0, 2 * np.pi, approximating_objective.num_thetas)

        opt_result = optimizer.minimize(
            fun=approximating_objective.objective,
            x0=initial_point,
            jac=approximating_objective.gradient,
        )

        approximate_circuit.build(opt_result.x)

        approx_matrix = Operator(approximate_circuit).data

        if global_phase_required:
            alpha = np.angle(
                np.trace(np.dot(approx_matrix.conj().T, target_matrix)))
            approximate_circuit.global_phase = alpha
    def test_vqc(self, config):
        """Test VQC."""

        opt, q_i = config

        if q_i == "statevector":
            quantum_instance = self.sv_quantum_instance
        elif q_i == "qasm":
            quantum_instance = self.qasm_quantum_instance
        else:
            quantum_instance = None

        if opt == "bfgs":
            optimizer = L_BFGS_B(maxiter=5)
        elif opt == "cobyla":
            optimizer = COBYLA(maxiter=25)
        else:
            optimizer = None

        num_inputs = 2
        feature_map = ZZFeatureMap(num_inputs)
        ansatz = RealAmplitudes(num_inputs, reps=1)
        # fix the initial point
        initial_point = np.array([0.5] * ansatz.num_parameters)

        # construct classifier - note: CrossEntropy requires eval_probabilities=True!
        classifier = VQC(
            feature_map=feature_map,
            ansatz=ansatz,
            optimizer=optimizer,
            quantum_instance=quantum_instance,
            initial_point=initial_point,
        )

        # construct data
        num_samples = 5
        # pylint: disable=invalid-name
        X = algorithm_globals.random.random((num_samples, num_inputs))
        y = 1.0 * (np.sum(X, axis=1) <= 1)
        while len(np.unique(y)) == 1:
            X = algorithm_globals.random.random((num_samples, num_inputs))
            y = 1.0 * (np.sum(X, axis=1) <= 1)
        y = np.array([y,
                      1 - y]).transpose()  # VQC requires one-hot encoded input

        # fit to data
        classifier.fit(X, y)

        # score
        score = classifier.score(X, y)
        self.assertGreater(score, 0.5)
Ejemplo n.º 18
0
 def test_stable_set_vqe(self):
     """ VQE Stable set  test """
     q_i = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                           seed_simulator=algorithm_globals.random_seed,
                           seed_transpiler=algorithm_globals.random_seed)
     result = VQE(EfficientSU2(reps=3, entanglement='linear'),
                  L_BFGS_B(maxfun=6000),
                  quantum_instance=q_i).compute_minimum_eigenvalue(
                      self.qubit_op)
     x = sample_most_likely(result.eigenstate)
     self.assertAlmostEqual(result.eigenvalue, -39.5)
     self.assertAlmostEqual(result.eigenvalue + self.offset, -38.0)
     ising_sol = stable_set.get_graph_solution(x)
     np.testing.assert_array_equal(ising_sol, [1, 1, 0, 1, 1])
     self.assertEqual(stable_set.stable_set_value(x, self.w), (4.0, False))
Ejemplo n.º 19
0
    def test_statevector(self):
        """Test running the VQC on BasicAer's Statevector simulator."""
        optimizer = L_BFGS_B(maxfun=200)
        data_preparation = self.data_preparation
        wavefunction = self.ryrz_wavefunction

        vqc = VQC(optimizer, data_preparation, wavefunction,
                  self.training_data, self.testing_data)
        result = vqc.run(self.statevector_simulator)

        with self.subTest(msg='check training loss'):
            self.assertLess(result['training_loss'], 0.12)

        with self.subTest(msg='check testing accuracy'):
            self.assertEqual(result['testing_accuracy'], 0.5)
    def test_vqr(self, config):
        """Test VQR."""

        opt, q_i, has_ansatz = config

        if q_i == "statevector":
            quantum_instance = self.sv_quantum_instance
        else:
            quantum_instance = self.qasm_quantum_instance

        if opt == "bfgs":
            optimizer = L_BFGS_B(maxiter=5)
        elif opt == "cobyla":
            optimizer = COBYLA(maxiter=25)
        else:
            optimizer = None

        num_qubits = 1
        # construct simple feature map
        param_x = Parameter("x")
        feature_map = QuantumCircuit(num_qubits, name="fm")
        feature_map.ry(param_x, 0)

        if has_ansatz:
            param_y = Parameter("y")
            ansatz = QuantumCircuit(num_qubits, name="vf")
            ansatz.ry(param_y, 0)
            initial_point = np.zeros(ansatz.num_parameters)
        else:
            ansatz = None
            # we know it will be RealAmplitudes
            initial_point = np.zeros(4)

        # construct regressor
        regressor = VQR(
            feature_map=feature_map,
            ansatz=ansatz,
            optimizer=optimizer,
            quantum_instance=quantum_instance,
            initial_point=initial_point,
        )

        # fit to data
        regressor.fit(self.X, self.y)

        # score
        score = regressor.score(self.X, self.y)
        self.assertGreater(score, 0.5)
    def test_sparse_arrays(self, q_i, loss):
        """Tests classifier with sparse arrays as features and labels."""
        optimizer = L_BFGS_B(maxiter=5)
        quantum_instance = self._create_quantum_instance(q_i)
        qnn, _, num_parameters = self._create_circuit_qnn(quantum_instance)
        classifier = self._create_classifier(qnn, num_parameters, optimizer, loss, one_hot=True)

        features = scipy.sparse.csr_matrix([[0, 0], [1, 1]])
        labels = scipy.sparse.csr_matrix([[1, 0], [0, 1]])

        # fit to data
        classifier.fit(features, labels)

        # score
        score = classifier.score(features, labels)
        self.assertGreater(score, 0.5)
Ejemplo n.º 22
0
    def test_invalid_num_timestep(self):
        """Test raises if the num_timestep is not positive."""
        pvqd = PVQD(
            self.ansatz,
            self.initial_parameters,
            num_timesteps=0,
            optimizer=L_BFGS_B(),
            quantum_instance=self.sv_backend,
            expectation=self.expectation,
        )
        problem = EvolutionProblem(
            self.hamiltonian,
            time=0.01,
            aux_operators=[self.hamiltonian, self.observable])

        with self.assertRaises(ValueError):
            _ = pvqd.evolve(problem)
Ejemplo n.º 23
0
    def run(self, unitary, **options):

        # Runtime imports to avoid the overhead of these imports for
        # plugin discovery and only use them if the plugin is run/used
        from qiskit.algorithms.optimizers import L_BFGS_B
        from qiskit.transpiler.synthesis.aqc.aqc import AQC
        from qiskit.transpiler.synthesis.aqc.cnot_structures import make_cnot_network
        from qiskit.transpiler.synthesis.aqc.cnot_unit_circuit import CNOTUnitCircuit
        from qiskit.transpiler.synthesis.aqc.cnot_unit_objective import DefaultCNOTUnitObjective

        num_qubits = int(round(np.log2(unitary.shape[0])))

        config = options.get("config") or {}

        network_layout = config.get("network_layout", "spin")
        connectivity_type = config.get("connectivity_type", "full")
        depth = config.get("depth", 0)

        cnots = make_cnot_network(
            num_qubits=num_qubits,
            network_layout=network_layout,
            connectivity_type=connectivity_type,
            depth=depth,
        )

        optimizer = config.get("optimizer", L_BFGS_B(maxiter=1000))
        seed = config.get("seed")
        aqc = AQC(optimizer, seed)

        approximate_circuit = CNOTUnitCircuit(num_qubits=num_qubits,
                                              cnots=cnots)
        approximating_objective = DefaultCNOTUnitObjective(
            num_qubits=num_qubits, cnots=cnots)

        initial_point = config.get("initial_point")
        aqc.compile_unitary(
            target_matrix=unitary,
            approximate_circuit=approximate_circuit,
            approximating_objective=approximating_objective,
            initial_point=initial_point,
        )

        dag_circuit = circuit_to_dag(approximate_circuit)
        return dag_circuit
    def test_regressor_with_opflow_qnn(self, config):
        """ Test Neural Network Regressor with Opflow QNN (Two Layer QNN)."""
        opt, q_i = config

        num_qubits = 1
        # construct simple feature map
        param_x = Parameter('x')
        feature_map = QuantumCircuit(num_qubits, name='fm')
        feature_map.ry(param_x, 0)

        # construct simple feature map
        param_y = Parameter('y')
        var_form = QuantumCircuit(num_qubits, name='vf')
        var_form.ry(param_y, 0)

        if q_i == 'statevector':
            quantum_instance = self.sv_quantum_instance
        else:
            quantum_instance = self.qasm_quantum_instance

        if opt == 'bfgs':
            optimizer = L_BFGS_B(maxiter=5)
        else:
            optimizer = COBYLA(maxiter=25)

        # construct QNN
        regression_opflow_qnn = TwoLayerQNN(num_qubits,
                                            feature_map,
                                            var_form,
                                            quantum_instance=quantum_instance)

        # construct the regressor from the neural network
        regressor = NeuralNetworkRegressor(
            neural_network=regression_opflow_qnn,
            loss='l2',
            optimizer=optimizer)

        # fit to data
        regressor.fit(self.X, self.y)

        # score the result
        score = regressor.score(self.X, self.y)
        self.assertGreater(score, 0.5)
Ejemplo n.º 25
0
            def get_solver(self, problem, qubit_converter):
                q_molecule_transformed = cast(
                    QMolecule, problem.molecule_data_transformed)
                num_molecular_orbitals = q_molecule_transformed.num_molecular_orbitals
                num_particles = (q_molecule_transformed.num_alpha,
                                 q_molecule_transformed.num_beta)
                num_spin_orbitals = 2 * num_molecular_orbitals

                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._quantum_instance,
                          optimizer=L_BFGS_B())
                return vqe
Ejemplo n.º 26
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()
Ejemplo n.º 27
0
    def test_pvqd(self, hamiltonian_type, expectation_cls, gradient,
                  backend_type, num_timesteps):
        """Test a simple evolution."""
        time = 0.02

        if hamiltonian_type == "ising":
            hamiltonian = self.hamiltonian
        elif hamiltonian_type == "ising_matrix":
            hamiltonian = self.hamiltonian.to_matrix_op()
        else:  # hamiltonian_type == "pauli":
            hamiltonian = X ^ X

        # parse input arguments
        if gradient:
            optimizer = GradientDescent(maxiter=1)
        else:
            optimizer = L_BFGS_B(maxiter=1)

        backend = self.sv_backend if backend_type == "sv" else self.qasm_backend
        expectation = expectation_cls()

        # run pVQD keeping track of the energy and the magnetization
        pvqd = PVQD(
            self.ansatz,
            self.initial_parameters,
            num_timesteps=num_timesteps,
            optimizer=optimizer,
            quantum_instance=backend,
            expectation=expectation,
        )
        problem = EvolutionProblem(
            hamiltonian, time, aux_operators=[hamiltonian, self.observable])
        result = pvqd.evolve(problem)

        self.assertTrue(len(result.fidelities) == 3)
        self.assertTrue(np.all(result.times == [0.0, 0.01, 0.02]))
        self.assertTrue(np.asarray(result.observables).shape == (3, 2))
        num_parameters = self.ansatz.num_parameters
        self.assertTrue(
            len(result.parameters) == 3 and np.all([
                len(params) == num_parameters for params in result.parameters
            ]))
Ejemplo n.º 28
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)
Ejemplo n.º 29
0
 def get_solver(self, transformation):
     num_orbitals = transformation.molecule_info['num_orbitals']
     num_particles = transformation.molecule_info['num_particles']
     qubit_mapping = transformation.qubit_mapping
     two_qubit_reduction = transformation.molecule_info[
         'two_qubit_reduction']
     z2_symmetries = transformation.molecule_info['z2_symmetries']
     initial_state = HartreeFock(num_orbitals, num_particles,
                                 qubit_mapping, two_qubit_reduction,
                                 z2_symmetries.sq_list)
     var_form = UCCSD(num_orbitals=num_orbitals,
                      num_particles=num_particles,
                      initial_state=initial_state,
                      qubit_mapping=qubit_mapping,
                      two_qubit_reduction=two_qubit_reduction,
                      z2_symmetries=z2_symmetries)
     vqe = VQE(var_form=var_form,
               quantum_instance=self._quantum_instance,
               optimizer=L_BFGS_B())
     return vqe
    def test_vqc(self, config):
        """ Test VQC."""

        opt, q_i = config

        if q_i == 'statevector':
            quantum_instance = self.sv_quantum_instance
        else:
            quantum_instance = self.qasm_quantum_instance

        if opt == 'bfgs':
            optimizer = L_BFGS_B(maxiter=5)
        else:
            optimizer = COBYLA(maxiter=25)

        num_inputs = 2
        feature_map = ZZFeatureMap(num_inputs)
        ansatz = RealAmplitudes(num_inputs, reps=1)

        # construct classifier - note: CrossEntropy requires eval_probabilities=True!
        classifier = VQC(feature_map=feature_map,
                         ansatz=ansatz,
                         optimizer=optimizer,
                         quantum_instance=quantum_instance)

        # construct data
        num_samples = 5
        X = np.random.rand(num_samples, num_inputs)  # pylint: disable=invalid-name
        y = 1.0 * (np.sum(X, axis=1) <= 1)
        while len(np.unique(y)) == 1:
            X = np.random.rand(num_samples, num_inputs)  # pylint: disable=invalid-name
            y = 1.0 * (np.sum(X, axis=1) <= 1)
        y = np.array([y,
                      1 - y]).transpose()  # VQC requires one-hot encoded input

        # fit to data
        classifier.fit(X, y)

        # score
        score = classifier.score(X, y)
        self.assertGreater(score, 0.5)