示例#1
0
    def test_ibmq_grouped_pauli_expectation(self):
        """ pauli expect op vector state vector test """
        from qiskit import IBMQ
        p = IBMQ.load_account()
        backend = p.get_backend('ibmq_qasm_simulator')
        q_instance = QuantumInstance(backend, seed_simulator=self.seed, seed_transpiler=self.seed)

        paulis_op = ListOp([X, Y, Z, I])
        states_op = ListOp([One, Zero, Plus, Minus])

        valids = [[+0, 0, 1, -1],
                  [+0, 0, 0, 0],
                  [-1, 1, 0, -0],
                  [+1, 1, 1, 1]]
        converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
        sampled = CircuitSampler(q_instance).convert(converted_meas)
        np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1)
示例#2
0
    def test_uvcc_vscf(self):
        """ uvcc vscf test """

        co2_2modes_2modals_2body = [[[[[0, 0, 0]], 320.8467332810141],
                                     [[[0, 1, 1]], 1760.878530705873],
                                     [[[1, 0, 0]], 342.8218290247543],
                                     [[[1, 1, 1]], 1032.396323618631]],
                                    [[[[0, 0, 0], [1, 0, 0]], -57.34003649795117],
                                     [[[0, 0, 1], [1, 0, 0]], -56.33205925807966],
                                     [[[0, 1, 0], [1, 0, 0]], -56.33205925807966],
                                     [[[0, 1, 1], [1, 0, 0]], -60.13032761856809],
                                     [[[0, 0, 0], [1, 0, 1]], -65.09576309934431],
                                     [[[0, 0, 1], [1, 0, 1]], -62.2363839133389],
                                     [[[0, 1, 0], [1, 0, 1]], -62.2363839133389],
                                     [[[0, 1, 1], [1, 0, 1]], -121.5533969109279],
                                     [[[0, 0, 0], [1, 1, 0]], -65.09576309934431],
                                     [[[0, 0, 1], [1, 1, 0]], -62.2363839133389],
                                     [[[0, 1, 0], [1, 1, 0]], -62.2363839133389],
                                     [[[0, 1, 1], [1, 1, 0]], -121.5533969109279],
                                     [[[0, 0, 0], [1, 1, 1]], -170.744837386338],
                                     [[[0, 0, 1], [1, 1, 1]], -167.7433236025723],
                                     [[[0, 1, 0], [1, 1, 1]], -167.7433236025723],
                                     [[[0, 1, 1], [1, 1, 1]], -179.0536532281924]]]

        basis = [2, 2]

        bosonic_op = BosonicOperator(co2_2modes_2modals_2body, basis)
        qubit_op = bosonic_op.mapping('direct', threshold=1e-5)

        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            init_state = VSCF(basis)

        num_qubits = sum(basis)
        uvcc_varform = UVCC(num_qubits, basis, [0, 1], initial_state=init_state)

        q_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                                     seed_transpiler=90, seed_simulator=12)
        optimizer = COBYLA(maxiter=1000)

        algo = VQE(uvcc_varform, optimizer=optimizer, quantum_instance=q_instance)
        vqe_result = algo.compute_minimum_eigenvalue(qubit_op)

        energy = vqe_result['optimal_value']

        self.assertAlmostEqual(energy, self.reference_energy, places=4)
    def test_vertex_cover_vqe(self):
        """ Vertex Cover VQE test """
        aqua_globals.random_seed = self.seed

        q_i = QuantumInstance(BasicAer.get_backend('qasm_simulator'),
                              seed_simulator=aqua_globals.random_seed,
                              seed_transpiler=aqua_globals.random_seed)
        result = VQE(EfficientSU2(reps=3),
                     SPSA(maxiter=200),
                     max_evals_grouped=2,
                     quantum_instance=q_i).compute_minimum_eigenvalue(
                         operator=self.qubit_op)

        x = sample_most_likely(result.eigenstate)
        sol = vertex_cover.get_graph_solution(x)
        oracle = self._brute_force()
        self.assertEqual(np.count_nonzero(sol), oracle)
    def test_uccsd_hf(self):
        """ uccsd hf test """
        ansatz = self._prepare_uccsd_hf(self.qubit_converter)

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

        gsc = GroundStateEigensolver(self.qubit_converter, solver)

        result = gsc.solve(self.electronic_structure_problem)

        self.assertAlmostEqual(result.total_energies[0],
                               self.reference_energy,
                               places=6)
