Beispiel #1
0
    def setUp(self):
        super().setUp()
        self.seed = 50
        algorithm_globals.random_seed = self.seed
        self.h2_op = (-1.052373245772859 * (I ^ I) + 0.39793742484318045 *
                      (I ^ Z) - 0.39793742484318045 * (Z ^ I) -
                      0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 *
                      (X ^ X))
        self.h2_energy = -1.85727503
        self.h2_energy_excited = [-1.85727503, -1.24458455]

        self.test_op = MatrixOp(np.diagflat([3, 5, -1, 0.8, 0.2, 2, 1,
                                             -3])).to_pauli_op()
        self.test_results = [-3, -1]

        self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"],
                                          entanglement_blocks="cz",
                                          reps=1)
        self.ry_wavefunction = TwoLocal(rotation_blocks="ry",
                                        entanglement_blocks="cz")

        self.qasm_simulator = QuantumInstance(
            BasicAer.get_backend("qasm_simulator"),
            shots=2048,
            seed_simulator=self.seed,
            seed_transpiler=self.seed,
        )
        self.statevector_simulator = QuantumInstance(
            BasicAer.get_backend("statevector_simulator"),
            shots=1,
            seed_simulator=self.seed,
            seed_transpiler=self.seed,
        )
Beispiel #2
0
    def test_application(self):
        """Test an end-to-end application."""
        bounds = np.array([0., 7.])
        num_qubits = 3

        # the distribution circuit is a normal distribution plus a QGAN-trained ansatz circuit
        dist = NormalDistribution(num_qubits, mu=1, sigma=1, bounds=bounds)

        ansatz = TwoLocal(num_qubits, 'ry', 'cz', reps=1, entanglement='circular')
        trained_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]
        ansatz.assign_parameters(trained_params, inplace=True)

        dist.compose(ansatz, inplace=True)

        # create the European call expected value
        strike_price = 2
        rescaling_factor = 0.25
        european_call = EuropeanCallExpectedValue(num_qubits, strike_price, rescaling_factor,
                                                  bounds)

        # create the state preparation circuit
        state_preparation = european_call.compose(dist, front=True)

        iae = IterativeAmplitudeEstimation(0.01, 0.05, state_preparation=state_preparation,
                                           objective_qubits=[num_qubits],
                                           post_processing=european_call.post_processing)

        backend = QuantumInstance(Aer.get_backend('qasm_simulator'),
                                  seed_simulator=125, seed_transpiler=80)
        result = iae.run(backend)
        self.assertAlmostEqual(result.estimation, 1.0364776997977694)
Beispiel #3
0
    def setUp(self):
        super().setUp()
        self.seed = 50
        aqua_globals.random_seed = self.seed
        self.h2_op = -1.052373245772859 * (I ^ I) \
            + 0.39793742484318045 * (I ^ Z) \
            - 0.39793742484318045 * (Z ^ I) \
            - 0.01128010425623538 * (Z ^ Z) \
            + 0.18093119978423156 * (X ^ X)
        self.h2_energy = -1.85727503

        self.ryrz_wavefunction = TwoLocal(rotation_blocks=['ry', 'rz'],
                                          entanglement_blocks='cz')
        self.ry_wavefunction = TwoLocal(rotation_blocks='ry',
                                        entanglement_blocks='cz')

        self.qasm_simulator = QuantumInstance(
            BasicAer.get_backend('qasm_simulator'),
            shots=1024,
            seed_simulator=self.seed,
            seed_transpiler=self.seed)
        self.statevector_simulator = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'),
            shots=1,
            seed_simulator=self.seed,
            seed_transpiler=self.seed)
