def test_complex_1_qubit_circuit(self):
        q = QuantumRegister(1)
        circ = QuantumCircuit(q)
        circ.append(U3Gate(1, 1, 1), [q[0]])

        rho, psi = run_circuit_and_tomography(circ, q, self.method)
        F_bell = state_fidelity(psi, rho, validate=False)
        self.assertAlmostEqual(F_bell, 1, places=1)
Ejemplo n.º 2
0
 def test_basis_state_circuit(self):
     state = state = (basis_state('001', 3)+basis_state('111', 3))/np.sqrt(2)
     q = QuantumRegister(3)
     qc = QuantumCircuit(q)
     qc.initialize(state, [q[0], q[1], q[2]])
     backend = BasicAer.get_backend('statevector_simulator')
     qc_state = execute(qc, backend).result().get_statevector(qc)
     self.assertAlmostEqual(state_fidelity(qc_state, state), 1.0, places=7)
 def test_local_pbasis_default_densitymatrix(self):
     """Test default states kwarg"""
     default_states = [qi.random_density_matrix(2, seed=30 + i) for i in range(3)]
     basis = LocalPreparationBasis("fitter_basis", default_states=default_states)
     for i, state in enumerate(default_states):
         basis_state = qi.DensityMatrix(basis.matrix([i], [0]))
         fid = qi.state_fidelity(state, basis_state)
         self.assertTrue(isclose(fid, 1))
Ejemplo n.º 4
0
 def test_random_state_circuit(self):
     state = random_state(2**3, seed=40)
     q = QuantumRegister(3)
     qc = QuantumCircuit(q)
     qc.initialize(state, [q[0], q[1], q[2]])
     backend = BasicAer.get_backend('statevector_simulator')
     qc_state = execute(qc, backend).result().get_statevector(qc)
     self.assertAlmostEqual(state_fidelity(qc_state, state), 1.0, places=7)
Ejemplo n.º 5
0
    def test_2Q_interaction(self):
        r"""Test 2 qubit interaction via controlled operations using u channels."""

        total_samples = 100

        # set coupling term and drive channels to 0 frequency
        j = 0.5 / total_samples
        omega_d0 = 0.
        omega_d1 = 0.

        system_model = self._system_model_2Q(j)

        schedule = self._2Q_constant_sched(total_samples)

        qobj = assemble([schedule],
                        backend=self.backend_sim,
                        meas_level=2,
                        meas_return='single',
                        meas_map=[[0]],
                        qubit_lo_freq=[omega_d0, omega_d1],
                        memory_slots=2,
                        shots=1)

        y0 = np.kron(np.array([1., 0.]), np.array([0., 1.]))
        backend_options = {'seed' : 9000, 'initial_state': y0}

        result = self.backend_sim.run(qobj, system_model, backend_options).result()
        pulse_sim_yf = result.get_statevector()

        # exact analytic solution
        yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0

        self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5))

        # run with different initial state
        y0 = np.kron(np.array([1., 0.]), np.array([1., 0.]))
        backend_options = {'seed' : 9000, 'initial_state': y0}

        result = self.backend_sim.run(qobj, system_model, backend_options).result()
        pulse_sim_yf = result.get_statevector()

        # exact analytic solution
        yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0

        self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5))
Ejemplo n.º 6
0
    def test_state_fidelity_statevector(self):
        """Test state_fidelity function for statevector inputs"""

        psi1 = [0.70710678118654746, 0, 0, 0.70710678118654746]
        psi2 = [0., 0.70710678118654746, 0.70710678118654746, 0.]
        self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7,
                               msg='vector-vector input')
        self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7,
                               msg='vector-vector input')
        self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7,
                               msg='vector-vector input')

        psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746])
        psi2 = Statevector([0., 0.70710678118654746, 0.70710678118654746, 0.])
        self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7,
                               msg='vector-vector input')
        self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7,
                               msg='vector-vector input')
        self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7,
                               msg='vector-vector input')

        psi1 = Statevector([1, 0, 0, 1])  # invalid state
        psi2 = Statevector([1, 0, 0, 0])
        self.assertRaises(QiskitError, state_fidelity, psi1, psi2)
        self.assertRaises(QiskitError, state_fidelity, psi1, psi2, validate=True)
        self.assertEqual(state_fidelity(psi1, psi2, validate=False), 1)
