コード例 #1
0
ファイル: qasm_save_expval.py プロジェクト: ocaisa/qiskit-aer
    def test_save_expval_stabilizer_pauli(self, pauli):
        """Test Pauli expval for stabilizer circuit"""

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

        # Stabilizer test circuit
        state = qi.random_clifford(2, seed=SEED).to_circuit()
        oper = qi.Pauli(pauli)
        target = qi.Statevector(state).expectation_value(oper).real.round(10)

        # Snapshot circuit
        opts = self.BACKEND_OPTS.copy()
        circ = transpile(state, self.SIMULATOR)
        circ.save_expectation_value('expval', oper, [0, 1])
        qobj = assemble(circ)
        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)
            value = result.data(0)['expval']
            self.assertAlmostEqual(value, target)
コード例 #2
0
    def test_save_expval_stabilizer_hermitian(self, qubits):
        """Test expval for stabilizer circuit and Hermitian operator"""

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

        # Stabilizer test circuit
        state_circ = qi.random_clifford(3, seed=SEED).to_circuit()
        oper = qi.random_hermitian(4, traceless=True, seed=SEED)
        state = qi.Statevector(state_circ)
        target = state.expectation_value(oper, qubits).real

        # Snapshot circuit
        opts = self.BACKEND_OPTS.copy()
        method = opts.get('method', 'automatic')
        circ = transpile(state_circ, basis_gates=[
            'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'cx', 'cz', 'swap'])
        circ.save_expectation_value('expval', oper, qubits)
        qobj = assemble(circ)
        result = self.SIMULATOR.run(qobj, **opts).result()
        if method not in SUPPORTED_METHODS:
            self.assertFalse(result.success)
        else:
            self.assertTrue(result.success)
            value = result.data(0)['expval']
            self.assertAlmostEqual(value, target)
コード例 #3
0
 def random(self, num_qubits, rand_seed=None):
     """Generate a random group element"""
     self._num_qubits = num_qubits
     if self._group_gates_type:
         return random_cnotdihedral(num_qubits, seed=rand_seed)
     else:
         return random_clifford(num_qubits, seed=rand_seed)
コード例 #4
0
    def test_set_stabilizer(self, num_qubits):
        """Test SetStabilizer instruction"""

        SUPPORTED_METHODS = [
            'automatic', 'stabilizer'
        ]

        seed = 100
        save_label = 'state'

        target = qi.random_clifford(num_qubits, seed=seed)

        circ = QuantumCircuit(num_qubits)
        circ.set_stabilizer(target)
        circ.save_stabilizer(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.Clifford.from_dict(result.data(0)[save_label])
            self.assertEqual(value, target)
コード例 #5
0
    def test_optimize_cliffords(self):
        """Test OptimizeCliffords pass."""

        rng = np.random.default_rng(1234)
        for _ in range(20):
            # Create several random Cliffords
            cliffs = [random_clifford(3, rng) for _ in range(5)]

            # The first circuit contains these cliffords
            qc1 = QuantumCircuit(5)
            for cliff in cliffs:
                qc1.append(cliff, [4, 0, 2])
            self.assertEqual(qc1.count_ops()["clifford"], 5)

            # The second circuit is obtained by running the OptimizeCliffords pass.
            qc2 = PassManager(OptimizeCliffords()).run(qc1)
            self.assertEqual(qc2.count_ops()["clifford"], 1)

            # The third circuit contains the decompositions of Cliffods.
            qc3 = QuantumCircuit(5)
            for cliff in cliffs:
                qc3.append(cliff.to_circuit(), [4, 0, 2])
            self.assertNotIn("clifford", qc3.count_ops())

            # Check that qc1, qc2 and qc3 and their decompositions are all equivalent.
            self.assertTrue(Operator(qc1).equiv(Operator(qc1.decompose())))
            self.assertTrue(Operator(qc2).equiv(Operator(qc2.decompose())))
            self.assertTrue(Operator(qc3).equiv(Operator(qc3.decompose())))
            self.assertTrue(Operator(qc1).equiv(Operator(qc2)))
            self.assertTrue(Operator(qc1).equiv(Operator(qc3)))
コード例 #6
0
    def test_save_expval_var_stabilizer_pauli(self, pauli):
        """Test Pauli expval_var for stabilizer circuit"""

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

        # Stabilizer test circuit
        state_circ = qi.random_clifford(2, seed=SEED).to_circuit()
        oper = qi.Pauli(pauli)
        state = qi.Statevector(state_circ)
        expval = state.expectation_value(oper).real
        variance = state.expectation_value(oper ** 2).real - expval ** 2
        target = [expval, variance]

        # Snapshot circuit
        opts = self.BACKEND_OPTS.copy()
        method = opts.get('method', 'automatic')
        circ = transpile(state_circ, basis_gates=[
            'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'cx', 'cz', 'swap'])
        circ.save_expectation_value_variance('expval', oper, [0, 1])
        qobj = assemble(circ)
        result = self.SIMULATOR.run(qobj, **opts).result()
        if method not in SUPPORTED_METHODS:
            self.assertFalse(result.success)
        else:
            self.assertTrue(result.success)
            value = result.data(0)['expval']
            self.assertTrue(allclose(value, target))
コード例 #7
0
 def test_stabilizer_getitem(self):
     clifford = qi.random_clifford(4, seed=10)
     cliff_dict = clifford.to_dict()
     compat = cqi.StabilizerState(clifford)
     with self.assertWarns(DeprecationWarning):
         stabs = compat['stabilizer']
     self.assertEqual(stabs, cliff_dict['stabilizer'])
     with self.assertWarns(DeprecationWarning):
         destabs = compat['destabilizer']
     self.assertEqual(destabs, cliff_dict['destabilizer'])
コード例 #8
0
ファイル: test_save_expval.py プロジェクト: iris48/qiskit-aer
 def test_save_expval_stabilizer_hermitian(self, method, device, qubits):
     """Test expval for stabilizer circuit and Hermitian operator"""
     SEED = 7123
     circ = qi.random_clifford(3, seed=SEED).to_circuit()
     oper = qi.random_hermitian(4, traceless=True, seed=SEED)
     self._test_save_expval(circ,
                            oper,
                            qubits,
                            False,
                            method=method,
                            device=device)
コード例 #9
0
ファイル: test_save_expval.py プロジェクト: iris48/qiskit-aer
 def test_save_expval_var_stabilizer_pauli(self, method, device, pauli):
     """Test Pauli expval_var for stabilizer circuit"""
     SEED = 5832
     circ = qi.random_clifford(2, seed=SEED).to_circuit()
     oper = qi.Operator(qi.Pauli(pauli))
     qubits = [0, 1]
     self._test_save_expval(circ,
                            oper,
                            qubits,
                            True,
                            method=method,
                            device=device)
コード例 #10
0
ファイル: test_save_expval.py プロジェクト: iris48/qiskit-aer
 def test_save_expval_stabilizer_pauli_cache_blocking(
         self, method, device, pauli):
     """Test Pauli expval for stabilizer circuit"""
     SEED = 5832
     circ = qi.random_clifford(2, seed=SEED).to_circuit()
     oper = qi.Operator(qi.Pauli(pauli))
     qubits = [0, 1]
     self._test_save_expval(circ,
                            oper,
                            qubits,
                            False,
                            method=method,
                            device=device,
                            blocking_qubits=2,
                            max_parallel_threads=1)
コード例 #11
0
    def random_clifford_circuits(
        self, num_qubits: int, size: int = 1, rng: Optional[Union[int, Generator]] = None
    ):
        """Generate a list of random clifford circuits"""
        if num_qubits > 2:
            return [random_clifford(num_qubits, seed=rng).to_circuit() for _ in range(size)]

        if rng is None:
            rng = default_rng()

        if isinstance(rng, int):
            rng = default_rng(rng)

        if num_qubits == 1:
            samples = rng.integers(24, size=size)
            return [self.clifford_1_qubit_circuit(i) for i in samples]
        else:
            samples = rng.integers(11520, size=size)
            return [self.clifford_2_qubit_circuit(i) for i in samples]
コード例 #12
0
 def _sample_circuits(self,
                      lengths: Iterable[int],
                      seed: Optional[Union[int, Generator]] = None):
     """Return a list RB circuits for the given lengths.
     Args:
         lengths: A list of RB sequences lengths.
         seed: Seed or generator object for random number
               generation. If None default_rng will be used.
     Returns:
         List[QuantumCircuit]: A list of :class:`QuantumCircuit`s.
     """
     circuits = []
     for length in lengths if self._full_sampling else [lengths[-1]]:
         elements = [
             random_clifford(self.num_qubits, seed=seed)
             for _ in range(length)
         ]
         element_lengths = [len(elements)
                            ] if self._full_sampling else lengths
         circuits += self._generate_circuit(elements, element_lengths)
     return circuits
コード例 #13
0
ファイル: test_set_state.py プロジェクト: jwoehr/qiskit-aer
    def test_set_stabilizer_clifford(self, method, device, num_qubits):
        """Test SetStabilizer instruction"""
        backend = self.backend(method=method, device=device)

        seed = 100
        label = 'state'

        target = qi.random_clifford(num_qubits, seed=seed)

        circ = QuantumCircuit(num_qubits)
        circ.set_stabilizer(target)
        circ.save_clifford(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 = simdata[label]
        self.assertEqual(value, target)
コード例 #14
0
    def test_stabilizer_iterable_methods(self):
        """Test that the iterable magic methods and related dict properties
        work on the compatibility classes."""
        clifford = qi.random_clifford(4, seed=10)
        cliff_dict = clifford.to_dict()
        compat = cqi.StabilizerState(clifford)

        with self.assertWarns(DeprecationWarning):
            compat_keys = compat.keys()
        self.assertEqual(compat_keys, cliff_dict.keys())

        with self.assertWarns(DeprecationWarning):
            compat_iter = set(compat)
        self.assertEqual(compat_iter, set(cliff_dict))

        with self.assertWarns(DeprecationWarning):
            compat_items = compat.items()
        self.assertEqual(sorted(compat_items), sorted(cliff_dict.items()))

        with self.assertWarns(DeprecationWarning):
            compat_len = len(compat)
        self.assertEqual(compat_len, len(cliff_dict))
コード例 #15
0
ファイル: test_clifford.py プロジェクト: Cryoris/qiskit-terra
 def test_instruction_name(self):
     """Test to verify the correct clifford name is maintained
     after converting to instruction"""
     clifford = random_clifford(2, seed=777)
     self.assertEqual(clifford.to_instruction().name, str(clifford))
コード例 #16
0
def generate_data(size, shots, num_qubits, basis_gates, device, group=-1, limit=0, train=1):
    circ_set = []
    val_ideals = []
    val_noisys = []
    idxs = []
    sizes = []
    
    backend_1 = Aer.get_backend('qasm_simulator')
    #IBMQ.save_account('83a95fc7efba05f250ed50ff6bdf1638541ebd4f9e46396f26c8dc12f15b2331ea24d9db4f59c30b6e397c2268e40ddc1dae4772091baa73d7e99c91e8d8c56b')
    provider = IBMQ.load_account()
    backend_2 = provider.get_backend('ibmq_16_melbourne')
    
    if device:
        for i in range(size):
            qr = QuantumRegister(num_qubits, 'q')
            cr = ClassicalRegister(num_qubits, 'c')
            circ = QuantumCircuit(qr,cr)
            cliff = random_clifford(num_qubits)
            cliff = cliff.to_circuit()
            circ = circ.compose(cliff,inplace=False)
            circ.measure(qr[:],cr[:])
            circ_set.append(circ)
        execute(circ_set,backend_2,basis_gates=basis_gates,shots=shots)
        output = open('./circs/circ{n}tr{tr}bn{bn}.pkl'.format(n=num_qubits, tr=train, bn=group), 'wb')
        pickle.dump(circ_set, output)
        output.close()
    else:
        limit = 66
        pkl_file = open('./circs/circ{n}tr{tr}bn{bn}.pkl'.format(n=num_qubits, tr=train, bn=group), 'rb')
        circ_set = pickle.load(pkl_file)
        pkl_file.close()
        
        data = ((list(reversed(backend_2.jobs(limit)))[group]).result()).get_counts()
        data = list(data) #make sure it is a list of dicts

        for circ, result_noisy, i in zip(circ_set, data, range(size)):
            # print(result_noisy)
            result_ideal = execute(circ, backend_1, basis_gates=basis_gates, shots=shots).result()
            result_ideal = result_ideal.get_counts()
            
            #update dict of ideal and noisy
            temp_ideal = dict.fromkeys(result_ideal, 0)
            temp_noisy = dict.fromkeys(result_noisy, 0)
            result_ideal.update(temp_noisy)
            result_noisy.update(temp_ideal)
            idx = sorted(result_ideal)
            val_ideal = list(itemgetter(*idx)(result_ideal))
            val_noisy = list(itemgetter(*idx)(result_noisy))
            
            #append noisy prob for each index
            for k in range(len(idx)):
                idx[k] = list(idx[k])
                idx[k].append(val_noisy[k]/shots)
                
            sizes.append(len(idx))
                
            #convert idx from str to float
            idx = np.array(idx)
            idx = idx.astype(np.float64)
            idx = torch.from_numpy(idx)
            
            #list of tensors
            val_ideals.append(torch.Tensor(val_ideal, dtype=torch.float64)/shots)
            val_noisys.append(torch.Tensor(val_noisy, dtype=torch.float64)/shots)
            idxs.append(idx)
        
        #pad noisy and ideal
        idxs = torch.nn.utils.rnn.pad_sequence(idxs, batch_first=True)
        val_ideals = torch.nn.utils.rnn.pad_sequence(val_ideals, batch_first=True)
        val_noisys = torch.nn.utils.rnn.pad_sequence(val_noisys, batch_first=True)
        
        #pack padded sequences
        pack_idxs = torch.nn.utils.rnn.pack_padded_sequence(idxs, lengths=sizes, batch_first=True, enforce_sorted=False)
        pack_ideals = torch.nn.utils.rnn.pack_padded_sequence(val_ideals, lengths=sizes, batch_first=True, enforce_sorted=False)
        pack_noisys = torch.nn.utils.rnn.pack_padded_sequence(val_noisys, lengths=sizes, batch_first=True, enforce_sorted=False)
        
        return (val_ideals, pack_idxs, sizes)
コード例 #17
0
 def test_stabilizer_eq(self):
     orig = qi.StabilizerState(qi.random_clifford(4, seed=10))
     compat = cqi.StabilizerState(orig.clifford)
     self.assertEqual(compat, orig)
     self.assertEqual(orig, compat)
コード例 #18
0
 def test_stabilizer_getattr(self):
     clifford = qi.random_clifford(4, seed=10)
     compat = cqi.StabilizerState(clifford)
     with self.assertWarns(DeprecationWarning):
         value = compat.keys()
     self.assertEqual(value, clifford.to_dict().keys())
コード例 #19
0
 def test_stabilizer_copy(self):
     clifford = qi.random_clifford(4, seed=10)
     compat = cqi.StabilizerState(clifford)
     cpy = copy.copy(compat)
     self.assertEqual(cpy, compat)
コード例 #20
0
 def setup(self, nqubits_length):
     (nqubits, length) = map(int, nqubits_length.split(','))
     self.random_clifford = \
         [random_clifford(nqubits) for _ in range(length)]
コード例 #21
0
 def time_random_clifford(self, nqubits_length):
     (nqubits, length) = map(int, nqubits_length.split(','))
     for _ in range(length):
         random_clifford(nqubits)
コード例 #22
0
 def time_evolve_by_clifford(self, num_qubits, __):
     c1 = random_clifford(num_qubits)
     self.pl1.evolve(c1)