コード例 #1
0
    def test_save_density_matrix(self, method, device):
        """Test save density matrix for instruction"""
        backend = self.backend(method=method, device=device)

        # Stabilizer test circuit
        circ = QuantumCircuit(3)
        circ.h(0)
        circ.sdg(0)
        circ.cx(0, 1)
        circ.cx(0, 2)

        # Target statevector
        target = qi.DensityMatrix(circ)

        # Add save to circuit
        label = 'state'
        circ.save_density_matrix(label=label)

        # Run
        result = backend.run(transpile(circ, backend, optimization_level=0),
                             shots=1).result()
        self.assertTrue(result.success)
        simdata = result.data(0)
        self.assertIn(label, simdata)
        value = qi.DensityMatrix(simdata[label])
        self.assertEqual(value, target)
コード例 #2
0
    def test_save_density_matrix_conditional(self, method, device):
        """Test conditional save density matrix instruction"""
        backend = self.backend(method=method, device=device)

        # Stabilizer test circuit
        label = 'state'
        circ = QuantumCircuit(2)
        circ.h(0)
        circ.sdg(0)
        circ.cx(0, 1)
        circ.measure_all()
        circ.save_density_matrix(label=label, conditional=True)

        # Target statevector
        target = {
            '0x0': qi.DensityMatrix(np.diag([1, 0, 0, 0])),
            '0x3': qi.DensityMatrix(np.diag([0, 0, 0, 1]))
        }

        # Run
        result = backend.run(transpile(circ, backend, optimization_level=0),
                             shots=1).result()
        self.assertTrue(result.success)
        simdata = result.data(0)
        self.assertIn(label, simdata)
        for key, state in simdata[label].items():
            self.assertIn(key, target)
            self.assertEqual(qi.DensityMatrix(state), target[key])
コード例 #3
0
    def test_local_mbasis_qubit_povms(self):
        """Test qubit povms kwarg"""
        size = 2
        outcomes = 2
        qubits = [0, 2]
        qubit_povms = {
            qubits[0]: [
                [qi.random_density_matrix(2, seed=30 + i + j) for i in range(outcomes)]
                for j in range(size)
            ],
            qubits[1]: [
                [qi.random_density_matrix(2, seed=40 + i + j) for i in range(outcomes)]
                for j in range(size)
            ],
        }
        basis = LocalMeasurementBasis("fitter_basis", qubit_povms=qubit_povms)

        # Check states
        indices = it.product(range(size), repeat=len(qubits))
        outcomes = it.product(range(outcomes), repeat=len(qubits))
        for index in indices:
            for outcome in outcomes:
                basis_state = qi.DensityMatrix(
                    basis.matrix(index, self._outcome_tup_to_int(outcome), qubits)
                )
                target0 = qi.DensityMatrix(qubit_povms[qubits[0]][index[0]][outcome[0]])
                target1 = qi.DensityMatrix(qubit_povms[qubits[1]][index[1]][outcome[1]])
                target = target0.expand(target1)
                fid = qi.state_fidelity(basis_state, target)
                self.assertTrue(isclose(fid, 1))
コード例 #4
0
    def test_save_density_matrix_pershot(self, method, device):
        """Test pershot save density matrix instruction"""
        backend = self.backend(method=method, device=device)

        # Stabilizer test circuit
        circ = QuantumCircuit(1)
        circ.x(0)
        circ.reset(0)
        circ.h(0)
        circ.sdg(0)

        # Target statevector
        target = qi.DensityMatrix(circ)

        # Add save
        label = 'state'
        circ.save_density_matrix(label=label, pershot=True)

        # Run
        shots = 10
        result = backend.run(transpile(circ, backend, optimization_level=0),
                             shots=shots).result()
        self.assertTrue(result.success)
        simdata = result.data(0)
        self.assertIn(label, simdata)
        value = simdata[label]
        for state in value:
            self.assertEqual(qi.DensityMatrix(state), target)
