예제 #1
0
 def test_open_control_composite_unrolling(self):
     """test unrolling of open control gates when gate is in basis"""
     # create composite gate
     qreg = QuantumRegister(2)
     qcomp = QuantumCircuit(qreg, name='bell')
     qcomp.h(qreg[0])
     qcomp.cx(qreg[0], qreg[1])
     bell = qcomp.to_gate()
     # create controlled composite gate
     cqreg = QuantumRegister(3)
     qc = QuantumCircuit(cqreg)
     qc.append(bell.control(ctrl_state=0), qc.qregs[0][:])
     dag = circuit_to_dag(qc)
     unroller = Unroller(['x', 'u1', 'cbell'])
     unrolled_dag = unroller.run(dag)
     # create reference circuit
     ref_circuit = QuantumCircuit(cqreg)
     ref_circuit.x(cqreg[0])
     ref_circuit.append(bell.control(), [cqreg[0], cqreg[1], cqreg[2]])
     ref_circuit.x(cqreg[0])
     ref_dag = circuit_to_dag(ref_circuit)
     self.assertEqual(unrolled_dag, ref_dag)
예제 #2
0
    def test_unroller_one(self):
        """Test unrolling gate.repeat(1).
        """
        qr = QuantumRegister(1, 'qr')

        circuit = QuantumCircuit(qr)
        circuit.append(SGate().repeat(1), [qr[0]])
        result = PassManager(Unroller('u3')).run(circuit)

        expected = QuantumCircuit(qr)
        expected.append(U3Gate(0, 0, pi / 2), [qr[0]])

        self.assertEqual(result, expected)
예제 #3
0
    def test_definition_unroll_parameterized(self):
        """Verify that unrolling complex gates with parameters raises."""
        qr = QuantumRegister(2)
        qc = QuantumCircuit(qr)

        theta = Parameter('theta')

        qc.cu1(theta, qr[0], qr[1])
        dag = circuit_to_dag(qc)

        with self.assertRaisesRegex(QiskitError, 'unsupported'):
            Unroller(['u1', 'cx']).run(dag)
            raise QiskitError('unsupported')
예제 #4
0
 def test_error_unknown_defn_unroller_pass(self):
     """Check for proper error message when unroller cannot find the definition
     of a gate."""
     circuit = ZGate().control(2).definition
     basis = ["u1", "u2", "u3", "cx"]
     unroller = Unroller(basis)
     with self.assertRaises(QiskitError) as cm:
         unroller(circuit)
     exp_msg = (
         "Error decomposing node of instruction 'p': 'NoneType' object has no"
         " attribute 'global_phase'. Unable to define instruction 'u' in the basis."
     )
     self.assertEqual(exp_msg, cm.exception.message)
예제 #5
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)

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

        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'])

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

        simulator = BasicAer.get_backend('unitary_simulator')
        for gate, cgate in zip([gu1, grx, gry, grz], [cgu1, cgrx, cgry, cgrz]):
            with self.subTest(i=gate.name):
                qc = QuantumCircuit(num_target)
                qc.append(gate, qc.qregs[0])
                op_mat = execute(qc, simulator).result().get_unitary(0)
                cqc = QuantumCircuit(num_ctrl + num_target)
                cqc.append(cgate, cqc.qregs[0])
                ref_mat = execute(cqc, simulator).result().get_unitary(0)
                cop_mat = _compute_control_matrix(op_mat, num_ctrl)
                self.assertTrue(
                    matrix_equal(cop_mat, ref_mat, ignore_phase=True))
                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)
                else:
                    self.assertTrue(uqc.size() <= 20)
        qc = QuantumCircuit(qreg, name='composite')
        qc.append(grx.q_if(num_ctrl), qreg)
        qc.append(gry.q_if(num_ctrl), qreg)
        qc.append(gry, qreg[0:gry.num_qubits])
        qc.append(grz.q_if(num_ctrl), qreg)

        dag = circuit_to_dag(qc)
        unroller = Unroller(['u3', 'cx'])
        uqc = dag_to_circuit(unroller.run(dag))
        self.log.info('%s gate count: %d', uqc.name, uqc.size())
        self.assertTrue(uqc.size() <= 73)  # this limit could be changed