Ejemplo n.º 7
0
    def test_state_fidelity_density_matrix(self):
        """Test state_fidelity function for density matrix inputs"""
        rho1 = [[0.5, 0, 0, 0.5],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0.5, 0, 0, 0.5]]
        mix = [[0.25, 0, 0, 0],
               [0, 0.25, 0, 0],
               [0, 0, 0.25, 0],
               [0, 0, 0, 0.25]]
        self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7,
                               msg='matrix-matrix input')
        self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7,
                               msg='matrix-matrix input')
        self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7,
                               msg='matrix-matrix input')

        rho1 = DensityMatrix(rho1)
        mix = DensityMatrix(mix)
        self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7,
                               msg='matrix-matrix input')
        self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7,
                               msg='matrix-matrix input')
        self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7,
                               msg='matrix-matrix input')

        rho1 = DensityMatrix([1, 0, 0, 0])
        mix = DensityMatrix(np.diag([1, 0, 0, 1]))
        self.assertRaises(QiskitError, state_fidelity, rho1, mix)
        self.assertRaises(QiskitError, state_fidelity, rho1, mix, validate=True)
        self.assertEqual(state_fidelity(rho1, mix, validate=False), 1)
    def test_different_qubit_sets(self):
        circuit = QuantumCircuit(5)
        circuit.h(0)
        circuit.cx(0, 1)
        circuit.x(2)
        circuit.s(3)
        circuit.z(4)
        circuit.cx(1, 3)

        for qubit_pair in [(0, 1), (2, 3), (1, 4), (0, 3)]:
            rho_cvx, rho_mle, psi = run_circuit_and_tomography(
                circuit, qubit_pair)
            psi = partial_trace(psi,
                                [x for x in range(5) if x not in qubit_pair])
            F_cvx = state_fidelity(psi, rho_cvx, validate=False)
            self.assertAlmostEqual(F_cvx, 1, places=1)
            F_mle = state_fidelity(psi, rho_mle, validate=False)
            self.assertAlmostEqual(F_mle, 1, places=1)
Ejemplo n.º 9
0
 def test_statevector_density_matrix(self):
     """Test state_fidelity function for statevector and density matrix inputs"""
     rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0],
                           [0.5, 0, 0, 0.5]])
     mix = DensityMatrix([[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0],
                          [0, 0, 0, 0.25]])
     self.assertAlmostEqual(state_fidelity(rho1, rho1),
                            1.0,
                            places=7,
                            msg='matrix-matrix input')
     self.assertAlmostEqual(state_fidelity(mix, mix),
                            1.0,
                            places=7,
                            msg='matrix-matrix input')
     self.assertAlmostEqual(state_fidelity(rho1, mix),
                            0.25,
                            places=7,
                            msg='matrix-matrix input')
Ejemplo n.º 10
0
 def test_random_state(self):
     # this test that a random state converges to 1/d
     number = 100000
     E_P0_last = 0
     for ii in range(number):
         state = basis_state(bin(3)[2:].zfill(3), 3)
         E_P0 = (E_P0_last*ii)/(ii+1)+state_fidelity(state, random_state(2**3, seed=ii))/(ii+1)
         E_P0_last = E_P0
     self.assertAlmostEqual(E_P0, 1/8, places=2)