Beispiel #4
0
    def setUp(self):
        super().setUp()
        self.seed = 50
        algorithm_globals.random_seed = self.seed
        self.h2_op = (-1.052373245772859 * (I ^ I) + 0.39793742484318045 *
                      (I ^ Z) - 0.39793742484318045 * (Z ^ I) -
                      0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 *
                      (X ^ X))
        self.h2_energy = -1.85727503

        self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"],
                                          entanglement_blocks="cz")
        self.ry_wavefunction = TwoLocal(rotation_blocks="ry",
                                        entanglement_blocks="cz")

        self.qasm_simulator = QuantumInstance(
            BasicAer.get_backend("qasm_simulator"),
            shots=1024,
            seed_simulator=self.seed,
            seed_transpiler=self.seed,
        )
        self.statevector_simulator = QuantumInstance(
            BasicAer.get_backend("statevector_simulator"),
            shots=1,
            seed_simulator=self.seed,
            seed_transpiler=self.seed,
        )
Beispiel #5
0
    def test_compose_no_clbits_in_one_inplace(self):
        """Test combining a circuit with cregs to one without inplace"""
        ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx")

        qc = QuantumCircuit(2)
        qc.measure_all()
        ansatz.compose(qc, inplace=True)
        self.assertEqual(ansatz.clbits, qc.clbits)
Beispiel #6
0
    def setUp(self):
        super().setUp()
        self.seed = 50
        aqua_globals.random_seed = self.seed
        pauli_dict = {
            'paulis': [{
                "coeff": {
                    "imag": 0.0,
                    "real": -1.052373245772859
                },
                "label": "II"
            }, {
                "coeff": {
                    "imag": 0.0,
                    "real": 0.39793742484318045
                },
                "label": "IZ"
            }, {
                "coeff": {
                    "imag": 0.0,
                    "real": -0.39793742484318045
                },
                "label": "ZI"
            }, {
                "coeff": {
                    "imag": 0.0,
                    "real": -0.01128010425623538
                },
                "label": "ZZ"
            }, {
                "coeff": {
                    "imag": 0.0,
                    "real": 0.18093119978423156
                },
                "label": "XX"
            }]
        }
        self.qubit_op = WeightedPauliOperator.from_dict(pauli_dict).to_opflow()

        num_qubits = self.qubit_op.num_qubits
        ansatz = TwoLocal(num_qubits,
                          rotation_blocks=['ry', 'rz'],
                          entanglement_blocks='cz')
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        self.ryrz_wavefunction = {
            'wrapped': RYRZ(num_qubits),
            'circuit': QuantumCircuit(num_qubits).compose(ansatz),
            'library': ansatz
        }

        ansatz = ansatz.copy()
        ansatz.rotation_blocks = 'ry'
        self.ry_wavefunction = {
            'wrapped': RY(num_qubits),
            'circuit': QuantumCircuit(num_qubits).compose(ansatz),
            'library': ansatz
        }
        warnings.filterwarnings('always', category=DeprecationWarning)
Beispiel #7
0
    def test_compose_no_clbits_in_one_multireg(self):
        """Test combining a circuit with cregs to one without, multi cregs"""
        ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx")

        qa = QuantumRegister(2, "q")
        ca = ClassicalRegister(2, "a")
        cb = ClassicalRegister(2, "b")
        qc = QuantumCircuit(qa, ca, cb)
        qc.measure(0, cb[1])
        out = ansatz.compose(qc)
        self.assertEqual(out.clbits, qc.clbits)
        self.assertEqual(out.cregs, qc.cregs)
Beispiel #8
0
    def test_parameters_settable_is_constant(self):
        """Test the attribute num_parameters_settable does not change on parameter change."""
        two = TwoLocal(3, rotation_blocks='rx', entanglement='cz', reps=2)
        ordered_params = two.ordered_parameters

        x = Parameter('x')
        two.assign_parameters(dict(zip(ordered_params, [x] * two.num_parameters)), inplace=True)

        with self.subTest(msg='num_parameters collapsed to 1'):
            self.assertEqual(two.num_parameters, 1)

        with self.subTest(msg='num_parameters_settable remained constant'):
            self.assertEqual(two.num_parameters_settable, len(ordered_params))