예제 #6
0
    def __init__(self, basis_gates):
        """MSBasisDecomposer initializer.

        Args:
            basis_gates (list[str]): Target basis names, e.g. `['rx', 'ry', 'rxx', 'ms']` .
        """
        super().__init__()

        self.basis_gates = basis_gates

        # Require all gates be unrolled to either a basis gate or U3,CX before
        # running the decomposer.
        input_basis = set(basis_gates).union(['u3', 'cx'])
        self.requires = [Unroller(list(input_basis))]
예제 #7
0
    def test_parameterized_angle(self):
        """Test unrolling with parameterized angle"""
        qc = QuantumCircuit(1)
        index = Parameter("index")
        with qc.for_loop((0, 0.5 * pi), index) as param:
            qc.rx(param, 0)
        dag = circuit_to_dag(qc)
        unrolled_dag = Unroller(["u", "cx"]).run(dag)

        expected = QuantumCircuit(1)
        with expected.for_loop((0, 0.5 * pi), index) as param:
            expected.u(param, -pi / 2, pi / 2, 0)
        expected_dag = circuit_to_dag(expected)
        self.assertEqual(unrolled_dag, expected_dag)
예제 #8
0
파일: ruleset.py 프로젝트: imbi7py/qwopt
    def _rule0(self, dag):
        '''
        optimization about ancillary qubits
        In this optimization, once map the control operations to ancillae
        qubits, and then, reduce the number of operations.

        Input:
            dag: DAG
        Output:
            dag: DAG, success(bool)
        '''
        # FIXME if the position of partition is symmetry,
        # we can't apply this optimization because it's redundunt

        # procedure 1, add ancilal or find ancilla
        # FIXME

        p_rule0 = self.toml['rule0']
        n_ancilla = p_rule0['n_ancilla']

        # unrolling dag to basis compornents
        ndag = Unroller(['ccx', 'cx', 'x', 'h', 'u3']).run(dag)

        ndag_nodes = [i for i in ndag.nodes()]
        ndag_names = [i.name for i in ndag_nodes]

        # FIXME taking parameters dynamically
        dag_nodes = [i for i in dag.nodes()]

        if n_ancilla < 0:
            raise ValueError('The number of ancillary qubits \
                             must be 0 or over 0')
        # adding ancilla qubit
        q = QuantumRegister(n_ancilla, name='opt ancilla')
        dag.add_qreg(q)
        ndag.draw()
        return dag, False
    def test_unroll_1q_chain_conditional(self):
        """Test unroll chain of 1-qubit gates interrupted by conditional.
        """
        qr = QuantumRegister(1, 'qr')
        cr = ClassicalRegister(1, 'cr')
        circuit = QuantumCircuit(qr, cr)
        circuit.h(qr)
        circuit.tdg(qr)
        circuit.z(qr)
        circuit.t(qr)
        circuit.ry(0.5, qr)
        circuit.rz(0.3, qr)
        circuit.rx(0.1, qr)
        circuit.measure(qr, cr)
        circuit.x(qr).c_if(cr, 1)
        circuit.y(qr).c_if(cr, 1)
        circuit.z(qr).c_if(cr, 1)
        dag = circuit_to_dag(circuit)
        pass_ = Unroller(['u1', 'u2', 'u3'])
        unrolled_dag = pass_.run(dag)

        # Pick up -1 * 0.3 / 2 global phase for one RZ -> U1.
        ref_circuit = QuantumCircuit(qr, cr, global_phase=-0.3 / 2)
        ref_circuit.append(U2Gate(0, pi), [qr[0]])
        ref_circuit.append(U1Gate(-pi/4), [qr[0]])
        ref_circuit.append(U1Gate(pi), [qr[0]])
        ref_circuit.append(U1Gate(pi/4), [qr[0]])
        ref_circuit.append(U3Gate(0.5, 0, 0), [qr[0]])
        ref_circuit.append(U1Gate(0.3), [qr[0]])
        ref_circuit.append(U3Gate(0.1, -pi/2, pi/2), [qr[0]])
        ref_circuit.measure(qr[0], cr[0])
        ref_circuit.append(U3Gate(pi, 0, pi), [qr[0]]).c_if(cr, 1)
        ref_circuit.append(U3Gate(pi, pi/2, pi/2), [qr[0]]).c_if(cr, 1)
        ref_circuit.append(U1Gate(pi), [qr[0]]).c_if(cr, 1)
        ref_dag = circuit_to_dag(ref_circuit)

        self.assertEqual(unrolled_dag, ref_dag)