Ejemplo n.º 11
0
    def test_bell_2_qubits(self):
        q2 = QuantumRegister(2)
        bell = QuantumCircuit(q2)
        bell.h(q2[0])
        bell.cx(q2[0], q2[1])

        rho, psi = run_circuit_and_tomography(bell, q2, self.method)
        F_bell = state_fidelity(psi, rho, validate=False)
        self.assertAlmostEqual(F_bell, 1, places=1)
    def test_meas_level_1(self):
        """Test measurement level 1. """

        shots = 10000  # run large number of shots for good proportions

        total_samples = 100
        omega_0 = 1.
        omega_d = omega_0

        # Require omega_a*time = pi to implement pi pulse (x gate)
        # num of samples gives time
        r = 1. / (2 * total_samples)

        system_model = self._system_model_1Q(omega_0, r)

        amp = np.exp(-1j * np.pi / 2)
        schedule = self._1Q_constant_sched(total_samples, amp=amp)

        y0=np.array([1.0, 0.0])
        pulse_sim = PulseSimulator(system_model=system_model,
                                   initial_state=y0,
                                   seed=9000)

        qobj = assemble([schedule],
                        backend=pulse_sim,
                        meas_level=1,
                        meas_return='single',
                        meas_map=[[0]],
                        qubit_lo_freq=[1.],
                        memory_slots=2,
                        shots=shots)

        result = pulse_sim.run(qobj).result()
        pulse_sim_yf = result.get_statevector()

        samples = amp * np.ones((total_samples, 1))
        indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]),
                                     samples, 1.)

        # test final state
        self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf),
                                1 - 10**-5)

        # Verify that (about) half the IQ vals have abs val 1 and half have abs val 0
        # (use prop for easier comparison)
        mem = np.abs(result.get_memory()[:, 0])

        iq_prop = {'0': 0, '1': 0}
        for i in mem:
            if i == 0:
                iq_prop['0'] += 1 / shots
            else:
                iq_prop['1'] += 1 / shots

        exp_prop = {'0': 0.5, '1': 0.5}

        self.assertDictAlmostEqual(iq_prop, exp_prop, delta=0.01)
Ejemplo n.º 13
0
    def test_qobj_two_qubit_gates(self):
        filename = self._get_resource_path('qobj/cpp_two_qubit_gates.json')
        with open(filename, 'r') as file:
            qobj = Qobj.from_dict(json.load(file))
        result = self.backend.run(qobj).result()
        expected_data = {
            'h0 CX01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])},
            'h0 CX10': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])},
            'h1 CX01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])},
            'h1 CX10': {
                'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])},
            'h0 cx01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])},
            'h0 cx10': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])},
            'h1 cx01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])},
            'h1 cx10': {
                'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])},
            'h0 cz01': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])},
            'h0 cz10': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])},
            'h1 cz01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])},
            'h1 cz10': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])},
            'h0 h1 cz01': {'statevector': np.array([0.5, 0.5, 0.5, -0.5])},
            'h0 h1 cz10': {'statevector': np.array([0.5, 0.5, 0.5, -0.5])},
            'h0 rzz01': {
                'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2), 0, 0])},
            'h0 rzz10': {
                'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2), 0, 0])},
            'h1 rzz01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1j / np.sqrt(2), 0])},
            'h1 rzz10': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1j / np.sqrt(2), 0])},
            'h0 h1 rzz01': {'statevector': np.array([0.5, 0.5j, 0.5j, 0.5])},
            'h0 h1 rzz10': {'statevector': np.array([0.5, 0.5j, 0.5j, 0.5])}
        }

        for name in expected_data:
            # Check snapshot
            snapshots = result.data(name)['snapshots']['statevector']
            self.assertEqual(set(snapshots), {'0'},
                             msg=name + ' snapshot keys')
            self.assertEqual(len(snapshots['0']), 1,
                             msg=name + ' snapshot length')
            state = format_statevector(snapshots['0'][0])
            expected_state = expected_data[name]['statevector']
            fidelity = state_fidelity(expected_state, state)
            self.assertAlmostEqual(fidelity, 1.0, places=10,
                                   msg=name + ' snapshot fidelity')
Ejemplo n.º 14
0
 def test_basis_state_circuit(self):
     """TO BE REMOVED with qiskit.quantum_info.basis_state"""
     with self.assertWarns(DeprecationWarning):
         state = (basis_state('001', 3) + basis_state('111', 3))/np.sqrt(2)
     q = QuantumRegister(3)
     qc = QuantumCircuit(q)
     qc.initialize(state, [q[0], q[1], q[2]])
     backend = BasicAer.get_backend('statevector_simulator')
     qc_state = execute(qc, backend).result().get_statevector(qc)
     self.assertAlmostEqual(state_fidelity(qc_state, state), 1.0, places=7)
