コード例 #1
0
    def test_circuit_multi(self):
        """Test circuit multi regs declared at start."""
        qreg0 = QuantumRegister(2, 'q0')
        creg0 = ClassicalRegister(2, 'c0')
        qreg1 = QuantumRegister(2, 'q1')
        creg1 = ClassicalRegister(2, 'c1')
        circ = QuantumCircuit(qreg0, qreg1)
        circ.x(qreg0[1])
        circ.x(qreg1[0])

        meas = QuantumCircuit(qreg0, qreg1, creg0, creg1)
        meas.measure(qreg0, creg0)
        meas.measure(qreg1, creg1)

        qc = circ + meas

        backend_sim = BasicAer.get_backend('qasm_simulator')

        result = execute(qc, backend_sim, seed_transpiler=34342).result()
        counts = result.get_counts(qc)

        target = {'01 10': 1024}

        backend_sim = BasicAer.get_backend('statevector_simulator')
        result = execute(circ, backend_sim, seed_transpiler=3438).result()
        state = result.get_statevector(circ)

        backend_sim = BasicAer.get_backend('unitary_simulator')
        result = execute(circ, backend_sim, seed_transpiler=3438).result()
        unitary = result.get_unitary(circ)

        self.assertEqual(counts, target)
        self.assertAlmostEqual(state_fidelity(Statevector.from_label('0110'),
                                              state),
                               1.0,
                               places=7)
        self.assertAlmostEqual(process_fidelity(Operator.from_label('IXXI'),
                                                unitary),
                               1.0,
                               places=7)
コード例 #2
0
    def test_plugin_configuration(self):
        """Tests plugin with a custom configuration."""
        config = {
            "network_layout": "sequ",
            "connectivity_type": "full",
            "depth": 0,
            "seed": 12345,
            "optimizer": SLSQP(),
        }
        transpiler_pass = UnitarySynthesis(
            basis_gates=["rx", "ry", "rz", "cx"],
            method="aqc",
            plugin_config=config)

        dag = circuit_to_dag(self._qc)
        dag = transpiler_pass.run(dag)

        approx_circuit = dag_to_circuit(dag)
        approx_unitary = Operator(approx_circuit).data

        np.testing.assert_array_almost_equal(self._target_unitary,
                                             approx_unitary, 3)
コード例 #3
0
    def _fidelity_result(evals, evecs, target, qpt=False):
        """Faster computation of fidelity from eigen decomposition"""
        # Format target to statevector or densitymatrix array
        trace = np.sqrt(len(evals)) if qpt else 1
        name = "process_fidelity" if qpt else "state_fidelity"
        if target is None:
            raise AnalysisError("No target state provided")
        if isinstance(target, QuantumChannel):
            target_state = Choi(target).data / trace
        elif isinstance(target, BaseOperator):
            target_state = np.ravel(Operator(target), order="F") / np.sqrt(trace)
        else:
            target_state = np.array(target)

        if target_state.ndim == 1:
            rho = evecs @ (evals / trace * evecs).T.conj()
            fidelity = np.real(target_state.conj() @ rho @ target_state)
        else:
            sqrt_rho = evecs @ (np.sqrt(evals / trace) * evecs).T.conj()
            eig = la.eigvalsh(sqrt_rho @ target_state @ sqrt_rho)
            fidelity = np.sum(np.sqrt(np.maximum(eig, 0))) ** 2
        return AnalysisResultData(name, fidelity)
コード例 #4
0
    def __init__(self):
        # Initialize Registers
        self.code = QuantumRegister(5, name="code")
        self.syndrm = QuantumRegister(4, name="syndrome")

        # Build Circuit Components
        self.encoder_ckt = self.build_encoder()
        self.syndrome_ckt = self.build_syndrome()
        self.correction_ckt = self.build_correction()
        self.decoder_ckt = self.encoder_ckt.mirror()

        # Build Noisy Channel
        self.noise_ckt = QuantumCircuit(self.code, self.syndrm)
        for i in range(5):
            self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[i]],
                                   label='noise')

        # Compose Full Circuit
        circ = QuantumCircuit(self.code, self.syndrm)
        circ.barrier()
        self.circuit = self.encoder_ckt + circ + self.noise_ckt + circ + self.syndrome_ckt
        self.circuit = self.circuit + circ + self.correction_ckt + circ + self.decoder_ckt