コード例 #5
0
    def test_kraus_circuit_noise(self, method, device):
        """Test simulation with Kraus quantum errors in circuit."""
        backend = self.backend(method=method, device=device)
        shots = 1000
        error0 = noise.amplitude_damping_error(0.05)
        error1 = noise.amplitude_damping_error(0.15)
        error01 = error1.tensor(error0)

        # Target Circuit 0
        tc0 = QuantumCircuit(2)
        tc0.h(0)
        tc0.append(qi.Kraus(error0), [0])
        tc0.cx(0, 1)
        tc0.append(qi.Kraus(error01), [0, 1])
        target_probs0 = qi.DensityMatrix(tc0).probabilities_dict()

        # Sim circuit 0
        qc0 = QuantumCircuit(2)
        qc0.h(0)
        qc0.append(error0, [0])
        qc0.cx(0, 1)
        qc0.append(error01, [0, 1])
        qc0.measure_all()

        # Target Circuit 1
        tc1 = QuantumCircuit(2)
        tc1.h(1)
        tc1.append(qi.Kraus(error0), [1])
        tc1.cx(1, 0)
        tc1.append(qi.Kraus(error01), [1, 0])
        target_probs1 = qi.DensityMatrix(tc1).probabilities_dict()

        # Sim circuit 1
        qc1 = QuantumCircuit(2)
        qc1.h(1)
        qc1.append(error0, [1])
        qc1.cx(1, 0)
        qc1.append(error01, [1, 0])
        qc1.measure_all()

        result = backend.run([qc0, qc1], shots=shots).result()
        self.assertSuccess(result)
        probs = [{
            key: val / shots
            for key, val in result.get_counts(i).items()
        } for i in range(2)]
        self.assertDictAlmostEqual(target_probs0, probs[0], delta=0.1)
        self.assertDictAlmostEqual(target_probs1, probs[1], delta=0.1)
コード例 #6
0
ファイル: test_noise.py プロジェクト: jwoehr/qiskit-aer
    def test_clifford_circuit_noise(self, method, device):
        """Test simulation with mixed Clifford quantum errors in circuit."""
        backend = self.backend(method=method, device=device)
        shots = 1000
        error1 = noise.QuantumError([
            ([(IGate(), [0])], 0.8),
            ([(Reset(), [0])], 0.1),
            ([(HGate(), [0])], 0.1)])

        error2 = noise.QuantumError([
            ([(IGate(), [0])], 0.75),
            ([(Reset(), [0])], 0.1),
            ([(Reset(), [1])], 0.1),
            ([(Reset(), [0]), (Reset(), [1])], 0.05)])

        qc = QuantumCircuit(2)
        qc.h(0)
        qc.append(error1, [0])
        qc.cx(0, 1)
        qc.append(error2, [0, 1])
        target_probs = qi.DensityMatrix(qc).probabilities_dict()

        # Add measurement
        qc.measure_all()
        result = backend.run(qc, shots=shots).result()
        self.assertSuccess(result)
        probs = {key: val / shots for key, val in result.get_counts(0).items()}
        self.assertDictAlmostEqual(target_probs, probs, delta=0.1)
コード例 #7
0
 def test_density_matrix_snapshot_ideal(self):
     seed = 500
     op = qi.random_unitary(8, seed=seed)
     circ = QuantumCircuit(3)
     circ.append(op, [0, 1, 2])
     method = self.BACKEND_OPTS.get('method', 'automatic')
     label = 'density_matrix'
     snap_qargs = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1],
                   [2, 1, 0], [0, 1], [1, 0], [0, 2], [2, 0], [1, 2],
                   [2, 1], [0], [1], [2]]
     evolve_qargs = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [2, 0, 1], [1, 2, 0],
                     [2, 1, 0], [0, 1, 2], [1, 0, 2], [0, 2, 1], [1, 2, 0],
                     [2, 0, 1], [2, 1, 0], [0, 1, 2], [1, 0, 2], [2, 1, 0]]
     for squbits, equbits in zip(snap_qargs, evolve_qargs):
         with self.subTest(msg='qubits={}'.format(squbits)):
             num_qubits = len(squbits)
             tmp = circ.copy()
             tmp.append(Snapshot(label, 'density_matrix', num_qubits),
                        squbits)
             result = execute(tmp,
                              self.SIMULATOR,
                              backend_options=self.BACKEND_OPTS).result()
             if method not in QasmSnapshotDensityMatrixTests.SUPPORTED_QASM_METHODS:
                 self.assertFalse(result.success)
             else:
                 self.assertSuccess(result)
                 snapshots = result.data(0)['snapshots']['density_matrix']
                 value = qi.DensityMatrix(snapshots[label][0]['value'])
                 target = qi.DensityMatrix.from_label(3 * '0').evolve(
                     circ, equbits)
                 if num_qubits == 2:
                     target = qi.partial_trace(target, [2])
                 elif num_qubits == 1:
                     target = qi.partial_trace(target, [1, 2])
                 self.assertEqual(value, target)