Beispiel #9
0
    def test_composing_two(self):
        """Test adding two two-local circuits."""
        entangler_map = [[0, 3], [0, 2]]
        two = TwoLocal(4, [], 'cry', entangler_map, reps=1)
        circuit = two.compose(two)

        reference = QuantumCircuit(4)
        params = two.ordered_parameters
        for _ in range(2):
            reference.cry(params[0], 0, 3)
            reference.cry(params[1], 0, 2)

        self.assertCircuitEqual(reference, circuit)
Beispiel #10
0
    def test_circular_on_same_block_and_circuit_size(self):
        """Test circular entanglement works correctly if the circuit and block sizes match."""

        two = TwoLocal(2, 'ry', 'cx', entanglement='circular', reps=1)
        parameters = np.arange(two.num_parameters)

        ref = QuantumCircuit(2)
        ref.ry(parameters[0], 0)
        ref.ry(parameters[1], 1)
        ref.cx(0, 1)
        ref.ry(parameters[2], 0)
        ref.ry(parameters[3], 1)

        self.assertCircuitEqual(two.assign_parameters(parameters), ref)
    def test_application(self):
        """Test an end-to-end application."""
        from qiskit import Aer

        bounds = np.array([0.0, 7.0])
        num_qubits = 3

        # the distribution circuit is a normal distribution plus a QGAN-trained ansatz circuit
        dist = NormalDistribution(num_qubits, mu=1, sigma=1, bounds=bounds)

        ansatz = TwoLocal(num_qubits, "ry", "cz", reps=1, entanglement="circular")
        trained_params = [
            0.29399714,
            0.38853322,
            0.9557694,
            0.07245791,
            6.02626428,
            0.13537225,
        ]
        ansatz.assign_parameters(trained_params, inplace=True)

        dist.compose(ansatz, inplace=True)

        # create the European call expected value
        strike_price = 2
        rescaling_factor = 0.25
        european_call = EuropeanCallPricingObjective(
            num_state_qubits=num_qubits,
            strike_price=strike_price,
            rescaling_factor=rescaling_factor,
            bounds=bounds,
        )

        # create the state preparation circuit
        state_preparation = european_call.compose(dist, front=True)

        problem = EstimationProblem(
            state_preparation=state_preparation,
            objective_qubits=[num_qubits],
            post_processing=european_call.post_processing,
        )

        q_i = QuantumInstance(
            Aer.get_backend("aer_simulator"), seed_simulator=125, seed_transpiler=80
        )
        iae = IterativeAmplitudeEstimation(epsilon_target=0.01, alpha=0.05, quantum_instance=q_i)
        result = iae.estimate(problem)
        self.assertAlmostEqual(result.estimation_processed, 1.0364776997977694)
Beispiel #12
0
    def test_reuse(self):
        """Test re-using a VQE algorithm instance."""
        vqe = VQE()
        with self.subTest(msg='assert running empty raises AlgorithmError'):
            with self.assertRaises(AlgorithmError):
                _ = vqe.run()

        var_form = TwoLocal(rotation_blocks=['ry', 'rz'],
                            entanglement_blocks='cz')
        vqe.var_form = var_form
        with self.subTest(msg='assert missing operator raises AlgorithmError'):
            with self.assertRaises(AlgorithmError):
                _ = vqe.run()

        vqe.operator = self.h2_op
        with self.subTest(msg='assert missing backend raises AlgorithmError'):
            with self.assertRaises(AlgorithmError):
                _ = vqe.run()

        vqe.quantum_instance = self.statevector_simulator
        with self.subTest(msg='assert VQE works once all info is available'):
            result = vqe.run()
            self.assertAlmostEqual(result.eigenvalue.real,
                                   self.h2_energy,
                                   places=5)

        operator = PrimitiveOp(
            np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0,
                                                                  3]]))

        with self.subTest(msg='assert minimum eigensolver interface works'):
            result = vqe.compute_minimum_eigenvalue(operator)
            self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