コード例 #5
0
    def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None):
        r"""Return controlled version of gate

        Args:
            num_ctrl_qubits (int): number of controls to add to gate (default=1)
            label (str): optional gate label
            ctrl_state (int or str or None): The control state in decimal or as a
                bit string (e.g. '1011'). If None, use 2**num_ctrl_qubits-1.

        Returns:
            UnitaryGate: controlled version of gate.

        Raises:
            QiskitError: Invalid ctrl_state.
            ExtensionError: Non-unitary controlled unitary.
        """
        cmat = _compute_control_matrix(self.to_matrix(),
                                       num_ctrl_qubits,
                                       ctrl_state=None)
        iso = isometry.Isometry(cmat, 0, 0)
        cunitary = ControlledGate('c-unitary',
                                  num_qubits=self.num_qubits + num_ctrl_qubits,
                                  params=[cmat],
                                  label=label,
                                  num_ctrl_qubits=num_ctrl_qubits,
                                  definition=iso.definition,
                                  ctrl_state=ctrl_state,
                                  base_gate=self.copy())
        from qiskit.quantum_info import Operator
        # hack to correct global phase; should fix to prevent need for correction here
        pmat = (Operator(iso.inverse()).data @ cmat)
        diag = numpy.diag(pmat)
        if not numpy.allclose(diag, diag[0]):
            raise ExtensionError('controlled unitary generation failed')
        phase = numpy.angle(diag[0])
        if phase:
            # need to apply to _definition since open controls creates temporary definition
            cunitary._definition.global_phase = phase
        return cunitary
コード例 #6
0
 def test_2q_hamiltonian(self):
     """test 2 qubit hamiltonian"""
     qr = QuantumRegister(2)
     cr = ClassicalRegister(2)
     qc = QuantumCircuit(qr, cr)
     matrix = Operator.from_label("XY")
     qc.x(qr[0])
     theta = Parameter("theta")
     uni2q = HamiltonianGate(matrix, theta)
     qc.append(uni2q, [qr[0], qr[1]])
     qc2 = qc.bind_parameters({theta: -np.pi / 2})
     dag = circuit_to_dag(qc2)
     nodes = dag.two_qubit_ops()
     self.assertEqual(len(nodes), 1)
     dnode = nodes[0]
     self.assertIsInstance(dnode.op, HamiltonianGate)
     self.assertEqual(dnode.qargs, [qr[0], qr[1]])
     # Equality based on Pauli exponential identity
     np.testing.assert_array_almost_equal(dnode.op.to_matrix(),
                                          1j * matrix.data)
     qc3 = dag_to_circuit(dag)
     self.assertEqual(qc2, qc3)
コード例 #7
0
ファイル: test_measures.py プロジェクト: Cryoris/qiskit-terra
    def test_diamond_norm(self, num_qubits):
        """Test the diamond_norm for {num_qubits}-qubit pauli channel."""
        try:
            import cvxpy
        except ImportError:
            # Skip test if CVXPY not installed
            self.skipTest("CVXPY not installed.")

        # Pauli channels have an analytic expression for the
        # diamond norm so we can easily test it
        op = Choi(np.zeros((4 ** num_qubits, 4 ** num_qubits)))
        labels = [num_qubits * i for i in ['I', 'X', 'Y', 'Z']]
        coeffs = [-1.0, 0.5, 2.5, -0.1]
        for coeff, label in zip(coeffs, labels):
            op = op + coeff * Choi(Operator.from_label(label))
        target = np.sum(np.abs(coeffs))

        try:
            value = diamond_norm(op)
            self.assertAlmostEqual(value, target, places=4)
        except cvxpy.SolverError:
            self.skipTest("CVXPY solver failed.")
コード例 #8
0
    def run(self, dag):
        """Run the Optimize1qGatesDecomposition pass on `dag`.

        Args:
            dag (DAGCircuit): the DAG to be optimized.

        Returns:
            DAGCircuit: the optimized DAG.
        """
        if not self.basis:
            LOG.info("Skipping pass because no basis is set")
            return dag
        decomposer = OneQubitEulerDecomposer(self.basis)
        runs = dag.collect_runs(self.euler_basis_names[self.basis])
        runs = _split_runs_on_parameters(runs)
        for run in runs:
            if len(run) <= 1:
                params = run[0].op.params
                # Remove single identity gates
                if run[0].op.name in self.euler_basis_names[
                        self.basis] and len(params) > 0 and np.array_equal(
                            run[0].op.to_matrix(), np.eye(2)):
                    dag.remove_op_node(run[0])
                # Don't try to optimize a single 1q gate
                continue
            q = QuantumRegister(1, "q")
            qc = QuantumCircuit(1)
            for gate in run:
                qc.append(gate.op, [q[0]], [])

            operator = Operator(qc)
            new_circ = decomposer(operator)
            new_dag = circuit_to_dag(new_circ)
            dag.substitute_node_with_dag(run[0], new_dag)
            # Delete the other nodes in the run
            for current_node in run[1:]:
                dag.remove_op_node(current_node)
        return dag