示例#5
0
 def test_with_gradient(self, optimizer):
     """Test VQE using Gradient()."""
     quantum_instance = QuantumInstance(
         backend=Aer.get_backend("qasm_simulator"),
         shots=1,
         seed_simulator=algorithm_globals.random_seed,
         seed_transpiler=algorithm_globals.random_seed,
     )
     vqe = VQE(
         ansatz=self.ry_wavefunction,
         optimizer=optimizer,
         gradient=Gradient(),
         expectation=AerPauliExpectation(),
         quantum_instance=quantum_instance,
         max_evals_grouped=1000,
     )
     vqe.compute_minimum_eigenvalue(operator=self.h2_op)
 def test_clique_vqe(self):
     """ VQE Clique test """
     algorithm_globals.random_seed = 10598
     q_i = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                           seed_simulator=algorithm_globals.random_seed,
                           seed_transpiler=algorithm_globals.random_seed)
     result = VQE(RealAmplitudes(reps=5, entanglement='linear'),
                  COBYLA(),
                  max_evals_grouped=2,
                  quantum_instance=q_i).compute_minimum_eigenvalue(
                      operator=self.qubit_op)
     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)
示例#7
0
    def setUp(self) -> None:
        super().setUp()
        try:
            from qiskit import Aer

            self.seed = 97
            self.backend = Aer.get_backend('qasm_simulator')
            q_instance = QuantumInstance(self.backend,
                                         seed_simulator=self.seed,
                                         seed_transpiler=self.seed)
            self.sampler = CircuitSampler(q_instance, attach_results=True)
            self.expect = AerPauliExpectation()
        except Exception as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return
    def test_int_values(self):
        """test AQGD with int values passed as eta and momentum."""
        q_instance = QuantumInstance(
            Aer.get_backend("aer_simulator_statevector"),
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
        )

        aqgd = AQGD(maxiter=1000, eta=1, momentum=0)
        vqe = VQE(
            ansatz=RealAmplitudes(),
            optimizer=aqgd,
            gradient=Gradient("lin_comb"),
            quantum_instance=q_instance,
        )
        result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
        self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=3)
示例#9
0
 def test_vqe_uvccsd_factory(self):
     """Test with VQE plus UVCCSD"""
     optimizer = COBYLA(maxiter=5000)
     quantum_instance = QuantumInstance(
         backend=qiskit.BasicAer.get_backend("statevector_simulator"),
         seed_simulator=algorithm_globals.random_seed,
         seed_transpiler=algorithm_globals.random_seed,
     )
     solver = VQEUVCCFactory(quantum_instance=quantum_instance,
                             optimizer=optimizer)
     gsc = GroundStateEigensolver(self.qubit_converter, solver)
     esc = QEOM(gsc, "sd")
     results = esc.solve(self.vibrational_problem)
     for idx, energy in enumerate(self.reference_energies):
         self.assertAlmostEqual(results.computed_vibrational_energies[idx],
                                energy,
                                places=1)