コード例 #8
0
    def test_set_density_matrix(self, num_qubits):
        """Test SetDensityMatrix instruction"""

        SUPPORTED_METHODS = [
            'automatic', 'density_matrix', 'density_matrix_gpu',
            'density_matrix_thrust'
        ]

        seed = 100
        save_label = 'state'

        target = qi.random_density_matrix(2 ** num_qubits, seed=seed)

        circ = QuantumCircuit(num_qubits)
        circ.set_density_matrix(target)
        circ.save_density_matrix(label=save_label)

        # Run
        opts = self.BACKEND_OPTS.copy()
        qobj = assemble(circ, self.SIMULATOR)
        result = self.SIMULATOR.run(qobj, **opts).result()
        method = opts.get('method', 'automatic')
        if method not in SUPPORTED_METHODS:
            self.assertFalse(result.success)
        else:
            self.assertTrue(result.success)
            data = result.data(0)
            self.assertIn(save_label, data)
            value = qi.DensityMatrix(result.data(0)[save_label])
            self.assertAlmostEqual(value, target)
コード例 #9
0
    def _target_quantum_state(
            cls,
            circuit: QuantumCircuit,
            measurement_qubits: Optional[Sequence[int]] = None):
        """Return the state tomography target"""
        # Check if circuit contains measure instructions
        # If so we cannot return target state
        circuit_ops = circuit.count_ops()
        if "measure" in circuit_ops:
            return None

        perm_circ = cls._permute_circuit(circuit,
                                         measurement_qubits=measurement_qubits)

        try:
            if "reset" in circuit_ops or "kraus" in circuit_ops or "superop" in circuit_ops:
                state = qi.DensityMatrix(perm_circ)
            else:
                state = qi.Statevector(perm_circ)
        except QiskitError:
            # Circuit couldn't be simulated
            return None

        total_qubits = circuit.num_qubits
        if measurement_qubits:
            num_meas = len(measurement_qubits)
        else:
            num_meas = total_qubits
        if num_meas == total_qubits:
            return state

        # Trace out non-measurement qubits
        tr_qargs = range(num_meas, total_qubits)
        return qi.partial_trace(state, tr_qargs)
コード例 #10
0
    def test_save_expval_var_cptp_pauli(self, pauli):
        """Test Pauli expval_var for stabilizer circuit"""

        SUPPORTED_METHODS = [
            'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust'
        ]
        SEED = 5832

        opts = self.BACKEND_OPTS.copy()
        if opts.get('method') in SUPPORTED_METHODS:

            oper = qi.Pauli(pauli)

            # CPTP channel test circuit
            channel = qi.random_quantum_channel(4, seed=SEED)
            state_circ = QuantumCircuit(2)
            state_circ.append(channel, range(2))

            state = qi.DensityMatrix(state_circ)
            expval = state.expectation_value(oper).real
            variance = state.expectation_value(oper**2).real - expval**2
            target = [expval, variance]

            # Snapshot circuit
            circ = transpile(state_circ, self.SIMULATOR)
            circ.save_expectation_value_variance(oper, [0, 1], label='expval')
            qobj = assemble(circ)
            result = self.SIMULATOR.run(qobj, **opts).result()

            self.assertTrue(result.success)
            value = result.data(0)['expval']
            self.assertTrue(allclose(value, target))
コード例 #11
0
ファイル: test_save_expval.py プロジェクト: iris48/qiskit-aer
    def _test_save_expval(self, circuit, oper, qubits, variance, **options):
        """Test Pauli expval for stabilizer circuit"""
        backend = self.backend(**options)
        label = 'expval'

        # Format operator and target value
        circ = circuit.copy()
        oper = qi.Operator(oper)
        state = qi.DensityMatrix(circ)
        expval = state.expectation_value(oper, qubits).real

        if variance:
            var = state.expectation_value(oper**2, qubits).real - expval**2
            target = [expval, var]
            circ.save_expectation_value_variance(oper, qubits, label=label)
        else:
            target = expval
            circ.save_expectation_value(oper, qubits, label=label)

        result = backend.run(transpile(circ, backend, optimization_level=0),
                             shots=1).result()
        self.assertTrue(result.success)
        simdata = result.data(0)
        self.assertIn(label, simdata)
        value = simdata[label]
        if variance:
            self.assertTrue(allclose(value, target))
        else:
            self.assertAlmostEqual(value, target)