Ejemplo n.º 15
0
 def test_initialize_qureg_give_int(self, name, a_int):
     bits = binary.get_required_bits(a_int)
     qreg = QuantumRegister(bits)
     qc = QuantumCircuit(qreg)
     qregs.initialize_qureg_given_int(a_int, qreg, qc)
     vec = CircuitTestCase.execute_statevector(qc).get_statevector(qc)
     exp_vec = [0] * (2**bits)
     exp_vec[a_int] = 1
     f = state_fidelity(vec, exp_vec)
     self.assertAlmostEqual(f, 1)
Ejemplo n.º 16
0
 def test_state_fidelity_mixed(self):
     """Test state_fidelity function for statevector and density matrix inputs"""
     psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746])
     rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0],
                           [0.5, 0, 0, 0.5]])
     mix = DensityMatrix([[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0],
                          [0, 0, 0, 0.25]])
     self.assertAlmostEqual(state_fidelity(psi1, rho1),
                            1.0,
                            places=7,
                            msg='vector-matrix input')
     self.assertAlmostEqual(state_fidelity(psi1, mix),
                            0.25,
                            places=7,
                            msg='vector-matrix input')
     self.assertAlmostEqual(state_fidelity(rho1, psi1),
                            1.0,
                            places=7,
                            msg='matrix-vector input')
    def test_gaussian_drive(self):
        """Test gaussian drive pulse using meas_level_2. Set omega_d0=omega_0 (drive on resonance),
        phi=0, omega_a = pi/time
        """

        # set omega_0, omega_d0 equal (use qubit frequency) -> drive on resonance
        total_samples = 100
        omega_0 = 1.
        omega_d = omega_0

        # Require omega_a*time = pi to implement pi pulse (x gate)
        # num of samples gives time
        r = np.pi / total_samples

        # initial state and seed
        y0 = np.array([1., 0.])
        seed = 9000

        # Test gaussian drive results for a few different sigma
        gauss_sigmas = [total_samples / 6, total_samples / 3, total_samples]

        # set up pulse simulator
        pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r))

        for gauss_sigma in gauss_sigmas:
            with self.subTest(gauss_sigma=gauss_sigma):
                times = 1.0 * np.arange(total_samples)
                gaussian_samples = np.exp(-times**2 / 2 / gauss_sigma**2)
                drive_pulse = Waveform(gaussian_samples, name='drive_pulse')

                # construct schedule
                schedule = Schedule()
                schedule |= Play(drive_pulse, DriveChannel(0))
                schedule |= Acquire(1, AcquireChannel(0),
                                    MemorySlot(0)) << schedule.duration

                qobj = assemble([schedule],
                                backend=pulse_sim,
                                meas_level=2,
                                meas_return='single',
                                meas_map=[[0]],
                                qubit_lo_freq=[omega_d],
                                memory_slots=2,
                                shots=1)

                result = pulse_sim.run(qobj, initial_state=y0, seed=seed).result()
                pulse_sim_yf = result.get_statevector()

                # run independent simulation
                yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]),
                                       gaussian_samples, 1.)

                # Check fidelity of statevectors
                self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf),
                                        1 - (10**-5))
Ejemplo n.º 18
0
 def test_random_state_circuit(self):
     """TO BE REMOVED Run initizalized circuit"""
     with self.assertWarns(DeprecationWarning):
         state = random_state(2**3, seed=40)
     # Initializer test should be elsewhere
     q = QuantumRegister(3)
     qc = QuantumCircuit(q)
     qc.initialize(state, [q[0], q[1], q[2]])
     backend = BasicAer.get_backend('statevector_simulator')
     qc_state = execute(qc, backend).result().get_statevector(qc)
     self.assertAlmostEqual(state_fidelity(qc_state, state), 1.0, places=7)
Ejemplo n.º 19
0
 def test_random_state(self):
     """TO BE REMOVED with qiskit.quantum_info.basis_state"""
     # this test that a random state converges to 1/d
     number = 1000
     E_P0_last = 0
     for ii in range(number):
         with self.assertWarns(DeprecationWarning):
             state = basis_state(bin(3)[2:].zfill(3), 3)
         E_P0 = (E_P0_last*ii)/(ii+1)+state_fidelity(state, random_state(2**3, seed=ii))/(ii+1)
         E_P0_last = E_P0
     self.assertAlmostEqual(E_P0, 1/8, places=2)