示例#10
0
    def test_aux_ops_reusability(self):
        """ Test that the auxiliary operators can be reused """
        # Regression test against #1475
        solver = VQEUCCFactory(
            QuantumInstance(BasicAer.get_backend('statevector_simulator')))
        calc = AdaptVQE(self.qubit_converter, solver)

        modes = 4
        h_1 = np.eye(modes, dtype=complex)
        h_2 = np.zeros((modes, modes, modes, modes))
        aux_ops = [build_ferm_op_from_ints(h_1, h_2)]
        aux_ops_copy = copy.deepcopy(aux_ops)

        _ = calc.solve(self.problem)
        assert all(
            frozenset(a.to_list()) == frozenset(b.to_list())
            for a, b in zip(aux_ops, aux_ops_copy))
    def test_simple(self):
        """test AQGD optimizer with the parameters as single values."""
        q_instance = QuantumInstance(
            Aer.get_backend("aer_simulator_statevector"),
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
        )

        aqgd = AQGD(momentum=0.0)
        vqe = VQE(
            ansatz=RealAmplitudes(),
            optimizer=aqgd,
            gradient=Gradient("fin_diff"),
            quantum_instance=q_instance,
        )
        result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
        self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=3)
示例#12
0
    def _set_quantum_instance(
        self,
        quantum_instance: Optional[Union[QuantumInstance, Backend]],
        output_shape: Union[int, Tuple[int, ...]],
        interpret: Optional[Callable[[int], Union[int, Tuple[int, ...]]]],
    ) -> None:
        """
        Internal method to set a quantum instance and compute/initialize internal properties such
        as an interpret function, output shape and a sampler.

        Args:
            quantum_instance: A quantum instance to set.
            output_shape: An output shape of the custom interpretation.
            interpret: A callable that maps the measured integer to another unsigned integer or
                tuple of unsigned integers.
        """
        if isinstance(quantum_instance, Backend):
            quantum_instance = QuantumInstance(quantum_instance)
        self._quantum_instance = quantum_instance

        if self._quantum_instance is not None:
            # add measurements in case none are given
            if self._quantum_instance.is_statevector:
                if len(self._circuit.clbits) > 0:
                    self._circuit.remove_final_measurements()
            elif len(self._circuit.clbits) == 0:
                self._circuit.measure_all()

            # set interpret and compute output shape
            self.set_interpret(interpret, output_shape)

            # prepare sampler
            self._sampler = CircuitSampler(self._quantum_instance, param_qobj=False, caching="all")

            # transpile the QNN circuit
            try:
                self._circuit = self._quantum_instance.transpile(
                    self._circuit, pass_manager=self._quantum_instance.unbound_pass_manager
                )[0]
                self._circuit_transpiled = True
            except QiskitError:
                # likely it is caused by RawFeatureVector, we just ignore this error and
                # transpile circuits when it is required.
                self._circuit_transpiled = False
        else:
            self._output_shape = output_shape
    def __init__(self, h, w, outputs):
        super(DQN, self).__init__()
        # We did a lot of experimentation with model sizes and types, so we decided to leave some
        # of our attempts here
        #1
        # self.conv1 = nn.Conv2d(1, 16, kernel_size=5, stride=2)
        # self.bn1 = nn.BatchNorm2d(16)
        # self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2)
        # self.bn2 = nn.BatchNorm2d(32)
        # self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)
        # self.bn3 = nn.BatchNorm2d(32)

        #2
        # # Number of Linear input connections depends on output of conv2d layers
        # # and therefore the input image size, so compute it.
        # def conv2d_size_out(size, kernel_size = 5, stride = 2):
        #     return (size - (kernel_size - 1) - 1) // stride  + 1
        # convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w)))
        # convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h)))
        # linear_input_size = convw * convh * 32

        #3
        # self.conv1 = nn.Conv2d(1, 128, kernel_size=2, stride=1, padding=1)
        # self.bn1 = nn.BatchNorm2d(128)
        # self.conv2 = nn.Conv2d(128, 256, kernel_size=5, stride=1, padding=1)
        # self.bn2 = nn.BatchNorm2d(256)
        # self.fcl1 = nn.Linear(12544,5000)
        # self.fcl2 = nn.Linear(5000, 64)
        qi = QuantumInstance(Aer.get_backend('statevector_simulator'))

        feature_map = ZZFeatureMap(4)
        ansatz = RealAmplitudes(4, reps=1)
        qnn = TwoLayerQNN(4,
                          feature_map,
                          ansatz,
                          exp_val=AerPauliExpectation(),
                          quantum_instance=qi)

        #4
        # Our final network choice. It is wide enough to capture a lot of detail but not too
        # large to have problems with vanishing gradients on such a small sample size
        self.conv1 = nn.Conv2d(1, 256, kernel_size=2, stride=1, padding=1)
        self.bn1 = nn.BatchNorm2d(256)
        self.fcl1 = nn.Linear(20736, 10000)
        self.fcl2 = nn.Linear(10000, 4)
        self.qnn = TorchConnector(qnn)