예제 #10
0
def create_direction_only_pass_manager(device):
    # type: (BaseBackend) -> PassManager

    LOG.info("Creating direction-only PassManager for {}".format(device))

    cp = CouplingMap(couplinglist=device.configuration().coupling_map)
    basis = device.configuration().basis_gates

    pm = PassManager()
    pm.append(Unroller(basis=basis))
    # noinspection PyTypeChecker
    if cp.size() > 0:
        pm.append(CXDirection(coupling_map=cp))
    pm.append(Optimize1qGates())
    return pm
 def __init__(self):
     """TransformCxCascade initializer.
     Raises:
         TranspilerError: if run after the layout has been set.
     """
     super().__init__()
     if self.property_set['layout']:
         raise TranspilerError('TransformCxCascade pass must be run before any layout has been set.')
     self.requires.append(Unroller(['u1', 'u2', 'u3', 'cx', 'id']))
     self._num_qubits = None
     self._wires_to_id = {}
     self._id_to_wires = {}
     self._layers = None
     self._extra_layers = None
     self._skip = []
    def test_unrolling_global_phase_1q(self):
        """Test unrolling a circuit with global phase in a composite gate."""
        circ = QuantumCircuit(1, global_phase=pi / 2)
        circ.x(0)
        circ.h(0)
        v = circ.to_gate()

        qc = QuantumCircuit(1)
        qc.append(v, [0])

        dag = circuit_to_dag(qc)
        out_dag = Unroller(["cx", "x", "h"]).run(dag)
        qcd = dag_to_circuit(out_dag)

        self.assertEqual(Operator(qc), Operator(qcd))
예제 #13
0
    def test_unroll_1q_chain_conditional(self):
        """Test unroll chain of 1-qubit gates interrupted by conditional.
        """
        qr = QuantumRegister(1, 'qr')
        cr = ClassicalRegister(1, 'cr')
        circuit = QuantumCircuit(qr, cr)
        circuit.h(qr)
        circuit.tdg(qr)
        circuit.z(qr)
        circuit.t(qr)
        circuit.ry(0.5, qr)
        circuit.rz(0.3, qr)
        circuit.rx(0.1, qr)
        circuit.measure(qr, cr)
        circuit.x(qr).c_if(cr, 1)
        circuit.y(qr).c_if(cr, 1)
        circuit.z(qr).c_if(cr, 1)
        dag = circuit_to_dag(circuit)
        pass_ = Unroller(['u1', 'u2', 'u3'])
        unrolled_dag = pass_.run(dag)

        ref_circuit = QuantumCircuit(qr, cr)
        ref_circuit.u2(0, pi, qr[0])
        ref_circuit.u1(-pi/4, qr[0])
        ref_circuit.u1(pi, qr[0])
        ref_circuit.u1(pi/4, qr[0])
        ref_circuit.u3(0.5, 0, 0, qr[0])
        ref_circuit.u1(0.3, qr[0])
        ref_circuit.u3(0.1, -pi/2, pi/2, qr[0])
        ref_circuit.measure(qr[0], cr[0])
        ref_circuit.u3(pi, 0, pi, qr[0]).c_if(cr, 1)
        ref_circuit.u3(pi, pi/2, pi/2, qr[0]).c_if(cr, 1)
        ref_circuit.u1(pi, qr[0]).c_if(cr, 1)
        ref_dag = circuit_to_dag(ref_circuit)

        self.assertEqual(unrolled_dag, ref_dag)
    def test_simple_unroll_parameterized_without_expressions(self):
        """Verify unrolling parameterized gates without expressions."""
        qr = QuantumRegister(1)
        qc = QuantumCircuit(qr)

        theta = Parameter("theta")

        qc.rz(theta, qr[0])
        dag = circuit_to_dag(qc)

        unrolled_dag = Unroller(["u1", "u3", "cx"]).run(dag)

        expected = QuantumCircuit(qr, global_phase=-theta / 2)
        expected.append(U1Gate(theta), [qr[0]])

        self.assertEqual(circuit_to_dag(expected), unrolled_dag)