Ejemplo n.º 20
0
    def test_hhl_negative_eigs(self):
        """ hhl negative eigs test """
        self.log.debug('Testing HHL with matrix with negative eigenvalues')

        # The following seed was chosen so as to ensure we get a negative eigenvalue
        # and in case anything changes we assert this after the random matrix is created
        aqua_globals.random_seed = 27
        n = 2
        matrix = rmg.random_diag(n, eigrange=[-1, 1])
        vector = aqua_globals.random.random(n)
        self.assertTrue(np.any(matrix < 0),
                        "Random matrix has no negative values")

        # run NumPyLSsolver
        ref_result = NumPyLSsolver(matrix, vector).run()
        ref_solution = ref_result.solution
        ref_normed = ref_solution / np.linalg.norm(ref_solution)

        # run hhl
        orig_size = len(vector)
        matrix, vector, truncate_powerdim, truncate_hermitian = HHL.matrix_resize(
            matrix, vector)

        # Initialize eigenvalue finding module
        eigs = TestHHL._create_eigs(matrix, 4, True)
        num_q, num_a = eigs.get_register_sizes()

        # Initialize initial state module
        init_state = QuantumCircuit(num_q)
        init_state.initialize(vector / np.linalg.norm(vector), range(num_q))

        # Initialize reciprocal rotation module
        reci = LookupRotation(negative_evals=eigs._negative_evals,
                              evo_time=eigs._evo_time)

        algo = HHL(matrix, vector, truncate_powerdim, truncate_hermitian, eigs,
                   init_state, reci, num_q, num_a, orig_size)
        hhl_result = algo.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                            seed_simulator=aqua_globals.random_seed,
                            seed_transpiler=aqua_globals.random_seed))

        hhl_solution = hhl_result.solution
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)

        # compare results
        fidelity = state_fidelity(ref_normed, hhl_normed)
        np.testing.assert_approx_equal(fidelity, 1, significant=3)

        self.log.debug('HHL solution vector:       %s', hhl_solution)
        self.log.debug('algebraic solution vector: %s', ref_normed)
        self.log.debug('fidelity HHL to algebraic: %s', fidelity)
        self.log.debug('probability of result:     %s',
                       hhl_result.probability_result)
Ejemplo n.º 21
0
 def _hhl_results(self, vec):
     self._ret["output_hhl"] = vec
     # Calculating the fidelity with the classical solution
     theo = np.linalg.solve(self._matrix, self._vector)
     theo = theo/np.linalg.norm(theo)
     self._ret["fidelity_hhl_to_classical"] = state_fidelity(theo, vec)
     # Rescaling the output vector to the real solution vector
     tmp_vec = self._matrix.dot(vec)
     f1 = np.linalg.norm(self._vector)/np.linalg.norm(tmp_vec)
     f2 = sum(np.angle(self._vector*tmp_vec.conj()-1+1))/self._num_q # "-1+1" to fix angle error for -0.-0.j
     self._ret["solution_hhl"] = f1*vec*np.exp(-1j*f2)
 def test_local_mbasis_default_unitary(self):
     """Test default povms kwarg"""
     default_povms = [qi.random_unitary(2, seed=30 + i) for i in range(3)]
     basis = LocalMeasurementBasis("fitter_basis", default_povms=default_povms)
     for i, povm in enumerate(default_povms):
         adjoint = povm.adjoint()
         for outcome in range(2):
             state = qi.Statevector.from_int(outcome, dims=2**adjoint.num_qubits)
             state = state.evolve(adjoint)
             basis_state = qi.DensityMatrix(basis.matrix([i], outcome, [0]))
             fid = qi.state_fidelity(state, basis_state)
             self.assertTrue(isclose(fid, 1))