コード例 #12
0
 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))
コード例 #13
0
    def test_local_pbasis_qubit_states(self):
        """Test qubit states kwarg"""
        size = 3
        qubits = [0, 2]
        qubit_states = {
            qubits[0]: [qi.random_density_matrix(2, seed=30 + i) for i in range(size)],
            qubits[1]: [qi.random_statevector(2, seed=40 + i) for i in range(size)],
        }
        basis = LocalPreparationBasis("fitter_basis", qubit_states=qubit_states)

        # Check states
        indices = it.product(range(size), repeat=2)
        for index in indices:
            basis_state = qi.DensityMatrix(basis.matrix(index, qubits))
            target0 = qi.DensityMatrix(qubit_states[qubits[0]][index[0]])
            target1 = qi.DensityMatrix(qubit_states[qubits[1]][index[1]])
            target = target0.expand(target1)
            fid = qi.state_fidelity(basis_state, target)
            self.assertTrue(isclose(fid, 1))
コード例 #14
0
    def test_local_pbasis_default_and_qubit_states(self):
        """Test qubit states kwarg"""
        size = 3
        qubits = [2, 0]
        default_states = [qi.random_density_matrix(2, seed=20 + i) for i in range(size)]
        qubit_states = {2: [qi.random_statevector(2, seed=40 + i) for i in range(size)]}
        basis = LocalPreparationBasis(
            "fitter_basis", default_states=default_states, qubit_states=qubit_states
        )

        # Check states
        indices = it.product(range(size), repeat=2)
        states0 = qubit_states[qubits[0]] if qubits[0] in qubit_states else default_states
        states1 = qubit_states[qubits[1]] if qubits[1] in qubit_states else default_states
        for index in indices:
            basis_state = qi.DensityMatrix(basis.matrix(index, qubits))
            target = qi.DensityMatrix(states0[index[0]]).expand(states1[index[1]])
            fid = qi.state_fidelity(basis_state, target)
            self.assertTrue(isclose(fid, 1))
コード例 #15
0
    def _test_gate(self, gate, gates_dict, **options):
        """Test standard gates."""

        backend = self.backend(**options)

        gate_cls, num_angles, has_ctrl_qubits = gates_dict[gate]
        circuits = self.gate_circuits(gate_cls,
                                      num_angles=num_angles,
                                      has_ctrl_qubits=has_ctrl_qubits,
                                      rng=self.RNG)

        label = 'final'
        method = backend.options.method
        for circuit in circuits:
            if method == 'density_matrix':
                target = qi.DensityMatrix(circuit)
                circuit.save_density_matrix(label=label)
                state_fn = qi.DensityMatrix
                fidelity_fn = qi.state_fidelity
            elif method == 'stabilizer':
                target = qi.Clifford(circuit)
                circuit.save_stabilizer(label=label)
                state_fn = qi.Clifford.from_dict
                fidelity_fn = qi.process_fidelity
            elif method == 'unitary':
                target = qi.Operator(circuit)
                circuit.save_unitary(label=label)
                state_fn = qi.Operator
                fidelity_fn = qi.process_fidelity
            elif method == 'superop':
                target = qi.SuperOp(circuit)
                circuit.save_superop(label=label)
                state_fn = qi.SuperOp
                fidelity_fn = qi.process_fidelity
            else:
                target = qi.Statevector(circuit)
                circuit.save_statevector(label=label)
                state_fn = qi.Statevector
                fidelity_fn = qi.state_fidelity

            result = backend.run(transpile(circuit,
                                           backend,
                                           optimization_level=0),
                                 shots=1).result()

            # Check results
            success = getattr(result, 'success', False)
            self.assertTrue(success)
            data = result.data(0)
            self.assertIn(label, data)
            value = state_fn(data[label])
            fidelity = fidelity_fn(target, value)
            self.assertGreater(fidelity, 0.9999)
コード例 #16
0
 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))