예제 #15
0
    def test_simple_unroll_parameterized_without_expressions(self):
        """Verify unrolling parameterized gates without expressions."""
        qr = QuantumRegister(1)
        qc = QuantumCircuit(qr)

        theta = Parameter('theta')

        qc.rz(theta, qr[0])
        dag = circuit_to_dag(qc)

        unrolled_dag = Unroller(['u1', 'cx']).run(dag)

        expected = QuantumCircuit(qr)
        expected.u1(theta, qr[0])

        self.assertEqual(circuit_to_dag(expected), unrolled_dag)
예제 #16
0
def circuit_from_qasm(qasm):
    """Creates a QCircuit from a QASM circuit, uses Qiskit transpiler
    to unroll the QASM circuit into basic U gates.

    Args:
        qasm (str): a QASM circuit

    Returns:
        QCircuit: the QCircuit equivalent of the provided QASM circuit
    """

    pm = PassManager()
    pm.append(Unroller(['u3', 'cx']))
    qasm = transpile(QuantumCircuit.from_qasm_str(qasm), pass_manager=pm).qasm()
    q_circuit = QCircuit()
    lines = list(qasm.split(';\n'))
    for line in lines:
        if line.startswith('qreg'):
            q_circuit.add_q_register(line.split(' ')[-1].split('[')[0], int(line.split('[')[1][:-1]))
        elif line.startswith('creg'):
            q_circuit.add_c_register(line.split(' ')[-1].split('[')[0], int(line.split('[')[1][:-1]))
        else:
            if line.startswith('u3'):
                q_reg = _q_reg_1q_qasm_gate(line)
                q_arg = (q_circuit.q_regs[q_reg[0]][0], q_reg[1])
                params = _qasm_gate_params(line)
                # print(line)
                if params[0] == pi.evalf(5)/2 and params[1] == 0 and params[2] == pi.evalf(5):
                    # print('H')
                    q_circuit.h(q_arg)
                else:
                    q_circuit.dummy_gate(name='u3', q_args=[q_arg], params=params)
            elif line.startswith('cx'):
                q_regs = _q_regs_2q_qasm_gate(line)
                q_circuit.cx((q_circuit.q_regs[q_regs[0][0]][0], q_regs[0][1]),
                             (q_circuit.q_regs[q_regs[1][0]][0], q_regs[1][1]))
            elif line.startswith('measure'):
                q_reg = line.split(' ')[1]
                c_reg = line.split(' ')[3]
                q_circuit.measure((q_circuit.q_regs[q_reg.split('[')[0]][0], int(q_reg.split('[')[-1][:-1])),
                                  (q_circuit.c_regs[c_reg.split('[')[0]][0], int(c_reg.split('[')[-1][:-1])))
            elif line.startswith('barrier'):
                q_args = list()
                for q_arg in line.split(' ')[-1].split(','):
                    q_args.append((q_circuit.q_regs[q_arg.split('[')[0]][0], int(q_arg.split('[')[-1][:-1])))
                q_circuit.barrier(*q_args)
    return q_circuit
예제 #17
0
    def test_callback(self):
        """Test the callback parameter."""
        qr = QuantumRegister(1, 'qr')
        circuit = QuantumCircuit(qr, name='MyCircuit')
        circuit.h(qr[0])
        circuit.h(qr[0])
        circuit.h(qr[0])
        expected_start = QuantumCircuit(qr)
        expected_start.u2(0, np.pi, qr[0])
        expected_start.u2(0, np.pi, qr[0])
        expected_start.u2(0, np.pi, qr[0])
        expected_start_dag = circuit_to_dag(expected_start)

        expected_end = QuantumCircuit(qr)
        expected_end.u2(0, np.pi, qr[0])
        expected_end_dag = circuit_to_dag(expected_end)

        calls = []

        def callback(**kwargs):
            out_dict = kwargs
            out_dict['dag'] = copy.deepcopy(kwargs['dag'])
            calls.append(out_dict)

        passmanager = PassManager()
        passmanager.append(Unroller(['u2']))
        passmanager.append(Optimize1qGates())
        transpile(circuit,
                  FakeRueschlikon(),
                  pass_manager=passmanager,
                  callback=callback)
        self.assertEqual(len(calls), 2)
        self.assertEqual(len(calls[0]), 5)
        self.assertEqual(calls[0]['count'], 0)
        self.assertEqual(calls[0]['pass_'].name(), 'Unroller')
        self.assertEqual(expected_start_dag, calls[0]['dag'])
        self.assertIsInstance(calls[0]['time'], float)
        self.assertEqual(calls[0]['property_set'], PropertySet())
        self.assertEqual('MyCircuit', calls[0]['dag'].name)
        self.assertEqual(len(calls[1]), 5)
        self.assertEqual(calls[1]['count'], 1)
        self.assertEqual(calls[1]['pass_'].name(), 'Optimize1qGates')
        self.assertEqual(expected_end_dag, calls[1]['dag'])
        self.assertIsInstance(calls[0]['time'], float)
        self.assertEqual(calls[0]['property_set'], PropertySet())
        self.assertEqual('MyCircuit', calls[1]['dag'].name)