Beispiel #13
0
    def test_compose_inplace_to_circuit(self):
        """Test adding a two-local to an existing circuit."""
        two = TwoLocal(3, ["ry", "rz"],
                       "cz",
                       "full",
                       reps=1,
                       insert_barriers=True)
        circuit = QuantumCircuit(3)
        circuit.compose(two, inplace=True)

        reference = QuantumCircuit(3)
        param_iter = iter(two.ordered_parameters)
        for i in range(3):
            reference.ry(next(param_iter), i)
        for i in range(3):
            reference.rz(next(param_iter), i)
        reference.barrier()
        reference.cz(0, 1)
        reference.cz(0, 2)
        reference.cz(1, 2)
        reference.barrier()
        for i in range(3):
            reference.ry(next(param_iter), i)
        for i in range(3):
            reference.rz(next(param_iter), i)

        self.assertCircuitEqual(circuit, reference)
Beispiel #14
0
 def test_skip_final_rotation_layer(self):
     """Test skipping the final rotation layer works."""
     two = TwoLocal(3, ["ry", "h"], ["cz", "cx"],
                    reps=2,
                    skip_final_rotation_layer=True)
     self.assertEqual(two.num_parameters,
                      6)  # would be 9 with a final rotation layer
Beispiel #15
0
    def test_set_packing_vqe(self):
        """ set packing vqe test """
        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

        wavefunction = TwoLocal(rotation_blocks='ry',
                                entanglement_blocks='cz',
                                reps=3,
                                entanglement='linear')
        q_i = QuantumInstance(Aer.get_backend('qasm_simulator'),
                              seed_simulator=aqua_globals.random_seed,
                              seed_transpiler=aqua_globals.random_seed)
        result = VQE(wavefunction,
                     SPSA(maxiter=200),
                     max_evals_grouped=2,
                     quantum_instance=q_i).compute_minimum_eigenvalue(
                         operator=self.qubit_op)
        x = sample_most_likely(result.eigenstate)
        ising_sol = set_packing.get_solution(x)
        oracle = self._brute_force()
        self.assertEqual(np.count_nonzero(ising_sol), oracle)
Beispiel #16
0
    def test_compose_inplace_to_circuit(self):
        """Test adding a two-local to an existing circuit."""
        two = TwoLocal(3, ["ry", "rz"],
                       "cz",
                       "full",
                       reps=1,
                       insert_barriers=True)
        circuit = QuantumCircuit(3)
        circuit.compose(two, inplace=True)

        #      ┌──────────┐┌──────────┐ ░           ░ ┌──────────┐ ┌──────────┐
        # q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├
        #      ├──────────┤├──────────┤ ░  │  │     ░ ├──────────┤┌┴──────────┤
        # q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├
        #      ├──────────┤├──────────┤ ░     │  │  ░ ├──────────┤├───────────┤
        # q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├
        #      └──────────┘└──────────┘ ░           ░ └──────────┘└───────────┘
        reference = QuantumCircuit(3)
        param_iter = iter(two.ordered_parameters)
        for i in range(3):
            reference.ry(next(param_iter), i)
        for i in range(3):
            reference.rz(next(param_iter), i)
        reference.barrier()
        reference.cz(0, 1)
        reference.cz(0, 2)
        reference.cz(1, 2)
        reference.barrier()
        for i in range(3):
            reference.ry(next(param_iter), i)
        for i in range(3):
            reference.rz(next(param_iter), i)

        self.assertCircuitEqual(circuit.decompose(), reference)