Ejemplo n.º 23
0
 def test_single_qubit(self):
     desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3)]
     qr = QuantumRegister(1, "qr")
     qc = QuantumCircuit(qr)
     qc.initialize(desired_vector, [qr[0]])
     job = execute(qc, BasicAer.get_backend('statevector_simulator'))
     result = job.result()
     statevector = result.get_statevector()
     fidelity = state_fidelity(statevector, desired_vector)
     self.assertGreater(
         fidelity, self._desired_fidelity,
         "Initializer has low fidelity {0:.2g}.".format(fidelity))
Ejemplo n.º 24
0
 def test_deterministic_state(self):
     desired_vector = [0, 1, 0, 0]
     qr = QuantumRegister(2, "qr")
     qc = QuantumCircuit(qr)
     qc.initialize(desired_vector, [qr[0], qr[1]])
     job = execute(qc, BasicAer.get_backend('statevector_simulator'))
     result = job.result()
     statevector = result.get_statevector()
     fidelity = state_fidelity(statevector, desired_vector)
     self.assertGreater(
         fidelity, self._desired_fidelity,
         "Initializer has low fidelity {0:.2g}.".format(fidelity))
Ejemplo n.º 25
0
    def _compare_outcomes(self, circ):
        Provider = QCGPUProvider()
        backend_qcgpu = Provider.get_backend('statevector_simulator')
        statevector_qcgpu = execute(circ,
                                    backend_qcgpu).result().get_statevector()

        backend_qiskit = BasicAer.get_backend('statevector_simulator')
        statevector_qiskit = execute(
            circ, backend_qiskit).result().get_statevector()

        self.assertAlmostEqual(
            state_fidelity(statevector_qcgpu, statevector_qiskit), 1, 5)
Ejemplo n.º 26
0
 def test_uniform_superposition(self):
     desired_vector = [0.5, 0.5, 0.5, 0.5]
     qr = QuantumRegister(2, "qr")
     qc = QuantumCircuit(qr)
     qc.initialize(desired_vector, [qr[0], qr[1]])
     job = execute(qc, Aer.get_backend('statevector_simulator_py'))
     result = job.result()
     statevector = result.get_statevector()
     fidelity = state_fidelity(statevector, desired_vector)
     self.assertGreater(
         fidelity, self._desired_fidelity,
         "Initializer has low fidelity {0:.2g}.".format(fidelity))
Ejemplo n.º 27
0
 def test_ghz_state(self):
     desired_vector = [1/math.sqrt(2), 0, 0, 0, 0, 0, 0, 1/math.sqrt(2)]
     qr = QuantumRegister(3, "qr")
     qc = QuantumCircuit(qr)
     qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
     job = execute(qc, Aer.get_backend('statevector_simulator_py'))
     result = job.result()
     statevector = result.get_statevector()
     fidelity = state_fidelity(statevector, desired_vector)
     self.assertGreater(
         fidelity, self._desired_fidelity,
         "Initializer has low fidelity {0:.2g}.".format(fidelity))
Ejemplo n.º 28
0
    def test_mixed_batch_exp(self):
        """Test batch state and process tomography experiment"""
        # Subsystem unitaries
        state_op = qi.random_unitary(2, seed=321)
        chan_op = qi.random_unitary(2, seed=123)

        state_target = qi.Statevector(state_op.to_instruction())
        chan_target = qi.Choi(chan_op.to_instruction())

        state_exp = StateTomography(state_op)
        chan_exp = ProcessTomography(chan_op)
        batch_exp = BatchExperiment([state_exp, chan_exp])

        # Run batch experiments
        backend = AerSimulator(seed_simulator=9000)
        par_data = batch_exp.run(backend)
        self.assertExperimentDone(par_data)

        f_threshold = 0.95

        # Check state tomo results
        state_results = par_data.child_data(0).analysis_results()
        state = filter_results(state_results, "state").value

        # Check fit state fidelity
        state_fid = filter_results(state_results, "state_fidelity").value
        self.assertGreater(state_fid, f_threshold, msg="fit fidelity is low")

        # Manually check fidelity
        target_fid = qi.state_fidelity(state, state_target, validate=False)
        self.assertAlmostEqual(state_fid,
                               target_fid,
                               places=6,
                               msg="result fidelity is incorrect")

        # Check process tomo results
        chan_results = par_data.child_data(1).analysis_results()
        chan = filter_results(chan_results, "state").value

        # Check fit process fidelity
        chan_fid = filter_results(chan_results, "process_fidelity").value
        self.assertGreater(chan_fid, f_threshold, msg="fit fidelity is low")

        # Manually check fidelity
        target_fid = qi.process_fidelity(chan,
                                         chan_target,
                                         require_cp=False,
                                         require_tp=False)
        self.assertAlmostEqual(chan_fid,
                               target_fid,
                               places=6,
                               msg="result fidelity is incorrect")