예제 #18
0
 def test_default_stages(self):
     spm = StagedPassManager()
     self.assertEqual(spm.stages,
                      ("init", "layout", "routing", "translation",
                       "optimization", "scheduling"))
     spm = StagedPassManager(
         init=PassManager([Optimize1qGates()]),
         routing=PassManager([Unroller(["u", "cx"])]),
         scheduling=PassManager([Depth()]),
     )
     self.assertEqual(
         [
             x.__class__.__name__ for passes in spm.passes()
             for x in passes["passes"]
         ],
         ["Optimize1qGates", "Unroller", "Depth"],
     )
예제 #19
0
    def test_optimize_h_gates_pass_manager(self):
        """Transpile: qr:--[H]-[H]-[H]-- == qr:--[u2]-- """
        qr = QuantumRegister(1, 'qr')
        circuit = QuantumCircuit(qr)
        circuit.h(qr[0])
        circuit.h(qr[0])
        circuit.h(qr[0])

        expected = QuantumCircuit(qr)
        expected.u2(0, np.pi, qr[0])

        passmanager = PassManager()
        passmanager.append(Unroller(['u2']))
        passmanager.append(Optimize1qGates())
        result = passmanager.run(circuit)

        self.assertEqual(expected, result)
    def test_unrolling_global_phase_nested_gates(self):
        """Test unrolling a nested gate preseveres global phase."""
        qc = QuantumCircuit(1, global_phase=pi)
        qc.x(0)
        gate = qc.to_gate()

        qc = QuantumCircuit(1)
        qc.append(gate, [0])
        gate = qc.to_gate()

        qc = QuantumCircuit(1)
        qc.append(gate, [0])
        dag = circuit_to_dag(qc)
        out_dag = Unroller(["x", "u"]).run(dag)
        qcd = dag_to_circuit(out_dag)

        self.assertEqual(Operator(qc), Operator(qcd))
예제 #21
0
def max_cut_v3_challange():
    prepare()
    circ.barrier()

    for i in range(2):
        # Oracle part
        cutter_edge_checker(q[0], q[1], q[4])
        cutter_edge_checker(q[0], q[2], q[5])
        cutter_edge_checker(q[0], q[3], q[6])
        count_cuts()
        oracle()
        circ.barrier()

        clean_helper_registers()
        circ.barrier()

        amplitude_amplification()
        circ.barrier()

    circ.measure(q[0:4], c[0:4])

    res = run()

    print("max_cut")
    print(circ.draw(output='text', line_length=200))
    print(res.get_counts())
    # print("We have found the answear: '0001': high, '1110': high,")

    # Decompose the circuit by using the Unroller
    from qiskit.transpiler import PassManager
    from qiskit.transpiler.passes import Unroller
    pass_ = Unroller(['u3', 'cx'])
    pm = PassManager(pass_)
    new_circuit = pm.run(circ)
    # new_circuit.draw(output='mpl')

    #show elementary gate counts
    new_circuit.count_ops()
    # create output text file with the gate counts
    import json
    dct = new_circuit.count_ops()
    with open('wk3_output-last-run.txt', 'w') as f:
        f.write(json.dumps(dct))
    print('0001 %s', res.get_counts()['0001'])
    print('1110 %s', res.get_counts()['1110'])