Beispiel #17
0
    def test_batch_evaluate_with_qnspsa(self):
        """Test batch evaluating with QNSPSA works."""
        ansatz = TwoLocal(2,
                          rotation_blocks=["ry", "rz"],
                          entanglement_blocks="cz")

        wrapped_backend = BasicAer.get_backend("qasm_simulator")
        inner_backend = BasicAer.get_backend("statevector_simulator")

        callcount = {"count": 0}

        def wrapped_run(circuits, **kwargs):
            kwargs["callcount"]["count"] += 1
            return inner_backend.run(circuits)

        wrapped_backend.run = partial(wrapped_run, callcount=callcount)

        fidelity = QNSPSA.get_fidelity(ansatz, backend=wrapped_backend)
        qnspsa = QNSPSA(fidelity, maxiter=5)

        vqe = VQE(
            ansatz=ansatz,
            optimizer=qnspsa,
            max_evals_grouped=100,
            quantum_instance=wrapped_backend,
        )
        _ = vqe.compute_minimum_eigenvalue(Z ^ Z)

        # 1 calibration + 1 stddev estimation + 1 initial blocking
        # + 5 (1 loss + 1 fidelity + 1 blocking) + 1 return loss + 1 VQE eval
        expected = 1 + 1 + 1 + 5 * 3 + 1 + 1

        self.assertEqual(callcount["count"], expected)
Beispiel #18
0
    def test_reuse(self):
        """Test re-using a VQE algorithm instance."""
        vqe = VQE()
        with self.subTest(msg="assert running empty raises AlgorithmError"):
            with self.assertRaises(AlgorithmError):
                _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op)

        ansatz = TwoLocal(rotation_blocks=["ry", "rz"],
                          entanglement_blocks="cz")
        vqe.ansatz = ansatz
        with self.subTest(msg="assert missing operator raises AlgorithmError"):
            with self.assertRaises(AlgorithmError):
                _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op)

        vqe.expectation = MatrixExpectation()
        vqe.quantum_instance = self.statevector_simulator
        with self.subTest(msg="assert VQE works once all info is available"):
            result = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
            self.assertAlmostEqual(result.eigenvalue.real,
                                   self.h2_energy,
                                   places=5)

        operator = PrimitiveOp(
            np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0,
                                                                  3]]))

        with self.subTest(msg="assert minimum eigensolver interface works"):
            result = vqe.compute_minimum_eigenvalue(operator=operator)
            self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
Beispiel #19
0
    def test_vqe_reuse(self):
        """ Test vqe reuse """
        vqe = VQE()
        with self.assertRaises(AquaError):
            _ = vqe.run()

        var_form = TwoLocal(rotation_blocks=['ry', 'rz'],
                            entanglement_blocks='cz')
        vqe.var_form = var_form
        with self.assertRaises(AquaError):
            _ = vqe.run()

        vqe.operator = self.qubit_op
        with self.assertRaises(AquaError):
            _ = vqe.run()

        qinst = QuantumInstance(BasicAer.get_backend('statevector_simulator'))
        vqe.quantum_instance = qinst
        result = vqe.run()
        self.assertAlmostEqual(result.eigenvalue.real, -1.85727503, places=5)

        operator = PrimitiveOp(
            np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0,
                                                                  3]]))
        vqe.operator = operator
        result = vqe.run()
        self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
