예제 #1
0
 def test_default(self):
     """ Default execution """
     solver = VQEUCCSDFactory(
         QuantumInstance(BasicAer.get_backend('statevector_simulator')))
     calc = AdaptVQE(self.transformation, solver)
     res = calc.solve(self.driver)
     self.assertAlmostEqual(res.electronic_energy, self.expected, places=6)
예제 #2
0
    def test_print_result(self):
        """Regression test against issues with printing results."""
        solver = VQEUCCFactory(quantum_instance=QuantumInstance(
            BasicAer.get_backend("statevector_simulator")))
        calc = AdaptVQE(self.qubit_converter, solver)
        res = calc.solve(self.problem)
        with contextlib.redirect_stdout(io.StringIO()) as out:
            print(res)
        # do NOT change the below! Lines have been truncated as to not force exact numerical matches
        expected = """\
            === GROUND STATE ENERGY ===

            * Electronic ground state energy (Hartree): -1.857
              - computed part:      -1.857
            ~ Nuclear repulsion energy (Hartree): 0.719
            > Total ground state energy (Hartree): -1.137

            === MEASURED OBSERVABLES ===

              0:  # Particles: 2.000 S: 0.000 S^2: 0.000 M: 0.000

            === DIPOLE MOMENTS ===

            ~ Nuclear dipole moment (a.u.): [0.0  0.0  1.38

              0:
              * Electronic dipole moment (a.u.): [0.0  0.0  1.38
                - computed part:      [0.0  0.0  1.38
              > Dipole moment (a.u.): [0.0  0.0  0.0]  Total: 0.
                             (debye): [0.0  0.0  0.0]  Total: 0.
        """
        for truth, expected in zip(out.getvalue().split("\n"),
                                   expected.split("\n")):
            assert truth.strip().startswith(expected.strip())
예제 #3
0
 def run(self, qobj):
     """Main job in simulator"""
     if HAS_AER:
         if qobj.type == 'PULSE':
             from qiskit.providers.aer.pulse import PulseSystemModel
             system_model = PulseSystemModel.from_backend(self)
             sim = Aer.get_backend('pulse_simulator')
             job = sim.run(qobj, system_model)
         else:
             sim = Aer.get_backend('qasm_simulator')
             if self.properties():
                 from qiskit.providers.aer.noise import NoiseModel
                 noise_model = NoiseModel.from_backend(self, warnings=False)
                 job = sim.run(qobj, noise_model=noise_model)
             else:
                 job = sim.run(qobj)
     else:
         if qobj.type == 'PULSE':
             raise QiskitError("Unable to run pulse schedules without "
                               "qiskit-aer installed")
         warnings.warn("Aer not found using BasicAer and no noise",
                       RuntimeWarning)
         sim = BasicAer.get_backend('qasm_simulator')
         job = sim.run(qobj)
     return job
예제 #4
0
    def test_custom_minimum_eigensolver(self):
        """ Test custom MES """
        class CustomFactory(VQEUCCFactory):
            """A custom MESFactory"""
            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

        solver = CustomFactory(
            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 setUp(self):
        super().setUp()

        self.driver1 = HDF5Driver(
            hdf5_input=self.get_resource_path('test_oovqe_h4.hdf5'))
        self.driver2 = HDF5Driver(
            hdf5_input=self.get_resource_path('test_oovqe_lih.hdf5'))
        self.driver3 = HDF5Driver(
            hdf5_input=self.get_resource_path('test_oovqe_h4_uhf.hdf5'))

        self.energy1_rotation = -3.0104
        self.energy1 = -2.77  # energy of the VQE with pUCCD ansatz and LBFGSB optimizer
        self.energy2 = -7.70
        self.energy3 = -2.50
        self.initial_point1 = [
            0.039374, -0.47225463, -0.61891996, 0.02598386, 0.79045546,
            -0.04134567, 0.04944946, -0.02971617, -0.00374005, 0.77542149
        ]

        self.seed = 50

        self.optimizer = COBYLA(maxiter=1)
        self.transformation1 = \
            FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER,
                                    two_qubit_reduction=False)
        self.transformation2 = \
            FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER,
                                    two_qubit_reduction=False,
                                    freeze_core=True)

        self.quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'),
            shots=1,
            seed_simulator=self.seed,
            seed_transpiler=self.seed)
예제 #6
0
    def test_custom_minimum_eigensolver(self):
        """ Test custom MES """

        # Note: the VQEUCCSDFactory actually allows to specify an optimizer through its constructor.
        # Thus, this example is quite far fetched but for a proof-of-principle test it still works.
        class CustomFactory(VQEUCCSDFactory):
            """A custom MESFactory"""
            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

        solver = CustomFactory(
            QuantumInstance(BasicAer.get_backend('statevector_simulator')))

        calc = AdaptVQE(self.transformation, solver)
        res = calc.solve(self.driver)
        self.assertAlmostEqual(res.electronic_energy, self.expected, places=6)