Ejemplo n.º 29
0
    def test_hhl_diagonal(self, vector, use_circuit_library):
        """ hhl diagonal test """
        self.log.debug(
            'Testing HHL simple test in mode Lookup with statevector simulator'
        )

        matrix = [[1, 0], [0, 1]]

        # run NumPyLSsolver
        ref_result = NumPyLSsolver(matrix, vector).run()
        ref_solution = ref_result['solution']
        ref_normed = ref_solution / np.linalg.norm(ref_solution)

        # run hhl
        orig_size = len(vector)
        matrix, vector, truncate_powerdim, truncate_hermitian = HHL.matrix_resize(
            matrix, vector)

        # Initialize eigenvalue finding module
        eigs = TestHHL._create_eigs(matrix, 3, False, use_circuit_library)
        num_q, num_a = eigs.get_register_sizes()

        # Initialize initial state module
        init_state = Custom(num_q, state_vector=vector)

        # Initialize reciprocal rotation module
        reci = LookupRotation(negative_evals=eigs._negative_evals,
                              evo_time=eigs._evo_time)

        algo = HHL(matrix, vector, truncate_powerdim, truncate_hermitian, eigs,
                   init_state, reci, num_q, num_a, orig_size)
        if not use_circuit_library:
            warnings.filterwarnings('ignore', category=DeprecationWarning)
        hhl_result = algo.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                            seed_simulator=aqua_globals.random_seed,
                            seed_transpiler=aqua_globals.random_seed))
        if not use_circuit_library:
            warnings.filterwarnings('always', category=DeprecationWarning)

        hhl_solution = hhl_result['solution']
        hhl_normed = hhl_solution / np.linalg.norm(hhl_solution)

        # compare results
        fidelity = state_fidelity(ref_normed, hhl_normed)
        np.testing.assert_approx_equal(fidelity, 1, significant=5)

        self.log.debug('HHL solution vector:       %s', hhl_solution)
        self.log.debug('algebraic solution vector: %s', ref_solution)
        self.log.debug('fidelity HHL to algebraic: %s', fidelity)
        self.log.debug('probability of result:     %s',
                       hhl_result["probability_result"])
Ejemplo n.º 30
0
    def test_complex_3_qubit_circuit(self):
        def rand_angles():
            # pylint: disable=E1101
            return tuple(2 * numpy.pi * numpy.random.random(3) - numpy.pi)

        q = QuantumRegister(3)
        circ = QuantumCircuit(q)
        for j in range(3):
            circ.u3(*rand_angles(), q[j])

        rho, psi = run_circuit_and_tomography(circ, q, self.method)
        F_bell = state_fidelity(psi, rho, validate=False)
        self.assertAlmostEqual(F_bell, 1, places=1)
    def _run(self):
        evo_time = 1
        # get the groundtruth via simple matrix * vector
        state_out_exact = self._operator.evolve(self._initial_state.construct_circuit('vector'), evo_time, 'matrix', 0)

        qr = QuantumRegister(self._operator.num_qubits, name='q')
        circuit = self._initial_state.construct_circuit('circuit', qr)
        circuit += self._operator.evolve(
            None, evo_time, 'circuit', 1,
            quantum_registers=qr,
            expansion_mode='suzuki',
            expansion_order=self._expansion_order
        )

        result = self._quantum_instance.execute(circuit)
        state_out_dynamics = np.asarray(result.get_statevector(circuit))

        self._ret['score'] = state_fidelity(state_out_exact, state_out_dynamics)

        return self._ret