Beispiel #20
0
 def test_samples_vqe(self, simulator):
     """Test samples for VQE"""
     # test minimize
     algorithm_globals.random_seed = 1
     quantum_instance = self.sv_simulator if simulator == "sv" else self.qasm_simulator
     opt_sol = -2
     success = OptimizationResultStatus.SUCCESS
     optimizer = SPSA(maxiter=100)
     ry_ansatz = TwoLocal(5, "ry", "cz", reps=3, entanglement="full")
     vqe_mes = VQE(ry_ansatz, optimizer=optimizer, quantum_instance=quantum_instance)
     vqe = MinimumEigenOptimizer(vqe_mes)
     results = vqe.solve(self.op_ordering)
     self.assertEqual(results.fval, opt_sol)
     np.testing.assert_array_almost_equal(results.x, [0, 1])
     self.assertEqual(results.status, success)
     results.raw_samples.sort(key=lambda x: x.probability, reverse=True)
     np.testing.assert_array_almost_equal(results.x, results.raw_samples[0].x)
     self.assertAlmostEqual(sum(s.probability for s in results.samples), 1, delta=1e-5)
     self.assertAlmostEqual(sum(s.probability for s in results.raw_samples), 1, delta=1e-5)
     self.assertAlmostEqual(min(s.fval for s in results.samples), -2)
     self.assertAlmostEqual(min(s.fval for s in results.samples if s.status == success), opt_sol)
     self.assertAlmostEqual(min(s.fval for s in results.raw_samples), opt_sol)
     for sample in results.raw_samples:
         self.assertEqual(sample.status, success)
     np.testing.assert_array_almost_equal(results.samples[0].x, [0, 1])
     self.assertAlmostEqual(results.samples[0].fval, opt_sol)
     self.assertEqual(results.samples[0].status, success)
     np.testing.assert_array_almost_equal(results.raw_samples[0].x, [0, 1])
     self.assertAlmostEqual(results.raw_samples[0].fval, opt_sol)
     self.assertEqual(results.raw_samples[0].status, success)
    def test_runtime(self, subroutine):
        """Test vqe and qaoa runtime"""
        optimizer = {"name": "SPSA", "maxiter": 100}
        backend = QasmSimulatorPy()

        if subroutine == "vqe":
            ry_ansatz = TwoLocal(5, "ry", "cz", reps=3, entanglement="full")
            initial_point = np.random.default_rng(42).random(
                ry_ansatz.num_parameters)
            solver = VQEProgram(
                ansatz=ry_ansatz,
                optimizer=optimizer,
                initial_point=initial_point,
                backend=backend,
                provider=FakeVQERuntimeProvider(),
            )
        else:
            reps = 2
            initial_point = np.random.default_rng(42).random(2 * reps)
            solver = QAOAProgram(
                optimizer=optimizer,
                reps=reps,
                initial_point=initial_point,
                backend=backend,
                provider=FakeQAOARuntimeProvider(),
            )

        opt = MinimumEigenOptimizer(solver)
        result = opt.solve(self.op_ordering)
        self.assertIsInstance(result, MinimumEigenOptimizationResult)
Beispiel #22
0
    def test_backend_change(self, user_expectation):
        """Test that VQE works when backend changes."""
        vqe = VQE(
            operator=self.h2_op,
            var_form=TwoLocal(rotation_blocks=['ry', 'rz'],
                              entanglement_blocks='cz'),
            optimizer=SLSQP(maxiter=2),
            expectation=user_expectation,
            quantum_instance=BasicAer.get_backend('statevector_simulator'))
        result0 = vqe.run()
        if user_expectation is not None:
            with self.subTest('User expectation kept.'):
                self.assertEqual(vqe.expectation, user_expectation)
        else:
            with self.subTest('Expectation created.'):
                self.assertIsInstance(vqe.expectation, ExpectationBase)
        try:
            vqe.set_backend(BasicAer.get_backend('qasm_simulator'))
        except Exception as ex:  # pylint: disable=broad-except
            self.fail("Failed to change backend. Error: '{}'".format(str(ex)))
            return

        result1 = vqe.run()
        if user_expectation is not None:
            with self.subTest(
                    'Change backend with user expectation, it is kept.'):
                self.assertEqual(vqe.expectation, user_expectation)
        else:
            with self.subTest(
                    'Change backend without user expectation, one created.'):
                self.assertIsInstance(vqe.expectation, ExpectationBase)

        with self.subTest('Check results.'):
            self.assertEqual(len(result0.optimal_point),
                             len(result1.optimal_point))