예제 #7
0
def quick_simulate(circuit, shots=1024, x="0", verbose=False):
    """simulates circuit with given input

    Args:
        circuit (QuantumCircuit): Circuit to simulate. Currently no more than 2 registers supported
        shots (int, optional): number of shots to simulate. Default 1024
        x (str, optional): input string eg "11" would apply an X gate to first 2 qubits. Default "0"
        verbose (bool, optional): prints extra output

    Returns:
        dict[str:int]: results.get_counts()

    Raises:
        QiskitError: if circuit has more than two registers
    """
    names = []
    regs = []
    for q in circuit.qubits:
        name = q.register.name
        size = len(q.register)
        if name not in names:
            names.append(name)
            regs.append(size)

    if verbose:
        print(names, regs)

    # assuming that we only have 2: control + ancillary

    qra = QuantumRegister(regs[0], name=names[0])
    if len(regs) == 1:
        qa = QuantumCircuit(qra)
    elif len(regs) == 2:
        qran = QuantumRegister(regs[1], name=names[1])
        qa = QuantumCircuit(qra, qran)
    else:
        raise QiskitError("Not yet implemented for more than 2 registers")

    if len(x) != sum(regs):
        x += "0" * (sum(regs) - len(x))
    if verbose:
        print(x)
    for i, bit in enumerate(x):
        if verbose:
            print(bit, type(bit))
        if bit != "0":
            qa.x(i)
    qa.barrier()

    qa.extend(circuit)

    if verbose:
        print(qa)

    backend = BasicAer.get_backend('qasm_simulator')
    results = execute(qa, backend=backend, shots=shots).result()
    answer = results.get_counts()
    return answer
예제 #8
0
 def test_default(self):
     """Default execution"""
     solver = VQEUCCFactory(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)
예제 #9
0
 def test_natural_gradients_invalid(self):
     """test that an exception is thrown when an invalid gradient method is used"""
     solver = VQEUCCFactory(quantum_instance=QuantumInstance(
         BasicAer.get_backend("statevector_simulator")))
     grad = NaturalGradient(grad_method="fin_diff",
                            qfi_method="lin_comb_full",
                            regularization="ridge")
     calc = AdaptVQE(self.qubit_converter, solver, gradient=grad)
     with self.assertRaises(QiskitNatureError):
         _ = calc.solve(self.problem)
예제 #10
0
 def test_gradient(self, grad_method):
     """test for different gradient methods"""
     solver = VQEUCCFactory(quantum_instance=QuantumInstance(
         BasicAer.get_backend("statevector_simulator")))
     grad = Gradient(grad_method, epsilon=1.0)
     calc = AdaptVQE(self.qubit_converter, solver, gradient=grad)
     res = calc.solve(self.problem)
     self.assertAlmostEqual(res.electronic_energies[0],
                            self.expected,
                            places=6)
예제 #11
0
 def test_delta_and_gradient(self):
     """test for when delta and gradient both are set"""
     solver = VQEUCCFactory(quantum_instance=QuantumInstance(
         BasicAer.get_backend("statevector_simulator")))
     delta1 = 0.01
     grad = Gradient(grad_method="fin_diff", epsilon=1.0)
     with self.assertRaises(TypeError):
         _ = AdaptVQE(self.qubit_converter,
                      solver,
                      delta=delta1,
                      gradient=grad)
예제 #12
0
 def test_delta(self):
     """test for when delta is set instead of gradient"""
     solver = VQEUCCFactory(quantum_instance=QuantumInstance(
         BasicAer.get_backend("statevector_simulator")))
     delta1 = 0.01
     with warnings.catch_warnings(record=True):
         warnings.simplefilter("always")
         calc = AdaptVQE(self.qubit_converter, solver, delta=delta1)
     res = calc.solve(self.problem)
     self.assertAlmostEqual(res.electronic_energies[0],
                            self.expected,
                            places=6)
예제 #13
0
    def test_aux_ops_reusability(self):
        """ Test that the auxiliary operators can be reused """
        # Regression test against #1475
        solver = VQEUCCSDFactory(QuantumInstance(BasicAer.get_backend('statevector_simulator')))
        calc = AdaptVQE(self.transformation, solver)

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

        _ = calc.solve(self.driver, aux_ops)
        assert all([a == b for a, b in zip(aux_ops, aux_ops_copy)])
예제 #14
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)
        )