예제 #22
0
    def setUp(self):
        coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
        coupling_map = CouplingMap(couplinglist=coupling)
        basis_gates = ['u1', 'u3', 'u2', 'cx']
        qr = QuantumRegister(7, 'q')
        layout = Layout({qr[i]: i for i in range(coupling_map.size())})

        # Create a pass manager with a variety of passes and flow control structures
        self.pass_manager = PassManager()
        self.pass_manager.append(SetLayout(layout))
        self.pass_manager.append(TrivialLayout(coupling_map), condition=lambda x: True)
        self.pass_manager.append(FullAncillaAllocation(coupling_map))
        self.pass_manager.append(EnlargeWithAncilla())
        self.pass_manager.append(Unroller(basis_gates))
        self.pass_manager.append(CheckMap(coupling_map))
        self.pass_manager.append(BarrierBeforeFinalMeasurements(), do_while=lambda x: False)
        self.pass_manager.append(CXDirection(coupling_map))
        self.pass_manager.append(RemoveResetInZeroState())
    def test_unrolling_preserves_qregs_order(self):
        """Test unrolling a gate preseveres it's definition registers order"""
        qr = QuantumRegister(2, "qr1")
        qc = QuantumCircuit(qr)
        qc.cx(1, 0)
        gate = qc.to_gate()

        qr2 = QuantumRegister(2, "qr2")
        qc2 = QuantumCircuit(qr2)
        qc2.append(gate, qr2)

        dag = circuit_to_dag(qc2)
        out_dag = Unroller(["cx"]).run(dag)

        expected = QuantumCircuit(qr2)
        expected.cx(1, 0)

        self.assertEqual(circuit_to_dag(expected), out_dag)
    def test_simple_unroll_parameterized_with_expressions(self):
        """Verify unrolling parameterized gates with expressions."""
        qr = QuantumRegister(1)
        qc = QuantumCircuit(qr)

        theta = Parameter('theta')
        phi = Parameter('phi')
        sum_ = theta + phi

        qc.rz(sum_, qr[0])
        dag = circuit_to_dag(qc)

        unrolled_dag = Unroller(['u1', 'u3', 'cx']).run(dag)

        expected = QuantumCircuit(qr, global_phase=-sum_ / 2)
        expected.append(U1Gate(sum_), [qr[0]])

        self.assertEqual(circuit_to_dag(expected), unrolled_dag)
예제 #25
0
 def test_inplace_edit(self):
     spm = StagedPassManager(stages=["single_stage"])
     spm.single_stage = PassManager([Optimize1qGates(), Depth()])
     self.assertEqual(
         [
             x.__class__.__name__ for passes in spm.passes()
             for x in passes["passes"]
         ],
         ["Optimize1qGates", "Depth"],
     )
     spm.single_stage.append(Unroller(["u"]))
     spm.single_stage.append(Depth())
     self.assertEqual(
         [
             x.__class__.__name__ for passes in spm.passes()
             for x in passes["passes"]
         ],
         ["Optimize1qGates", "Depth", "Unroller", "Depth"],
     )
예제 #26
0
    def run(self, dag):

        #Unroll input gates to the gates supported by VOQC and check if gates are supported in VOQC
        try:
            after_dag = (BasisTranslator(eq_lib, self.voqc_gates)).run(dag)
        except TranspilerError as e:
            #From qiskit repository to get gates in basis
            source_basis = {(node.op.name, node.op.num_qubits)
                            for node in dag.op_nodes()}

            for x in source_basis:
                if (x[0] in self.voqc_gates) == False:
                    raise InvalidVOQCGate(str(x[0]))

        #Remove rz(0) gates to pass to VOQC
        circ = dag_to_circuit(after_dag)

        i = 0
        while i < len(circ.data):
            if (circ.data[i][0]).name == "rz":
                if (circ.data[i][0].params)[0] == 0:
                    circ.data.pop(i)
                else:
                    i += 1
            else:
                i += 1

        #Write qasm file to pass to get_gate_list
        circ.qasm(formatted=False, filename="temp.qasm")

        #Apply and get optimized SQIR
        qasm_str = self.function_call("temp.qasm")
        after_circ = QuantumCircuit.from_qasm_str(qasm_str)

        #Unroll rzq definitions to rz
        pm = PassManager()
        pm.append(Unroller(['x', 'h', 'cx', 'rz', 'tdg', 'sdg', 's', 't',
                            'z']))
        after_circ = pm.run(after_circ)

        to_dag = circuit_to_dag(after_circ)
        os.remove("temp.qasm")
        return to_dag