コード例 #9
0
    def test_open_controlled_to_matrix(self, gate_class, ctrl_state):
        """Test open controlled to_matrix."""
        num_free_params = len(_get_free_params(gate_class.__init__,
                                               ignore=['self']))
        free_params = [0.1 * i for i in range(1, num_free_params + 1)]
        if gate_class in [MCU1Gate, MCPhaseGate]:
            free_params[1] = 3
        elif gate_class in [MCXGate]:
            free_params[0] = 3
        cgate = gate_class(*free_params)
        cgate.ctrl_state = ctrl_state

        base_mat = Operator(cgate.base_gate).data
        if gate_class == CUGate:  # account for global phase
            base_mat = np.array(base_mat) * np.exp(1j * cgate.params[3])

        target = _compute_control_matrix(base_mat, cgate.num_ctrl_qubits,
                                         ctrl_state=ctrl_state)
        try:
            actual = cgate.to_matrix()
        except CircuitError as cerr:
            self.skipTest(cerr)
        self.assertTrue(np.allclose(actual, target))
コード例 #10
0
 def levelOperator(
         self,
         Level_Num):  #Gives the unitary representation of level =Level_Num
     QC = self.level(Level_Num)
     leveloperator = Operator(QC)
     return leveloperator
コード例 #11
0
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from matplotlib import pyplot as plt
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Operator

import numpy as np
from numpy import sqrt

sim_qasm = Aer.get_backend('qasm_simulator')

U1_op = Operator([[0.5, 0.5, 0.5, 0.5], [0, 0, 1 / sqrt(2), -1 / sqrt(2)],
                  [1 / sqrt(2), -1 / sqrt(2), 0, 0], [0.5, 0.5, -0.5, -0.5]])

U1_q = QuantumRegister(2)
U1_c = QuantumCircuit(U1_q, name='U1')
U1_c.unitary(U1_op, [0, 1], label='label')
U1 = U1_c.to_gate()


def construct_encode(U):
    return U.control(1)


def construct_decode(U):
    # circ = QuantumCircuit(3, name='_decode')
    circ = QuantumCircuit(3, name=U.name + '_decode')
    U_dag = U.inverse()
    circ.x(0)
    circ.append(U_dag.control(1), [0, 1, 2])
    circ.x(0)
    return circ.to_gate()
コード例 #12
0
    return M_0_E


a, b = np.pi / 2, np.pi / 2
M_0_E = M_0_Eve(a, b)
M_1_E = np.matrix(([-complex(0, 1) / sqrt(2),
                    1 / sqrt(2)], [complex(0, 1) / sqrt(2), 1 / sqrt(2)]))
ZERO_E = np.zeros([2, 2])
# U_E is an identity matrix (default)
U_E = np.matrix(
    np.vstack((np.hstack((M_0_E, ZERO_E)), np.hstack((ZERO_E, M_1_E)))))
U_E_dagger = np.matrix(U_E).H.T
print("U_E: \n", U_E)
print("U_E_dagger: \n", U_E_dagger)
# Operator to gate
U1_op = Operator(U_E)
print("U_E to gate: ", U1_op)

#########################################################################################
#                                        rho                                            #
#########################################################################################
# Alice
rho_i = np.matrix(alice_bits * np.reshape(alice_bits, (1, 4)))
print("rho: \n", rho_i)
# Alice + Bob
rho_i_prime = 0.5 * (rho_i + U_epi * rho_i * U_epi_dagger)
print("rho_i_prime: \n", rho_i_prime)
# Eve mapping "rho_i_prime" --> "rho_E_prime" --> send to Bob to decode --> "rho_E_double_prime" --> measure --> "phi_j"
rho_E_double_prime = 0.5 * (U_E * rho_i * U_E_dagger + U_epi_dagger * U_E *
                            U_epi * rho_i * U_epi_dagger * U_E_dagger * U_epi)