示例#14
0
    def test_gradient_wrapper(self, backend_type):
        """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.0)

        shots = 8000
        backend = BasicAer.get_backend(backend_type)
        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.0)).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)
            if backend_type == "qasm_simulator":  # sparse result
                result = [result[0].toarray(), result[1].toarray()]

            self.assertTrue(np.allclose(result[0], correct_values[i][0], atol=0.1))
            self.assertTrue(np.allclose(result[1], correct_values[i][1], atol=0.1))
示例#15
0
 def test_exact_cover_vqe(self):
     """ Exact Cover VQE test """
     algorithm_globals.random_seed = 10598
     q_i = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                           seed_simulator=algorithm_globals.random_seed,
                           seed_transpiler=algorithm_globals.random_seed)
     result = VQE(EfficientSU2(self.qubit_op.num_qubits, reps=5),
                  COBYLA(),
                  max_evals_grouped=2,
                  quantum_instance=q_i).compute_minimum_eigenvalue(
                      operator=self.qubit_op)
     x = sample_most_likely(result.eigenstate)
     ising_sol = exact_cover.get_solution(x)
     oracle = self._brute_force()
     self.assertEqual(
         exact_cover.check_solution_satisfiability(ising_sol,
                                                   self.list_of_subsets),
         oracle)
    def test_uccsd_hf_aer_qasm_snapshot(self):
        """ uccsd hf test with Aer qasm_simulator snapshot. """
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
            backend = Aer.get_backend('qasm_simulator')
        except ImportError as ex:  # pylint: disable=broad-except
            self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
            return
        optimizer = SPSA(maxiter=200, last_avg=5)
        solver = VQE(var_form=self.var_form, optimizer=optimizer,
                     expectation=AerPauliExpectation(),
                     quantum_instance=QuantumInstance(backend=backend))

        gsc = GroundStateEigensolver(self.fermionic_transformation, solver)

        result = gsc.solve(self.driver)
        self.assertAlmostEqual(result.total_energies[0], self.reference_energy, places=3)
示例#17
0
    def __init__(
        self,
        num_iterations: int,
        quantum_instance: Optional[Union[QuantumInstance, Backend]] = None,
    ) -> None:
        """Args:
          num_iterations: The number of iterations (rounds) of the phase estimation to run.
          quantum_instance: The quantum instance on which the circuit will be run.

        Raises:
          ValueError: if num_iterations is not greater than zero.
        """
        if isinstance(quantum_instance, Backend):
            quantum_instance = QuantumInstance(quantum_instance)
        self._quantum_instance = quantum_instance
        if num_iterations <= 0:
            raise ValueError("`num_iterations` must be greater than zero.")
        self._num_iterations = num_iterations
    def test_vqe_ucc_factory_with_mp2(self):
        """Test when using MP2InitialPoint to generate the initial point."""

        informed_start = MP2InitialPoint()

        solver = VQEUCCFactory(
            quantum_instance=QuantumInstance(
                BasicAer.get_backend("statevector_simulator")),
            initial_point=informed_start,
        )
        calc = GroundStateEigensolver(self.qubit_converter, solver)
        res = calc.solve(self.electronic_structure_problem)

        np.testing.assert_array_almost_equal(
            solver.initial_point.to_numpy_array(), [0.0, 0.0, -0.07197145])
        self.assertAlmostEqual(res.total_energies[0],
                               self.reference_energy,
                               places=6)
    def test_vqe_uccsd_with_callback(self):
        """Test VQE UCCSD with callback."""

        def callback(nfev, parameters, energy, stddev):
            # pylint: disable=unused-argument
            print(f"iterations {nfev}: energy: {energy}")

        solver = VQEUCCFactory(
            quantum_instance=QuantumInstance(BasicAer.get_backend("statevector_simulator")),
            callback=callback,
        )
        calc = GroundStateEigensolver(self.qubit_converter, solver)
        with contextlib.redirect_stdout(io.StringIO()) as out:
            res = calc.solve(self.electronic_structure_problem)
        self.assertAlmostEqual(res.total_energies[0], self.reference_energy, places=6)
        for idx, line in enumerate(out.getvalue().split("\n")):
            if line.strip():
                self.assertTrue(line.startswith(f"iterations {idx+1}: energy: "))
示例#20
0
    def test_LiH(self):
        """Lih test"""
        driver = PySCFDriver(
            atom="Li .0 .0 .0; H .0 .0 1.6",
            unit=UnitsType.ANGSTROM,
            basis="sto3g",
        )
        transformer = ActiveSpaceTransformer(num_electrons=2,
                                             num_molecular_orbitals=3)
        problem = ElectronicStructureProblem(driver, [transformer])

        solver = VQEUCCFactory(quantum_instance=QuantumInstance(
            BasicAer.get_backend("statevector_simulator")))
        calc = AdaptVQE(self.qubit_converter, solver)
        res = calc.solve(problem)
        self.assertAlmostEqual(res.electronic_energies[0],
                               -8.855126478,
                               places=6)
示例#21
0
    def test_2step_transpile(self):
        """Test the two-step transpiler pass."""
        # count how often the pass for parameterized circuits is called
        pre_counter = LogPass("pre_passmanager")
        pre_pass = PassManager(pre_counter)
        config = PassManagerConfig(basis_gates=["u3", "cx"])
        pre_pass += level_1_pass_manager(config)

        # ... and the pass for bound circuits
        bound_counter = LogPass("bound_pass_manager")
        bound_pass = PassManager(bound_counter)

        quantum_instance = QuantumInstance(
            backend=BasicAer.get_backend("statevector_simulator"),
            basis_gates=["u3", "cx"],
            pass_manager=pre_pass,
            bound_pass_manager=bound_pass,
        )

        optimizer = SPSA(maxiter=5, learning_rate=0.01, perturbation=0.01)

        vqe = VQE(optimizer=optimizer, quantum_instance=quantum_instance)
        _ = vqe.compute_minimum_eigenvalue(Z)

        with self.assertLogs(logger, level="INFO") as cm:
            _ = vqe.compute_minimum_eigenvalue(Z)

        expected = [
            "pre_passmanager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "bound_pass_manager",
            "pre_passmanager",
            "bound_pass_manager",
        ]
        self.assertEqual([record.message for record in cm.records], expected)
    def test_readme_sample(self):
        """ readme sample test """

        # pylint: disable=import-outside-toplevel,redefined-builtin

        def print(*args):
            """ overloads print to log values """
            if args:
                self.log.debug(args[0], *args[1:])

        # --- Exact copy of sample code ----------------------------------------

        from qiskit import BasicAer
        from qiskit.utils import QuantumInstance, algorithm_globals
        from qiskit.algorithms.optimizers import COBYLA
        from qiskit.circuit.library import TwoLocal
        from qiskit_machine_learning.algorithms import VQC
        from qiskit_machine_learning.datasets import wine
        from qiskit_machine_learning.circuit.library import RawFeatureVector

        seed = 1376
        algorithm_globals.random_seed = seed

        # Use Wine data set for training and test data
        feature_dim = 4  # dimension of each data point
        _, training_input, test_input, _ = wine(training_size=12,
                                                test_size=4,
                                                n=feature_dim)

        feature_map = RawFeatureVector(feature_dimension=feature_dim)
        vqc = VQC(COBYLA(maxiter=100), feature_map,
                  TwoLocal(feature_map.num_qubits, ['ry', 'rz'], 'cz', reps=3),
                  training_input, test_input)
        result = vqc.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                            shots=1024,
                            seed_simulator=seed,
                            seed_transpiler=seed))

        print('Testing accuracy: {:0.2f}'.format(result['testing_accuracy']))

        # ----------------------------------------------------------------------

        self.assertGreater(result['testing_accuracy'], 0.8)
示例#23
0
    def test_h2_bopes_sampler_qeom(self):
        """Test BOPES Sampler on H2"""
        # Molecule
        dof = partial(Molecule.absolute_distance, atom_pair=(1, 0))
        m = Molecule(
            geometry=[["H", [0.0, 0.0, 1.0]], ["H", [0.0, 0.45, 1.0]]],
            degrees_of_freedom=[dof],
        )
        driver = ElectronicStructureMoleculeDriver(
            m, driver_type=ElectronicStructureDriverType.PYSCF)
        problem = ElectronicStructureProblem(driver)

        qubit_converter = QubitConverter(JordanWignerMapper(),
                                         z2symmetry_reduction=None)
        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)
        me_gsc = GroundStateEigensolver(qubit_converter, solver)
        qeom_solver = QEOM(me_gsc, "sd")

        # BOPES sampler
        sampler = BOPESSampler(qeom_solver)

        # absolute internuclear distance in Angstrom
        points = [0.7, 1.0, 1.3]
        results = sampler.sample(problem, points)

        points_run = results.points
        energies = results.energies

        np.testing.assert_array_almost_equal(points_run, [0.7, 1.0, 1.3])
        np.testing.assert_array_almost_equal(
            energies,
            [
                [-1.13618945, -0.47845306, -0.1204519, 0.5833141],
                [-1.10115033, -0.74587179, -0.35229063, 0.03904763],
                [-1.03518627, -0.85523694, -0.42240202, -0.21860355],
            ],
            decimal=2,
        )
示例#24
0
    def __init__(self, operator: OperatorBase,
                 input_params: Optional[List[Parameter]] = None,
                 weight_params: Optional[List[Parameter]] = None,
                 exp_val: Optional[ExpectationBase] = None,
                 gradient: Optional[Gradient] = None,
                 quantum_instance: Optional[Union[QuantumInstance, BaseBackend, Backend]] = None):
        """Initializes the Opflow Quantum Neural Network.

        Args:
            operator: The parametrized operator that represents the neural network.
            input_params: The operator parameters that correspond to the input of the network.
            weight_params: The operator parameters that correspond to the trainable weights.
            exp_val: The Expected Value converter to be used for the operator.
            gradient: The Gradient converter to be used for the operator's backward pass.
            quantum_instance: The quantum instance to evaluate the network.
        """
        self.operator = operator
        self.input_params = list(input_params or [])
        self.weight_params = list(weight_params or [])
        self.exp_val = exp_val  # TODO: currently not used by Gradient!
        self.gradient = gradient or Gradient()

        if isinstance(quantum_instance, (BaseBackend, Backend)):
            quantum_instance = QuantumInstance(quantum_instance)

        if quantum_instance:
            self.quantum_instance = quantum_instance
            self.circuit_sampler = CircuitSampler(
                self.quantum_instance,
                param_qobj=is_aer_provider(self.quantum_instance.backend)
            )
            # TODO: replace by extended caching in circuit sampler after merged: "caching='all'"
            self.gradient_sampler = deepcopy(self.circuit_sampler)
        else:
            self.quantum_instance = None
            self.circuit_sampler = None
            self.gradient_sampler = None

        self.forward_operator = self.exp_val.convert(operator) if exp_val else operator
        self.gradient_operator = self.gradient.convert(operator,
                                                       self.input_params + self.weight_params)
        output_shape = self._get_output_shape_from_op(operator)
        super().__init__(len(self.input_params), len(self.weight_params),
                         sparse=False, output_shape=output_shape)
    def test_measurement_error_mitigation_with_diff_qubit_order(self):
        """ measurement error mitigation with different qubit order"""
        # pylint: disable=import-outside-toplevel
        try:
            from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
            from qiskit import Aer
            from qiskit.providers.aer import noise
        except ImportError as ex:  # pylint: disable=broad-except
            self.skipTest("Package doesn't appear to be installed. Error: '{}'".format(str(ex)))
            return

        aqua_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)

        backend = Aer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend=backend,
                                           seed_simulator=1679,
                                           seed_transpiler=167,
                                           shots=1000,
                                           noise_model=noise_model,
                                           measurement_error_mitigation_cls=CompleteMeasFitter,
                                           cals_matrix_refresh_period=0)
        # circuit
        qc1 = QuantumCircuit(2, 2)
        qc1.h(0)
        qc1.cx(0, 1)
        qc1.measure(0, 0)
        qc1.measure(1, 1)
        qc2 = QuantumCircuit(2, 2)
        qc2.h(0)
        qc2.cx(0, 1)
        qc2.measure(1, 0)
        qc2.measure(0, 1)

        # this should run smoothly
        quantum_instance.execute([qc1, qc2])
        self.assertGreater(quantum_instance.time_taken, 0.)
        quantum_instance.reset_execution_results()

        # failure case
        qc3 = QuantumCircuit(3, 3)
        qc3.h(2)
        qc3.cx(1, 2)
        qc3.measure(2, 1)
        qc3.measure(1, 2)

        self.assertRaises(QiskitError, quantum_instance.execute, [qc1, qc3])
示例#26
0
    def test_circuit_sampler2(self, method):
        """Test the probability gradient with the circuit sampler

        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
        """

        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
        if method == 'fin_diff':
            np.random.seed(8)
            prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.)).convert(
                operator=op,
                params=params)
        else:
            prob_grad = Gradient(grad_method=method).convert(operator=op, params=params)
        values_dict = [{a: [np.pi / 4], b: [0]}, {params[0]: [np.pi / 4], params[1]: [np.pi / 4]},
                       {params[0]: [np.pi / 2], params[1]: [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]]]

        backend = BasicAer.get_backend('qasm_simulator')
        q_instance = QuantumInstance(backend=backend, shots=shots)

        for i, value_dict in enumerate(values_dict):
            sampler = CircuitSampler(backend=q_instance).convert(prob_grad,
                                                                 params=value_dict)
            result = sampler.eval()
            np.testing.assert_array_almost_equal(result[0], correct_values[i], decimal=1)
示例#27
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)
示例#28
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",
                                   "second_q/drivers/hdf5d"))

        converter = QubitConverter(ParityMapper())

        problem = ElectronicStructureProblem(driver)

        _ = problem.second_q_ops()

        particle_number = cast(
            ParticleNumber,
            problem.grouped_property_transformed.get_property(ParticleNumber))
        num_particles = (particle_number.num_alpha, particle_number.num_beta)
        num_spin_orbitals = particle_number.num_spin_orbitals

        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)
    def test_qaoa_random_initial_point(self):
        """ QAOA random initial point """
        aqua_globals.random_seed = 10598
        w = nx.adjacency_matrix(
            nx.fast_gnp_random_graph(5, 0.5,
                                     seed=aqua_globals.random_seed)).toarray()
        qubit_op, _ = max_cut.get_operator(w)
        q_i = QuantumInstance(BasicAer.get_backend('qasm_simulator'),
                              seed_simulator=aqua_globals.random_seed,
                              seed_transpiler=aqua_globals.random_seed,
                              shots=4096)
        qaoa = QAOA(optimizer=NELDER_MEAD(disp=True),
                    p=1,
                    quantum_instance=q_i)
        _ = qaoa.compute_minimum_eigenvalue(operator=qubit_op)

        np.testing.assert_almost_equal([-0.8792, 0.3948],
                                       qaoa.optimal_params,
                                       decimal=4)
示例#30
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()