예제 #27
0
파일: default.py 프로젝트: danmills0/qiskit
def default_pass_manager_simulator(transpile_config):
    """
    The default pass manager without a coupling map.

    Args:
        transpile_config (TranspileConfig)

    Returns:
        PassManager: A passmanager that just unrolls, without any optimization.
    """
    basis_gates = transpile_config.basis_gates

    pass_manager = PassManager()
    pass_manager.append(Unroller(basis_gates))
    pass_manager.append(
        [RemoveResetInZeroState(),
         Depth(), FixedPoint('depth')],
        do_while=lambda property_set: not property_set['depth_fixed_point'])

    return pass_manager
예제 #28
0
def fiim_generate_circs_helper(circuit,
                               n,
                               basis_gates=['u1', 'u2', 'u3', 'cx']):
    unroller = Unroller(basis=basis_gates)
    p_m = PassManager(passes=[unroller])
    transpile_result = compiler.transpile(circuit,
                                          basis_gates=basis_gates,
                                          optimization_level=1)
    ops = transpile_result.data

    qc = QuantumCircuit()
    qregs = transpile_result.qregs
    qubits = []
    for qreg in qregs:
        if not qc.has_register(qreg):
            qc.add_register(qreg)
        qubits.extend(qreg)
    cregs = circuit.cregs
    clbits = []
    for creg in cregs:
        if not qc.has_register(creg):
            qc.add_register(creg)
        clbits.extend(creg)
    for op in ops:
        if op[0].name == 'cx':
            apply_extra_cnots(qc, *op[1], n)
        elif op[0].name == 'u1':
            apply_u1(qc, *op[0].params, op[1][0])
        # elif op[0].name == 'h':
        #    apply_h(qc, *op[0].params, op[1][0])
        elif op[0].name == 'u2':
            apply_u2(qc, *op[0].params, op[1][0])
        elif op[0].name == 'u3':
            apply_u3(qc, *op[0].params, op[1][0])
        elif op[0].name == 'barrier':
            qc.barrier()
        elif op[0].name == 'measure':
            qc.measure(op[1][0], op[2][0])
        else:
            print('ERROR:', op[0].name)
    return qc
예제 #29
0
    def test_optimize_u3_with_parameters(self):
        """Test correct behavior for u3 gates."""
        phi = Parameter("φ")
        alpha = Parameter("α")
        qr = QuantumRegister(1, "qr")

        qc = QuantumCircuit(qr)
        qc.ry(2 * phi, qr[0])
        qc.ry(alpha, qr[0])
        qc.ry(0.1, qr[0])
        qc.ry(0.2, qr[0])

        passmanager = PassManager([Unroller(["u3"]), Optimize1qGates()])
        result = passmanager.run(qc)

        expected = QuantumCircuit(qr)
        expected.append(U3Gate(2 * phi, 0, 0), [qr[0]])
        expected.append(U3Gate(alpha, 0, 0), [qr[0]])
        expected.append(U3Gate(0.3, 0, 0), [qr[0]])

        self.assertEqual(expected, result)
예제 #30
0
 def test_repeated_stages(self):
     stages = ["alpha", "omega", "alpha"]
     pre_alpha = PassManager(Unroller(["u", "cx"]))
     alpha = PassManager(Depth())
     post_alpha = PassManager(BasicSwap([[0, 1], [1, 2]]))
     omega = PassManager(Optimize1qGates())
     spm = StagedPassManager(stages,
                             pre_alpha=pre_alpha,
                             alpha=alpha,
                             post_alpha=post_alpha,
                             omega=omega)
     passes = [
         *pre_alpha.passes(),
         *alpha.passes(),
         *post_alpha.passes(),
         *omega.passes(),
         *pre_alpha.passes(),
         *alpha.passes(),
         *post_alpha.passes(),
     ]
     self.assertEqual(spm.passes(), passes)