print("rho_E_double_prime: \n", rho_E_double_prime)
コード例 #13
0
    def run(self, dag):
        """Run the ConsolidateBlocks pass on `dag`.

        Iterate over each block and replace it with an equivalent Unitary
        on the same wires.
        """
        if self.decomposer is None:
            return dag

        # compute ordered indices for the global circuit wires
        global_index_map = {wire: idx for idx, wire in enumerate(dag.qubits)}
        blocks = self.property_set["block_list"]
        basis_gate_name = self.decomposer.gate.name
        all_block_gates = set()
        for block in blocks:
            if len(block) == 1 and (self.basis_gates and block[0].name not in self.basis_gates):
                all_block_gates.add(block[0])
                dag.substitute_node(block[0], UnitaryGate(block[0].op.to_matrix()))
            else:
                basis_count = 0
                outside_basis = False
                block_qargs = set()
                block_cargs = set()
                for nd in block:
                    block_qargs |= set(nd.qargs)
                    if isinstance(nd, DAGOpNode) and nd.op.condition:
                        block_cargs |= set(nd.op.condition[0])
                    all_block_gates.add(nd)
                q = QuantumRegister(len(block_qargs))
                qc = QuantumCircuit(q)
                if block_cargs:
                    c = ClassicalRegister(len(block_cargs))
                    qc.add_register(c)
                block_index_map = self._block_qargs_to_indices(block_qargs, global_index_map)
                for nd in block:
                    if nd.op.name == basis_gate_name:
                        basis_count += 1
                    if self.basis_gates and nd.op.name not in self.basis_gates:
                        outside_basis = True
                    qc.append(nd.op, [q[block_index_map[i]] for i in nd.qargs])
                unitary = UnitaryGate(Operator(qc))

                max_2q_depth = 20  # If depth > 20, there will be 1q gates to consolidate.
                if (  # pylint: disable=too-many-boolean-expressions
                    self.force_consolidate
                    or unitary.num_qubits > 2
                    or self.decomposer.num_basis_gates(unitary) < basis_count
                    or len(block) > max_2q_depth
                    or (self.basis_gates is not None and outside_basis)
                ):
                    dag.replace_block_with_op(block, unitary, block_index_map, cycle_check=False)
        # If 1q runs are collected before consolidate those too
        runs = self.property_set["run_list"] or []
        for run in runs:
            if run[0] in all_block_gates:
                continue
            if len(run) == 1 and self.basis_gates and run[0].name not in self.basis_gates:
                dag.substitute_node(run[0], UnitaryGate(run[0].op.to_matrix()))
            else:
                qubit = run[0].qargs[0]
                operator = run[0].op.to_matrix()
                already_in_block = False
                for gate in run[1:]:
                    if gate in all_block_gates:
                        already_in_block = True
                    operator = gate.op.to_matrix().dot(operator)
                if already_in_block:
                    continue
                unitary = UnitaryGate(operator)
                dag.replace_block_with_op(run, unitary, {qubit: 0}, cycle_check=False)
        return dag
コード例 #14
0
ファイル: matrix_op.py プロジェクト: wbclark/qiskit-terra
 def _expand_dim(self, num_qubits: int) -> 'MatrixOp':
     identity = np.identity(2**num_qubits, dtype=complex)
     return MatrixOp(self.primitive.tensor(Operator(identity)),
                     coeff=self.coeff)  # type: ignore
コード例 #15
0
#!/usr/bin/env python
# coding: utf-8

# In[140]:

from qiskit import *
from qiskit.quantum_info import Operator, average_gate_fidelity
from math import pi
import numpy as np
import cmath

a1 = complex(0, 1)
op_1 = Operator([[a1, 0], [0, a1]])

from qiskit.visualization import plot_bloch_multivector, plot_histogram

qc = QuantumCircuit(2, 2)
# Applied H-gate = iRx(pi)Ry(pi/2):
#Applied X-gate = iRx(pi)
# here unitary gate is global phase i
qc.ry(pi / 2, 0)
qc.rx(pi, 0)
qc.unitary(op_1, [0])

# Applied C-NOT gate to both qubits
qc.cx(0, 1)
# Applied X-gate to first qubit
qc.rx(pi, 0)
qc.unitary(op_1, [0])

qc.draw()
コード例 #16
0
 def test_open_controlled_unitary_z(self, num_ctrl_qubits, ctrl_state):
     """Test that UnitaryGate with control returns params."""
     umat = np.array([[1, 0], [0, -1]])
     ugate = UnitaryGate(umat).control(num_ctrl_qubits, ctrl_state=ctrl_state)
     ref_mat = _compute_control_matrix(umat, num_ctrl_qubits, ctrl_state=ctrl_state)
     self.assertTrue(matrix_equal(Operator(ugate).data, ref_mat))
コード例 #17
0
 def test_cry_definition(self):
     """Test cry gate matrix and definition."""
     circ = QuantumCircuit(2)
     circ.cry(1, 0, 1)
     decomposed_circ = circ.decompose()
     self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