Beispiel #23
0
    def test_iadd_to_circuit(self):
        """Test adding a two-local to an existing circuit."""
        two = TwoLocal(3, ['ry', 'rz'],
                       'cz',
                       'full',
                       reps=1,
                       insert_barriers=True)
        circuit = QuantumCircuit(3)
        circuit += two

        reference = QuantumCircuit(3)
        param_iter = iter(two.ordered_parameters)
        for i in range(3):
            reference.ry(next(param_iter), i)
        for i in range(3):
            reference.rz(next(param_iter), i)
        reference.barrier()
        reference.cz(0, 1)
        reference.cz(0, 2)
        reference.cz(1, 2)
        reference.barrier()
        for i in range(3):
            reference.ry(next(param_iter), i)
        for i in range(3):
            reference.rz(next(param_iter), i)

        self.assertCircuitEqual(circuit, reference)
Beispiel #24
0
    def test_backend_change(self, user_expectation):
        """Test that VQE works when backend changes."""
        vqe = VQE(
            ansatz=TwoLocal(rotation_blocks=["ry", "rz"],
                            entanglement_blocks="cz"),
            optimizer=SLSQP(maxiter=2),
            expectation=user_expectation,
            quantum_instance=BasicAer.get_backend("statevector_simulator"),
        )
        result0 = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
        if user_expectation is not None:
            with self.subTest("User expectation kept."):
                self.assertEqual(vqe.expectation, user_expectation)

        vqe.quantum_instance = BasicAer.get_backend("qasm_simulator")

        # works also if no expectation is set, since it will be determined automatically
        result1 = vqe.compute_minimum_eigenvalue(operator=self.h2_op)

        if user_expectation is not None:
            with self.subTest(
                    "Change backend with user expectation, it is kept."):
                self.assertEqual(vqe.expectation, user_expectation)

        with self.subTest("Check results."):
            self.assertEqual(len(result0.optimal_point),
                             len(result1.optimal_point))
Beispiel #25
0
    def test_vqe_2_iqpe(self):
        """ vqe to iqpe test """
        backend = BasicAer.get_backend('qasm_simulator')
        num_qbits = self.qubit_op.num_qubits
        wavefunction = TwoLocal(num_qbits, ['ry', 'rz'],
                                'cz',
                                reps=3,
                                insert_barriers=True)

        optimizer = SPSA(maxiter=10)
        algo = VQE(self.qubit_op, wavefunction, optimizer)

        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=self.seed,
                                           seed_transpiler=self.seed)
        result = algo.run(quantum_instance)

        self.log.debug('VQE result: %s.', result)

        ref_eigenval = -1.85727503  # Known reference value

        num_time_slices = 1
        num_iterations = 6

        param_dict = result.optimal_parameters
        state_in = VarFormBased(wavefunction, param_dict)

        iqpe = IQPE(self.qubit_op,
                    state_in,
                    num_time_slices,
                    num_iterations,
                    expansion_mode='suzuki',
                    expansion_order=2,
                    shallow_circuit_concat=True)
        quantum_instance = QuantumInstance(backend,
                                           shots=100,
                                           seed_transpiler=self.seed,
                                           seed_simulator=self.seed)
        result = iqpe.run(quantum_instance)

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

        self.assertAlmostEqual(result.eigenvalue.real,
                               ref_eigenval.real,
                               delta=1e-2)
Beispiel #26
0
    def test_raw_feature_vector_on_wine(self, mode):
        """Test VQE on the wine dataset using the ``RawFeatureVector`` as data preparation."""
        feature_dim = 4  # dimension of each data point
        training_dataset_size = 8
        testing_dataset_size = 4

        _, training_input, test_input, _ = wine(
            training_size=training_dataset_size,
            test_size=testing_dataset_size,
            n=feature_dim,
            plot_data=False)
        if mode == 'component':
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            feature_map = LegacyRawFeatureVector(feature_dimension=feature_dim)
        else:
            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(self.statevector_simulator)
        if mode == 'component':
            warnings.filterwarnings('always', category=DeprecationWarning)

        self.log.debug(result['testing_accuracy'])
        self.assertGreater(result['testing_accuracy'], 0.7)