예제 #15
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)
예제 #16
0
    def test_entanglement(self):
        """
        Test entanglement circuits of Ignis verification -
            GHZ, MQC, parity oscillations
        """
        num_qubits = 5  # number of qubits
        sim = BasicAer.get_backend('qasm_simulator')

        # test simple GHZc
        circ = linear.get_ghz_simple(num_qubits, measure=True)
        counts = execute(circ, sim, shots=1024).result().get_counts(circ)
        self.assertTrue(
            counts.get('00000', 0) + counts.get('11111', 0) == 1024)

        # test MQC
        circ, delta = linear.get_ghz_mqc_para(num_qubits)
        theta_range = np.linspace(0, 2 * np.pi, 16)
        circuits = [
            circ.bind_parameters({delta: theta_val})
            for theta_val in theta_range
        ]
        for circ in circuits:
            counts = execute(circ, sim, shots=1024).result().get_counts(circ)
            self.assertTrue(
                (counts.get('00000', 0) == 1024)
                or (counts.get('00000', 0) + counts.get('00001', 0)) == 1024)

        # test parity oscillations
        circ, params = linear.get_ghz_po_para(num_qubits)
        theta_range = np.linspace(0, 2 * np.pi, 16)
        circuits = [
            circ.bind_parameters({
                params[0]: theta_val,
                params[1]: -theta_val
            }) for theta_val in theta_range
        ]
        for circ in circuits:
            counts = execute(circ, sim, shots=1024).result().get_counts(circ)
            even_counts = sum(key.count('1') % 2 == 0 for key in counts.keys())
            odd_counts = sum(key.count('1') % 2 == 1 for key in counts.keys())

        self.assertTrue(even_counts in (0, 16))
        self.assertTrue(odd_counts in (0, 16))
예제 #17
0
    def test_custom_excitation_pool(self):
        """ Test custom excitation pool """
        class CustomFactory(VQEUCCSDFactory):
            """A custom MES factory."""
            def get_solver(self, transformation):
                solver = super().get_solver(transformation)
                # Here, we can create essentially any custom excitation pool.
                # For testing purposes only, we simply select some hopping operator already
                # available in the variational form object.
                # pylint: disable=no-member
                custom_excitation_pool = [solver.var_form._hopping_ops[2]]
                solver.var_form.excitation_pool = custom_excitation_pool
                return solver

        solver = CustomFactory(
            QuantumInstance(BasicAer.get_backend('statevector_simulator')))
        calc = AdaptVQE(self.transformation, solver)
        res = calc.solve(self.driver)
        self.assertAlmostEqual(res.electronic_energy, self.expected, places=6)
예제 #18
0
    def test_custom_excitation_pool(self):
        """Test custom excitation pool"""
        class CustomFactory(VQEUCCFactory):
            """A custom MES factory."""
            def get_solver(self, problem, qubit_converter):
                solver = super().get_solver(problem, qubit_converter)
                # Here, we can create essentially any custom excitation pool.
                # For testing purposes only, we simply select some hopping operator already
                # available in the ansatz object.
                custom_excitation_pool = [solver.ansatz.operators[2]]
                solver.ansatz.operators = custom_excitation_pool
                return solver

        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)
예제 #19
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 = ElectronicEnergy([
            OneBodyElectronicIntegrals(ElectronicBasis.MO, (h_1, None)),
            TwoBodyElectronicIntegrals(ElectronicBasis.MO,
                                       (h_2, None, None, None)),
        ]).second_q_ops()
        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))
예제 #20
0
    def optmization_levels(self):
        backend = BasicAer.get_backend('qasm_simulator')

        circuit = self.circuit
        seed_simulator = self.seed_simulator
        seed_transpiler = seed_simulator

        counts_0 = execute(
            deepcopy(circuit),
            backend,
            optimization_level=0,
            seed_simulator=seed_simulator,
            seed_transpiler=seed_transpiler).result().get_counts()
        counts_1 = execute(
            deepcopy(circuit),
            backend,
            optimization_level=1,
            seed_simulator=seed_simulator,
            seed_transpiler=seed_transpiler,
        ).result().get_counts()
        counts_2 = execute(
            deepcopy(circuit),
            backend,
            optimization_level=2,
            seed_simulator=seed_simulator,
            seed_transpiler=seed_transpiler,
        ).result().get_counts()

        if self.random_bool:
            counts_3 = execute(
                deepcopy(circuit),
                backend,
                optimization_level=3,
                seed_simulator=seed_simulator,
                seed_transpiler=seed_transpiler,
            ).result().get_counts()
        else:
            counts_3 = deepcopy(counts_2)

        self.assertEqualCounts(counts_0, counts_1, counts_2, counts_3)
예제 #21
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)