コード例 #17
0
    def test_save_density_matrix_pershot_conditional(self):
        """Test pershot conditional save density matrix instruction"""

        SUPPORTED_METHODS = [
            'automatic', 'statevector', 'statevector_gpu',
            'statevector_thrust', 'density_matrix', 'density_matrix_gpu',
            'density_matrix_thrust', 'matrix_product_state'
        ]

        # Stabilizer test circuit
        circ = QuantumCircuit(1)
        circ.x(0)
        circ.reset(0)
        circ.h(0)
        circ.sdg(0)

        # Target statevector
        target = qi.DensityMatrix(circ)

        # Add save
        save_key = 'state'
        circ.save_density_matrix(save_key, pershot=True, conditional=True)
        circ.measure_all()

        # Run
        shots = 10
        opts = self.BACKEND_OPTS.copy()
        qobj = assemble(circ, self.SIMULATOR, shots=shots)
        result = self.SIMULATOR.run(qobj, **opts).result()
        method = opts.get('method', 'automatic')
        if method not in SUPPORTED_METHODS:
            self.assertFalse(result.success)
        else:
            self.assertTrue(result.success)
            data = result.data(0)
            self.assertIn(save_key, data)
            value = result.data(0)[save_key]
            self.assertIn('0x0', value)
            for state in value['0x0']:
                self.assertAlmostEqual(qi.DensityMatrix(state), target)
コード例 #18
0
    def test_local_mbasis_default_and_qubit_states(self):
        """Test qubit and default povm kwarg"""
        size = 3
        outcomes = 2
        qubits = [2, 0]
        default_povms = (
            [
                [qi.random_statevector(2, seed=20 + i + j) for i in range(outcomes)]
                for j in range(size)
            ],
        )
        qubit_povms = {
            qubits[0]: [
                [qi.random_density_matrix(2, seed=30 + i + j) for i in range(outcomes)]
                for j in range(size)
            ],
            qubits[1]: [
                [qi.random_density_matrix(2, seed=40 + i + j) for i in range(outcomes)]
                for j in range(size)
            ],
        }
        basis = LocalMeasurementBasis(
            "fitter_basis", default_povms=default_povms, qubit_povms=qubit_povms
        )

        # Check states
        states0 = qubit_povms[qubits[0]] if qubits[0] in qubit_povms else default_povms
        states1 = qubit_povms[qubits[1]] if qubits[1] in qubit_povms else default_povms
        indices = it.product(range(size), repeat=2)
        outcomes = it.product(range(outcomes), repeat=len(qubits))
        for index in indices:
            for outcome in outcomes:
                basis_state = qi.DensityMatrix(
                    basis.matrix(index, self._outcome_tup_to_int(outcome), qubits)
                )
                target0 = qi.DensityMatrix(states0[index[0]][outcome[0]])
                target1 = qi.DensityMatrix(states1[index[1]][outcome[1]])
                target = target0.expand(target1)
                fid = qi.state_fidelity(basis_state, target)
                self.assertTrue(isclose(fid, 1))
コード例 #19
0
    def test_save_density_matrix_conditional(self):
        """Test conditional save density matrix instruction"""

        SUPPORTED_METHODS = [
            'automatic', 'statevector', 'statevector_gpu',
            'statevector_thrust', 'density_matrix', 'density_matrix_gpu',
            'density_matrix_thrust', 'matrix_product_state'
        ]

        # Stabilizer test circuit
        save_key = 'state'
        circ = QuantumCircuit(2)
        circ.h(0)
        circ.sdg(0)
        circ.cx(0, 1)
        circ.measure_all()
        circ.save_density_matrix(save_key, conditional=True)

        # Target statevector
        target = {
            '0x0': qi.DensityMatrix(np.diag([1, 0, 0, 0])),
            '0x3': qi.DensityMatrix(np.diag([0, 0, 0, 1]))
        }

        # Run
        opts = self.BACKEND_OPTS.copy()
        qobj = assemble(circ, self.SIMULATOR, shots=10)
        result = self.SIMULATOR.run(qobj, **opts).result()
        method = opts.get('method', 'automatic')
        if method not in SUPPORTED_METHODS:
            self.assertFalse(result.success)
        else:
            self.assertTrue(result.success)
            data = result.data(0)
            self.assertIn(save_key, data)
            for key, state in data[save_key].items():
                self.assertIn(key, target)
                self.assertAlmostEqual(qi.DensityMatrix(state), target[key])