Beispiel #27
0
    def test_vqc_minibatching_with_gradient_support(self, mode):
        """ vqc minibatching with gradient support test """
        n_dim = 2  # dimension of each data point
        seed = 1024
        aqua_globals.random_seed = seed
        _, training_input, test_input, _ = ad_hoc_data(training_size=4,
                                                       test_size=2,
                                                       n=n_dim,
                                                       gap=0.3,
                                                       plot_data=False)
        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = L_BFGS_B(maxfun=30)

        # set up data encoding circuit
        data_preparation = self.data_preparation[mode]

        # set up wavefunction
        if mode == 'wrapped':
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            wavefunction = RYRZ(2, depth=1)
        else:
            wavefunction = TwoLocal(2, ['ry', 'rz'],
                                    'cz',
                                    reps=1,
                                    insert_barriers=True)
            theta = ParameterVector('theta', wavefunction.num_parameters)
            resorted = []
            for i in range(4):
                layer = wavefunction.ordered_parameters[4 * i:4 * (i + 1)]
                resorted += layer[::2]
                resorted += layer[1::2]
            wavefunction.assign_parameters(dict(zip(resorted, theta)),
                                           inplace=True)

        if mode == 'circuit':
            wavefunction = QuantumCircuit(2).compose(wavefunction)

        # set up algorithm
        vqc = VQC(optimizer,
                  data_preparation,
                  wavefunction,
                  training_input,
                  test_input,
                  minibatch_size=2)

        if mode in ['circuit', 'library']:
            vqc._feature_map_params = self._sorted_data_params
            vqc._var_form_params = list(theta)
        else:
            warnings.filterwarnings('always', category=DeprecationWarning)

        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)
        result = vqc.run(quantum_instance)
        vqc_accuracy = 0.5
        self.log.debug(result['testing_accuracy'])
        self.assertAlmostEqual(result['testing_accuracy'],
                               vqc_accuracy,
                               places=3)
Beispiel #28
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)
Beispiel #29
0
    def test_backend_change(self, user_expectation):
        """Test that VQE works when backend changes."""
        vqe = VQE(
            ansatz=TwoLocal(rotation_blocks=["ry", "rz"],
                            entanglement_blocks="cz"),
            optimizer=SLSQP(maxiter=2),
            expectation=user_expectation,
            quantum_instance=BasicAer.get_backend("statevector_simulator"),
        )
        result0 = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
        if user_expectation is not None:
            with self.subTest("User expectation kept."):
                self.assertEqual(vqe.expectation, user_expectation)
        else:
            with self.subTest("Expectation created."):
                self.assertIsInstance(vqe.expectation, ExpectationBase)
        try:
            vqe.quantum_instance = BasicAer.get_backend("qasm_simulator")
        except Exception as ex:  # pylint: disable=broad-except
            self.fail("Failed to change backend. Error: '{}'".format(str(ex)))
            return

        result1 = vqe.compute_minimum_eigenvalue(operator=self.h2_op)
        if user_expectation is not None:
            with self.subTest(
                    "Change backend with user expectation, it is kept."):
                self.assertEqual(vqe.expectation, user_expectation)
        else:
            with self.subTest(
                    "Change backend without user expectation, one created."):
                self.assertIsInstance(vqe.expectation, ExpectationBase)

        with self.subTest("Check results."):
            self.assertEqual(len(result0.optimal_point),
                             len(result1.optimal_point))
Beispiel #30
0
 def test_vqe_mes(self):
     """ Test vqe minimum eigen solver interface """
     ansatz = TwoLocal(rotation_blocks=['ry', 'rz'],
                       entanglement_blocks='cz')
     vqe = VQE(var_form=ansatz, optimizer=COBYLA())
     vqe.set_backend(BasicAer.get_backend('statevector_simulator'))
     result = vqe.compute_minimum_eigenvalue(self.qubit_op)
     self.assertAlmostEqual(result.eigenvalue.real, -1.85727503, places=5)