コード例 #18
0
    def test_rotation_gates(self):
        """Test controlled rotation gates"""
        import qiskit.extensions.standard.u1 as u1
        import qiskit.extensions.standard.rx as rx
        import qiskit.extensions.standard.ry as ry
        import qiskit.extensions.standard.rz as rz
        num_ctrl = 2
        num_target = 1
        qreg = QuantumRegister(num_ctrl + num_target)

        theta = pi / 2
        gu1 = u1.U1Gate(theta)
        grx = rx.RXGate(theta)
        gry = ry.RYGate(theta)
        grz = rz.RZGate(theta)

        ugu1 = ac._unroll_gate(gu1, ['u1', 'u3', 'cx'])
        ugrx = ac._unroll_gate(grx, ['u1', 'u3', 'cx'])
        ugry = ac._unroll_gate(gry, ['u1', 'u3', 'cx'])
        ugrz = ac._unroll_gate(grz, ['u1', 'u3', 'cx'])
        ugrz.params = grz.params

        cgu1 = ugu1.control(num_ctrl)
        cgrx = ugrx.control(num_ctrl)
        cgry = ugry.control(num_ctrl)
        cgrz = ugrz.control(num_ctrl)

        for gate, cgate in zip([gu1, grx, gry, grz], [cgu1, cgrx, cgry, cgrz]):
            with self.subTest(i=gate.name):
                if gate.name == 'rz':
                    iden = Operator.from_label('I')
                    zgen = Operator.from_label('Z')
                    op_mat = (np.cos(0.5 * theta) * iden -
                              1j * np.sin(0.5 * theta) * zgen).data
                else:
                    op_mat = Operator(gate).data
                ref_mat = Operator(cgate).data
                cop_mat = _compute_control_matrix(op_mat, num_ctrl)
                self.assertTrue(
                    matrix_equal(cop_mat, ref_mat, ignore_phase=True))
                cqc = QuantumCircuit(num_ctrl + num_target)
                cqc.append(cgate, cqc.qregs[0])
                dag = circuit_to_dag(cqc)
                unroller = Unroller(['u3', 'cx'])
                uqc = dag_to_circuit(unroller.run(dag))
                self.log.info('%s gate count: %d', cgate.name, uqc.size())
                self.log.info('\n%s', str(uqc))
                # these limits could be changed
                if gate.name == 'ry':
                    self.assertTrue(uqc.size() <= 32)
                elif gate.name == 'rz':
                    self.assertTrue(uqc.size() <= 40)
                else:
                    self.assertTrue(uqc.size() <= 20)
        qc = QuantumCircuit(qreg, name='composite')
        qc.append(grx.control(num_ctrl), qreg)
        qc.append(gry.control(num_ctrl), qreg)
        qc.append(gry, qreg[0:gry.num_qubits])
        qc.append(grz.control(num_ctrl), qreg)

        dag = circuit_to_dag(qc)
        unroller = Unroller(['u3', 'cx'])
        uqc = dag_to_circuit(unroller.run(dag))
        print(uqc.size())
        self.log.info('%s gate count: %d', uqc.name, uqc.size())
        self.assertTrue(uqc.size() <= 93)  # this limit could be changed
コード例 #19
0
 def test_cu3_definition(self):
     """Test cu3 gate matrix and definition."""
     circ = QuantumCircuit(2)
     circ.append(CU3Gate(1, 1, 1), [0, 1])
     decomposed_circ = circ.decompose()
     self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
コード例 #20
0
 def test_repeat_global_phase(self, num):
     """Test the global phase is properly handled upon repeat."""
     phase = 0.123
     qc = QuantumCircuit(1, global_phase=phase)
     expected = np.exp(1j * phase * num) * np.identity(2)
     np.testing.assert_array_almost_equal(Operator(qc.repeat(num)).data, expected)