コード例 #20
0
 def test_local_mbasis_default_statevector(self):
     """Test default povms kwarg"""
     size = 2
     outcomes = 3
     default_povms = [
         [qi.random_statevector(2, seed=30 + i + j) for j in range(outcomes)]
         for i in range(size)
     ]
     basis = LocalMeasurementBasis("fitter_basis", default_povms=default_povms)
     for i, povm in enumerate(default_povms):
         for outcome, effect in enumerate(povm):
             basis_state = qi.DensityMatrix(basis.matrix([i], outcome, [0]))
             fid = qi.state_fidelity(effect, basis_state)
             self.assertTrue(isclose(fid, 1))
コード例 #21
0
    def test_save_density_matrix(self):
        """Test save density matrix for instruction"""

        SUPPORTED_METHODS = [
            'automatic', 'statevector', 'statevector_gpu',
            'statevector_thrust', 'density_matrix', 'density_matrix_gpu',
            'density_matrix_thrust', 'matrix_product_state'
        ]

        # Stabilizer test circuit
        circ = QuantumCircuit(3)
        circ.h(0)
        circ.sdg(0)
        circ.cx(0, 1)
        circ.cx(0, 2)

        # Target statevector
        target = qi.DensityMatrix(circ)

        # Add save to circuit
        save_key = 'state'
        circ.save_density_matrix(save_key)

        # Run
        opts = self.BACKEND_OPTS.copy()
        qobj = assemble(circ, self.SIMULATOR)
        result = self.SIMULATOR.run(qobj, **opts).result()
        method = opts.get('method', 'automatic')
        if method not in SUPPORTED_METHODS:
            self.assertFalse(result.success)
        else:
            self.assertTrue(result.success)
            data = result.data(0)
            self.assertIn(save_key, data)
            value = qi.DensityMatrix(result.data(0)[save_key])
            self.assertAlmostEqual(value, target)
コード例 #22
0
    def test_pauli_gate(self, method, device, pauli):
        """Test multi-qubit Pauli gate."""
        pauli = qi.Pauli(pauli)
        circuit = QuantumCircuit(pauli.num_qubits)
        circuit.append(pauli, range(pauli.num_qubits))

        backend = self.backend(method=method, device=device)
        label = 'final'
        if method == 'density_matrix':
            target = qi.DensityMatrix(circuit)
            circuit.save_density_matrix(label=label)
            state_fn = qi.DensityMatrix
            fidelity_fn = qi.state_fidelity
        elif method == 'stabilizer':
            target = qi.Clifford(circuit)
            circuit.save_stabilizer(label=label)
            state_fn = qi.Clifford.from_dict
            fidelity_fn = qi.process_fidelity
        elif method == 'unitary':
            target = qi.Operator(circuit)
            circuit.save_unitary(label=label)
            state_fn = qi.Operator
            fidelity_fn = qi.process_fidelity
        elif method == 'superop':
            target = qi.SuperOp(circuit)
            circuit.save_superop(label=label)
            state_fn = qi.SuperOp
            fidelity_fn = qi.process_fidelity
        else:
            target = qi.Statevector(circuit)
            circuit.save_statevector(label=label)
            state_fn = qi.Statevector
            fidelity_fn = qi.state_fidelity

        result = backend.run(transpile(circuit, backend, optimization_level=0),
                             shots=1).result()

        # Check results
        success = getattr(result, 'success', False)
        self.assertTrue(success)
        data = result.data(0)
        self.assertIn(label, data)
        value = state_fn(data[label])
        fidelity = fidelity_fn(target, value)
        self.assertGreater(fidelity, 0.9999)
コード例 #23
0
    def test_set_density_matrix(self, method, device, num_qubits):
        """Test SetDensityMatrix instruction"""
        backend = self.backend(method=method, device=device)

        seed = 100
        label = 'state'

        target = qi.random_density_matrix(2**num_qubits, seed=seed)

        circ = QuantumCircuit(num_qubits)
        circ.set_density_matrix(target)
        circ.save_density_matrix(label=label)

        # Run
        result = backend.run(transpile(circ, backend, optimization_level=0),
                             shots=1).result()
        self.assertTrue(result.success)
        simdata = result.data(0)
        self.assertIn(label, simdata)
        value = qi.DensityMatrix(simdata[label])
        self.assertEqual(value, target)