コード例 #21
0
    from qiskit import QuantumCircuit
    from qiskit.quantum_info import Operator
    #import numpy as np
    
    n = 3 #number of qubits
    
    qs = QuantumCircuit(n)
    
    qs.h(1)
    qs.x(0)
    qs.h(2)
    
    
    initial_state = np.zeros(2**n)
    initial_state[0] = 1
    U = Operator(qs)

    G_wrapper = Graph_Wrapper(U,initial_state)
    graph_data = G_wrapper.data
    del graph_data["directed"]
    del graph_data["multigraph"]
    del graph_data["graph"]
    #print(graph_data)
    
    html1 = """<!DOCTYPE html>
            <html lang = "en">
            <head>
                <meta charset="utf-8">
                <title>Qflow - A Quantum Game</title>
                <style type="text/css">
                    canvas {
コード例 #22
0
 def test_ch_definition(self):  # TODO: expand this to all gates
     """Test ch gate matrix and definition."""
     circ = QuantumCircuit(2)
     circ.ch(0, 1)
     decomposed_circ = circ.decompose()
     self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
コード例 #23
0
ファイル: Tutorial.py プロジェクト: iCross989/qchack
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)

# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)

from qiskit.quantum_info import Operator

U = Operator(circ)

# Show the results
U.data

meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))

# The Qiskit circuit object supports composition.
# Here the meas has to be first and front=True (putting it before)
# as compose must put a smaller circuit into a larger one.
qc = meas.compose(circ, range(3), front=True)

#drawing the circuit
コード例 #24
0
ファイル: test_measures.py プロジェクト: Cryoris/qiskit-terra
 def test_nontp_process_fidelity(self):
     """Test process_fidelity for non-TP channel"""
     chan = 0.99 * Choi(Operator.from_label('X'))
     fid = process_fidelity(chan)
     self.assertLogs('qiskit.quantum_info.operators.measures', level='WARNING')
     self.assertAlmostEqual(fid, 0, places=15)
コード例 #25
0
    def test_parametric_template(self):
        """
        Check matching where template has parameters.
             ┌───────────┐                  ┌────────┐
        q_0: ┤ P(-1.0*β) ├──■────────────■──┤0       ├
             ├───────────┤┌─┴─┐┌──────┐┌─┴─┐│  CZ(β) │
        q_1: ┤ P(-1.0*β) ├┤ X ├┤ P(β) ├┤ X ├┤1       ├
             └───────────┘└───┘└──────┘└───┘└────────┘
        First test try match on
             ┌───────┐
        q_0: ┤ P(-2) ├──■────────────■─────────────────────────────
             ├───────┤┌─┴─┐┌──────┐┌─┴─┐┌───────┐
        q_1: ┤ P(-2) ├┤ X ├┤ P(2) ├┤ X ├┤ P(-3) ├──■────────────■──
             ├───────┤└───┘└──────┘└───┘└───────┘┌─┴─┐┌──────┐┌─┴─┐
        q_2: ┤ P(-3) ├───────────────────────────┤ X ├┤ P(3) ├┤ X ├
             └───────┘                           └───┘└──────┘└───┘
        Second test try match on
             ┌───────┐
        q_0: ┤ P(-2) ├──■────────────■────────────────────────────
             ├───────┤┌─┴─┐┌──────┐┌─┴─┐┌──────┐
        q_1: ┤ P(-2) ├┤ X ├┤ P(2) ├┤ X ├┤ P(3) ├──■────────────■──
             └┬──────┤└───┘└──────┘└───┘└──────┘┌─┴─┐┌──────┐┌─┴─┐
        q_2: ─┤ P(3) ├──────────────────────────┤ X ├┤ P(3) ├┤ X ├
              └──────┘                          └───┘└──────┘└───┘
        """
        class CZp(Gate):
            """CZ gates used for the test."""
            def __init__(self, num_qubits, params):
                super().__init__('cz', num_qubits, params)

            def inverse(self):
                inverse = UnitaryGate(
                    np.diag([1.0, 1.0, 1.0,
                             np.exp(-2.0j * self.params[0])]))
                inverse.name = 'icz'
                return inverse

        def template_czp2():
            beta = Parameter('β')
            qc = QuantumCircuit(2)
            qc.p(-beta, 0)
            qc.p(-beta, 1)
            qc.cx(0, 1)
            qc.p(beta, 1)
            qc.cx(0, 1)
            qc.append(CZp(2, [beta]), [0, 1])

            return qc

        def count_cx(qc):
            """Counts the number of CX gates for testing."""
            return qc.count_ops().get('cx', 0)

        circuit_in = QuantumCircuit(3)
        circuit_in.p(-2, 0)
        circuit_in.p(-2, 1)
        circuit_in.cx(0, 1)
        circuit_in.p(2, 1)
        circuit_in.cx(0, 1)
        circuit_in.p(-3, 1)
        circuit_in.p(-3, 2)
        circuit_in.cx(1, 2)
        circuit_in.p(3, 2)
        circuit_in.cx(1, 2)

        pass_ = TemplateOptimization(template_list=[template_czp2()])
        circuit_out = PassManager(pass_).run(circuit_in)

        np.testing.assert_almost_equal(
            Operator(circuit_out).data[3, 3], np.exp(-4.j))
        np.testing.assert_almost_equal(
            Operator(circuit_out).data[7, 7], np.exp(-10.j))
        self.assertEqual(count_cx(circuit_out),
                         0)  # Two matches => no CX gates.
        np.testing.assert_almost_equal(
            Operator(circuit_in).data,
            Operator(circuit_out).data)

        circuit_in = QuantumCircuit(3)
        circuit_in.p(-2, 0)
        circuit_in.p(-2, 1)
        circuit_in.cx(0, 1)
        circuit_in.p(2, 1)
        circuit_in.cx(0, 1)
        circuit_in.p(3, 1)
        circuit_in.p(3, 2)
        circuit_in.cx(1, 2)
        circuit_in.p(3, 2)
        circuit_in.cx(1, 2)

        pass_ = TemplateOptimization(template_list=[template_czp2()])
        circuit_out = PassManager(pass_).run(circuit_in)

        self.assertEqual(count_cx(circuit_out),
                         2)  # One match => two CX gates.
        np.testing.assert_almost_equal(
            Operator(circuit_in).data,
            Operator(circuit_out).data)
コード例 #26
0
 def test_ccx_definition(self):
     """Test ccx gate matrix and definition."""
     circ = QuantumCircuit(3)
     circ.ccx(0, 1, 2)
     decomposed_circ = circ.decompose()
     self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
コード例 #27
0
    def test_evals(self):
        """evals test"""
        # TODO: Think about eval names
        self.assertEqual(Z.eval("0").eval("0"), 1)
        self.assertEqual(Z.eval("1").eval("0"), 0)
        self.assertEqual(Z.eval("0").eval("1"), 0)
        self.assertEqual(Z.eval("1").eval("1"), -1)
        self.assertEqual(X.eval("0").eval("0"), 0)
        self.assertEqual(X.eval("1").eval("0"), 1)
        self.assertEqual(X.eval("0").eval("1"), 1)
        self.assertEqual(X.eval("1").eval("1"), 0)
        self.assertEqual(Y.eval("0").eval("0"), 0)
        self.assertEqual(Y.eval("1").eval("0"), -1j)
        self.assertEqual(Y.eval("0").eval("1"), 1j)
        self.assertEqual(Y.eval("1").eval("1"), 0)

        with self.assertRaises(ValueError):
            Y.eval("11")

        with self.assertRaises(ValueError):
            (X ^ Y).eval("1111")

        with self.assertRaises(ValueError):
            Y.eval((X ^ X).to_matrix_op())

        # Check that Pauli logic eval returns same as matrix logic
        self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("0").eval("0"), 1)
        self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("1").eval("0"), 0)
        self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("0").eval("1"), 0)
        self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("1").eval("1"), -1)
        self.assertEqual(PrimitiveOp(X.to_matrix()).eval("0").eval("0"), 0)
        self.assertEqual(PrimitiveOp(X.to_matrix()).eval("1").eval("0"), 1)
        self.assertEqual(PrimitiveOp(X.to_matrix()).eval("0").eval("1"), 1)
        self.assertEqual(PrimitiveOp(X.to_matrix()).eval("1").eval("1"), 0)
        self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("0").eval("0"), 0)
        self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("1").eval("0"), -1j)
        self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("0").eval("1"), 1j)
        self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("1").eval("1"), 0)

        pauli_op = Z ^ I ^ X ^ Y
        mat_op = PrimitiveOp(pauli_op.to_matrix())
        full_basis = list(
            map("".join, itertools.product("01", repeat=pauli_op.num_qubits)))
        for bstr1, bstr2 in itertools.product(full_basis, full_basis):
            # print('{} {} {} {}'.format(bstr1, bstr2, pauli_op.eval(bstr1, bstr2),
            # mat_op.eval(bstr1, bstr2)))
            np.testing.assert_array_almost_equal(
                pauli_op.eval(bstr1).eval(bstr2),
                mat_op.eval(bstr1).eval(bstr2))

        gnarly_op = SummedOp(
            [
                (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(Z),
                PrimitiveOp(Operator.from_label("+r0I")),
                3 * (X ^ CX ^ T),
            ],
            coeff=3 + 0.2j,
        )
        gnarly_mat_op = PrimitiveOp(gnarly_op.to_matrix())
        full_basis = list(
            map("".join, itertools.product("01", repeat=gnarly_op.num_qubits)))
        for bstr1, bstr2 in itertools.product(full_basis, full_basis):
            np.testing.assert_array_almost_equal(
                gnarly_op.eval(bstr1).eval(bstr2),
                gnarly_mat_op.eval(bstr1).eval(bstr2))
コード例 #28
0
 def test_adjoint(self):
     """ adjoint test """
     gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + \
         PrimitiveOp(Operator.from_label('+r0IX').data)
     np.testing.assert_array_almost_equal(np.conj(np.transpose(gnarly_op.to_matrix())),
                                          gnarly_op.adjoint().to_matrix())
コード例 #29
0
def get_fidelity_with_qiskit(dag_cir, noisy_position):
    cir = dag_2_circuit(dag_cir)
    U = Operator(cir)
    channel = get_error_channel(dag_cir, noisy_position, 0.001)
    fide = process_fidelity(channel, U)
    return fide
コード例 #30
0
    def test_unroll_all_instructions(self):
        """Test unrolling a circuit containing all standard instructions.
        """

        qr = QuantumRegister(3, 'qr')
        cr = ClassicalRegister(3, 'cr')
        circuit = QuantumCircuit(qr, cr)
        circuit.crx(0.5, qr[1], qr[2])
        circuit.cry(0.5, qr[1], qr[2])
        circuit.ccx(qr[0], qr[1], qr[2])
        circuit.ch(qr[0], qr[2])
        circuit.crz(0.5, qr[1], qr[2])
        circuit.cswap(qr[1], qr[0], qr[2])
        circuit.append(CU1Gate(0.1), [qr[0], qr[2]])
        circuit.append(CU3Gate(0.2, 0.1, 0.0), [qr[1], qr[2]])
        circuit.cx(qr[1], qr[0])
        circuit.cy(qr[1], qr[2])
        circuit.cz(qr[2], qr[0])
        circuit.h(qr[1])
        circuit.i(qr[0])
        circuit.rx(0.1, qr[0])
        circuit.ry(0.2, qr[1])
        circuit.rz(0.3, qr[2])
        circuit.rzz(0.6, qr[1], qr[0])
        circuit.s(qr[0])
        circuit.sdg(qr[1])
        circuit.swap(qr[1], qr[2])
        circuit.t(qr[2])
        circuit.tdg(qr[0])
        circuit.append(U1Gate(0.1), [qr[1]])
        circuit.append(U2Gate(0.2, -0.1), [qr[0]])
        circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]])
        circuit.x(qr[2])
        circuit.y(qr[1])
        circuit.z(qr[0])
        # circuit.snapshot('0')
        # circuit.measure(qr, cr)
        dag = circuit_to_dag(circuit)
        pass_ = UnrollCustomDefinitions(std_eqlib, ['u3', 'cx', 'id'])
        dag = pass_.run(dag)

        pass_ = BasisTranslator(std_eqlib, ['u3', 'cx', 'id'])
        unrolled_dag = pass_.run(dag)

        ref_circuit = QuantumCircuit(qr, cr)
        ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(0.25, -pi / 2, 0), [qr[2]])
        ref_circuit.append(U3Gate(0.25, 0, 0), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
        ref_circuit.cx(qr[0], qr[2])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]])
        ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
        ref_circuit.cx(qr[0], qr[2])
        ref_circuit.cx(qr[0], qr[1])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]])
        ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[1]])
        ref_circuit.cx(qr[0], qr[1])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
        ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
        ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
        ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
        ref_circuit.cx(qr[0], qr[2])
        ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
        ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
        ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]])
        ref_circuit.append(U3Gate(0, 0, 0.25), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(0, 0, -0.25), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.cx(qr[2], qr[0])
        ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
        ref_circuit.cx(qr[0], qr[2])
        ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
        ref_circuit.cx(qr[0], qr[2])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]])
        ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.cx(qr[1], qr[0])
        ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]])
        ref_circuit.cx(qr[1], qr[0])
        ref_circuit.append(U3Gate(0, 0, 0.05), [qr[1]])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
        ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
        ref_circuit.cx(qr[2], qr[0])
        ref_circuit.append(U3Gate(0, 0, 0.05), [qr[0]])
        ref_circuit.cx(qr[0], qr[2])
        ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]])
        ref_circuit.cx(qr[0], qr[2])
        ref_circuit.append(U3Gate(0, 0, 0.05), [qr[2]])
        ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(-0.1, 0, -0.05), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.cx(qr[1], qr[0])
        ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]])
        ref_circuit.append(U3Gate(0.1, 0.1, 0), [qr[2]])
        ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[1]])
        ref_circuit.append(U3Gate(0.2, 0, 0), [qr[1]])
        ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
        ref_circuit.cx(qr[2], qr[0])
        ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]])
        ref_circuit.i(qr[0])
        ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]])
        ref_circuit.cx(qr[1], qr[0])
        ref_circuit.append(U3Gate(0, 0, 0.6), [qr[0]])
        ref_circuit.cx(qr[1], qr[0])
        ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[0]])
        ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]])
        ref_circuit.append(U3Gate(pi / 2, 0.2, -0.1), [qr[0]])
        ref_circuit.append(U3Gate(0, 0, pi), [qr[0]])
        ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[1]])
        ref_circuit.append(U3Gate(0, 0, 0.3), [qr[2]])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.cx(qr[2], qr[1])
        ref_circuit.cx(qr[1], qr[2])
        ref_circuit.append(U3Gate(0, 0, 0.1), [qr[1]])
        ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[1]])
        ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
        ref_circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]])
        ref_circuit.append(U3Gate(pi, 0, pi), [qr[2]])
        # ref_circuit.snapshot('0')
        # ref_circuit.measure(qr, cr)
        # ref_dag = circuit_to_dag(ref_circuit)

        self.assertTrue(
            Operator(dag_to_circuit(unrolled_dag)).equiv(ref_circuit))