Ejemplo n.º 1
0
    def setUp(self):
        self.dag = DAGCircuit()
        qreg = QuantumRegister(3, 'qr')
        creg = ClassicalRegister(2, 'cr')
        self.dag.add_qreg(qreg)
        self.dag.add_creg(creg)

        self.qubit0 = qreg[0]
        self.qubit1 = qreg[1]
        self.qubit2 = qreg[2]
        self.clbit0 = creg[0]
        self.clbit1 = creg[1]
        self.condition = (creg, 3)

        self.dag.apply_operation_back(HGate(self.qubit0))
        self.dag.apply_operation_back(CnotGate(self.qubit0, self.qubit1))
        self.dag.apply_operation_back(XGate(self.qubit1))
Ejemplo n.º 2
0
    def test_default_shots_greater_than_max_shots(self):
        """Test assembling with default shots greater than max shots"""
        qr = QuantumRegister(2, name='q')
        qc = ClassicalRegister(2, name='c')
        circ = QuantumCircuit(qr, qc, name='circ')
        circ.h(qr[0])
        circ.cx(qr[0], qr[1])
        circ.measure(qr, qc)
        backend = FakeYorktown()
        backend._configuration.max_shots = 5

        qobj = assemble(circ, backend)

        validate_qobj_against_schema(qobj)

        self.assertIsInstance(qobj, QasmQobj)
        self.assertEqual(qobj.config.shots, 5)
Ejemplo n.º 3
0
 def test_dag_depth2(self):
     """Test barrier increases DAG depth
     """
     q = QuantumRegister(5, 'q')
     c = ClassicalRegister(1, 'c')
     qc = QuantumCircuit(q, c)
     qc.h(q[0])
     qc.cx(q[0], q[4])
     qc.x(q[2])
     qc.x(q[2])
     qc.x(q[2])
     qc.x(q[4])
     qc.cx(q[4], q[1])
     qc.barrier(q)
     qc.measure(q[1], c[0])
     dag = circuit_to_dag(qc)
     self.assertEqual(dag.depth(), 6)
Ejemplo n.º 4
0
    def test_assemble_single_circuit(self):
        """Test assembling a single circuit.
        """
        qr = QuantumRegister(2, name='q')
        cr = ClassicalRegister(2, name='c')
        circ = QuantumCircuit(qr, cr, name='circ')
        circ.h(qr[0])
        circ.cx(qr[0], qr[1])
        circ.measure(qr, cr)

        run_config = RunConfig(shots=2000, memory=True)
        qobj = assemble_circuits(circ, run_config=run_config)
        self.assertIsInstance(qobj, QasmQobj)
        self.assertEqual(qobj.config.shots, 2000)
        self.assertEqual(qobj.config.memory, True)
        self.assertEqual(len(qobj.experiments), 1)
        self.assertEqual(qobj.experiments[0].instructions[1].name, 'cx')
    def setUp(self):
        """Initial test setup."""
        super().setUp()
        qr = QuantumRegister(2)
        cr = ClassicalRegister(2)
        self.qc1 = QuantumCircuit(qr, cr, name='qc1')
        self.qc2 = QuantumCircuit(qr, cr, name='qc2')
        self.qc1.h(qr)
        self.qc2.h(qr[0])
        self.qc2.cx(qr[0], qr[1])
        self.qc1.measure(qr[0], cr[0])
        self.qc1.measure(qr[1], cr[1])
        self.qc2.measure(qr[0], cr[0])
        self.qc2.measure(qr[1], cr[1])
        self.seed = 73846087

        self.fake_server = None
Ejemplo n.º 6
0
 def test_dag_depth3(self):
     """Test DAG depth for silly circuit.
     """
     q = QuantumRegister(6, 'q')
     c = ClassicalRegister(1, 'c')
     qc = QuantumCircuit(q, c)
     qc.h(q[0])
     qc.cx(q[0], q[1])
     qc.cx(q[1], q[2])
     qc.cx(q[2], q[3])
     qc.cx(q[3], q[4])
     qc.cx(q[4], q[5])
     qc.barrier(q[0])
     qc.barrier(q[0])
     qc.measure(q[0], c[0])
     dag = circuit_to_dag(qc)
     self.assertEqual(dag.depth(), 6)
Ejemplo n.º 7
0
    def after_operation(self):
        delayed_circ = []
        for qc_i in self.circuits:
            qr = QuantumRegister(qc_i.num_qubits)
            cr = ClassicalRegister(qc_i.num_qubits)
            delayed_qc = QuantumCircuit(qr, cr)
            delayed_qc.compose(qc_i, inplace=True)  # operation

            delayed_qc.barrier()
            delayed_qc.delay(duration=self.duration, qarg=qr, unit=self.unit)
            delayed_qc.barrier()

            delayed_qc.measure(delayed_qc.qubits, delayed_qc.clbits)
            delayed_circ.append(delayed_qc)
        if len(delayed_circ) == 1:
            return delayed_circ[0]
        return delayed_circ
Ejemplo n.º 8
0
    def test_disassemble_no_run_config(self):
        """Test disassembling with no run_config, relying on default."""
        qr = QuantumRegister(2, name="q")
        qc = ClassicalRegister(2, name="c")
        circ = QuantumCircuit(qr, qc, name="circ")
        circ.h(qr[0])
        circ.cx(qr[0], qr[1])
        circ.measure(qr, qc)

        qobj = assemble(circ)
        circuits, run_config_out, headers = disassemble(qobj)
        run_config_out = RunConfig(**run_config_out)
        self.assertEqual(run_config_out.n_qubits, 2)
        self.assertEqual(run_config_out.memory_slots, 2)
        self.assertEqual(len(circuits), 1)
        self.assertEqual(circuits[0], circ)
        self.assertEqual({}, headers)
Ejemplo n.º 9
0
 def test_while_loop_no_iteration(self, method):
     backend = self.backend(method=method)
 
     qreg = QuantumRegister(1)
     creg = ClassicalRegister(1)
     circ = QuantumCircuit(qreg, creg)
     circ.measure(0, 0)
     with circ.while_loop((creg, 1)):
         circ.y(0)
     circ.measure_all()
 
     result = backend.run(circ, method=method).result()
     self.assertSuccess(result)
 
     counts = result.get_counts()
     self.assertEqual(len(counts), 1)
     self.assertIn('0 0', counts)
Ejemplo n.º 10
0
    def construct_circuit(
        self,
        estimation_problem: EstimationProblem,
        k: int,
        measurement: bool = False
    ) -> Union[QuantumCircuit, Tuple[QuantumCircuit, List[int]]]:
        r"""Construct the circuit :math:`Q^k X |0\rangle>`.

        The A operator is the unitary specifying the QAE problem and Q the associated Grover
        operator.

        Args:
            estimation_problem: The estimation problem for which to construct the circuit.
            k: The power of the Q operator.
            measurement: Boolean flag to indicate if measurements should be included in the
                circuits.

        Returns:
            The circuit :math:`Q^k X |0\rangle`.
        """
        num_qubits = max(estimation_problem.state_preparation.num_qubits,
                         estimation_problem.grover_operator.num_qubits)
        circuit = QuantumCircuit(num_qubits, name='circuit')

        # add classical register if needed
        if measurement:
            c = ClassicalRegister(len(estimation_problem.objective_qubits))
            circuit.add_register(c)

        # add A operator
        circuit.compose(estimation_problem.state_preparation, inplace=True)

        # add Q^k
        if k != 0:
            circuit.compose(estimation_problem.grover_operator.power(k),
                            inplace=True)

            # add optional measurement
        if measurement:
            # real hardware can currently not handle operations after measurements, which might
            # happen if the circuit gets transpiled, hence we're adding a safeguard-barrier
            circuit.barrier()
            circuit.measure(estimation_problem.objective_qubits, c[:])

        return circuit
Ejemplo n.º 11
0
 def test_opaque_instruction(self):
     """Test the disassembler handles opaque instructions correctly."""
     opaque_inst = Instruction(name='my_inst',
                               num_qubits=4,
                               num_clbits=2,
                               params=[0.5, 0.4])
     q = QuantumRegister(6, name='q')
     c = ClassicalRegister(4, name='c')
     circ = QuantumCircuit(q, c, name='circ')
     circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
     qobj = assemble(circ)
     circuits, run_config_out, header = disassemble(qobj)
     run_config_out = RunConfig(**run_config_out)
     self.assertEqual(run_config_out.n_qubits, 6)
     self.assertEqual(run_config_out.memory_slots, 4)
     self.assertEqual(len(circuits), 1)
     self.assertEqual(circuits[0], circ)
     self.assertEqual({}, header)
Ejemplo n.º 12
0
    def test_assemble_opaque_inst(self):
        """Test opaque instruction is assembled as-is"""
        opaque_inst = Instruction(name='my_inst', num_qubits=4,
                                  num_clbits=2, params=[0.5, 0.4])
        q = QuantumRegister(6, name='q')
        c = ClassicalRegister(4, name='c')
        circ = QuantumCircuit(q, c, name='circ')
        circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])

        qobj = assemble(circ)
        validate_qobj_against_schema(qobj)

        self.assertIsInstance(qobj, QasmQobj)
        self.assertEqual(len(qobj.experiments[0].instructions), 1)
        self.assertEqual(qobj.experiments[0].instructions[0].name, 'my_inst')
        self.assertEqual(qobj.experiments[0].instructions[0].qubits, [0, 2, 5, 3])
        self.assertEqual(qobj.experiments[0].instructions[0].memory, [3, 0])
        self.assertEqual(qobj.experiments[0].instructions[0].params, [0.5, 0.4])
Ejemplo n.º 13
0
    def test_mirror_gate(self):
        """test mirroring a composite gate"""
        q = QuantumRegister(4)
        c = ClassicalRegister(4)
        circ = QuantumCircuit(q, c, name='circ')
        circ.h(q[0])
        circ.crz(0.1, q[0], q[1])
        circ.iden(q[1])
        circ.u3(0.1, 0.2, -0.2, q[0])
        gate = circ.to_instruction()

        circ = QuantumCircuit(q, c, name='circ')
        circ.u3(0.1, 0.2, -0.2, q[0])
        circ.iden(q[1])
        circ.crz(0.1, q[0], q[1])
        circ.h(q[0])
        gate_mirror = circ.to_instruction()
        self.assertEqual(gate.mirror().definition, gate_mirror.definition)
Ejemplo n.º 14
0
    def test_apply_operation_back_conditional_measure(self):
        """Test consistency of apply_operation_back for conditional measure."""

        # Measure targeting a clbit which is not a member of the conditional
        # register. qc.measure(qr[0], cr[0]).c_if(cr2, 0)

        new_creg = ClassicalRegister(1, 'cr2')
        self.dag.add_creg(new_creg)

        meas_gate = Measure()
        meas_gate.condition = (new_creg, 0)
        meas_node = self.dag.apply_operation_back(
            meas_gate, [self.qubit0], [self.clbit0], meas_gate.condition)

        self.assertEqual(meas_node.qargs, [self.qubit0])
        self.assertEqual(meas_node.cargs, [self.clbit0])
        self.assertEqual(meas_node.condition, meas_gate.condition)

        self.assertEqual(
            sorted(self.dag._get_multi_graph_in_edges(meas_node._node_id)),
            sorted([
                (self.dag.input_map[self.qubit0]._node_id, meas_node._node_id,
                 {'wire': self.qubit0, 'name': 'qr[0]'}),
                (self.dag.input_map[self.clbit0]._node_id, meas_node._node_id,
                 {'wire': self.clbit0, 'name': 'cr[0]'}),
                (self.dag.input_map[new_creg[0]]._node_id, meas_node._node_id,
                 {'wire': Clbit(new_creg, 0), 'name': 'cr2[0]'}),
            ]))

        self.assertEqual(
            sorted(self.dag._get_multi_graph_out_edges(meas_node._node_id)),
            sorted([
                (meas_node._node_id, self.dag.output_map[self.qubit0]._node_id,
                 {'wire': self.qubit0, 'name': 'qr[0]'}),
                (meas_node._node_id, self.dag.output_map[self.clbit0]._node_id,
                 {'wire': self.clbit0, 'name': 'cr[0]'}),
                (meas_node._node_id, self.dag.output_map[new_creg[0]]._node_id,
                 {'wire': Clbit(new_creg, 0), 'name': 'cr2[0]'}),
            ]))

        if self.dag._USE_RX:
            self.assertTrue(rx.is_directed_acyclic_graph(self.dag._multi_graph))
        else:
            self.assertTrue(nx.is_directed_acyclic_graph(self.dag._multi_graph))
Ejemplo n.º 15
0
    def test_validate_nr_classical_qubits_less_than_needed_for_storing_measured_qubits(
            self):
        api = Mock()
        api.create_project.return_value = {'id': 42}
        api.execute_qasm_async.return_value = 42
        api.get_backend_type_by_name.return_value = {
            'max_number_of_shots': 4096
        }
        simulator = QuantumInspireBackend(api, Mock())

        q = QuantumRegister(2, "q")
        c = ClassicalRegister(1, "c")
        qc = QuantumCircuit(q, c, name="conditional")
        qc.cx(q[0], q[1])

        self.assertRaisesRegex(
            QiskitBackendError,
            'Number of classical bits \(1\) is not sufficient for storing the '
            'outcomes of the experiment', simulator.run, qc)
Ejemplo n.º 16
0
 def test_transpile_mumbai_target(self):
     """Test that transpile respects a more involved target for a fake mumbai."""
     backend = FakeMumbaiFractionalCX()
     qc = QuantumCircuit(2)
     qc.h(0)
     qc.cx(1, 0)
     qc.measure_all()
     tqc = transpile(qc, backend)
     qr = QuantumRegister(27, "q")
     cr = ClassicalRegister(2, "meas")
     expected = QuantumCircuit(qr, cr, global_phase=math.pi / 4)
     expected.rz(math.pi / 2, 0)
     expected.sx(0)
     expected.rz(math.pi / 2, 0)
     expected.cx(1, 0)
     expected.barrier(qr[0:2])
     expected.measure(qr[0], cr[0])
     expected.measure(qr[1], cr[1])
     self.assertEqual(expected, tqc)
Ejemplo n.º 17
0
    def test_circuit_with_swap_gate(self):
        """Test if a virtual circuit with one swap gate is transformed into
        a circuit with physical qubits.

        [Circuit with virtual qubits]
          v0:--X---.---M(v0->c0)
               |   |
          v1:--X---|---M(v1->c1)
                   |
          v2:-----(+)--M(v2->c2)

         Initial layout: {v[0]: 2, v[1]: 1, v[2]: 0}

        [Circuit with physical qubits]
          q2:--X---.---M(q2->c0)
               |   |
          q1:--X---|---M(q1->c1)
                   |
          q0:-----(+)--M(q0->c2)
        """
        v = QuantumRegister(3, "v")
        cr = ClassicalRegister(3, "c")
        circuit = QuantumCircuit(v, cr)
        circuit.swap(v[0], v[1])
        circuit.cx(v[0], v[2])
        circuit.measure(v[0], cr[0])
        circuit.measure(v[1], cr[1])
        circuit.measure(v[2], cr[2])

        q = QuantumRegister(3, "q")
        expected = QuantumCircuit(q, cr)
        expected.swap(q[2], q[1])
        expected.cx(q[2], q[0])
        expected.measure(q[2], cr[0])
        expected.measure(q[1], cr[1])
        expected.measure(q[0], cr[2])

        dag = circuit_to_dag(circuit)
        pass_ = ApplyLayout()
        pass_.property_set["layout"] = Layout({v[0]: 2, v[1]: 1, v[2]: 0})
        after = pass_.run(dag)

        self.assertEqual(circuit_to_dag(expected), after)
Ejemplo n.º 18
0
    def test_convert_to_bfunc_plus_conditional(self):
        """Verify assemble_circuits converts conditionals from QASM to Qobj."""
        qr = QuantumRegister(1)
        cr = ClassicalRegister(1)
        qc = QuantumCircuit(qr, cr)

        qc.h(qr[0]).c_if(cr, 1)

        qobj = assemble(qc)

        bfunc_op, h_op = qobj.experiments[0].instructions

        self.assertEqual(bfunc_op.name, 'bfunc')
        self.assertEqual(bfunc_op.mask, '0x1')
        self.assertEqual(bfunc_op.val, '0x1')
        self.assertEqual(bfunc_op.relation, '==')

        self.assertTrue(hasattr(h_op, 'conditional'))
        self.assertEqual(bfunc_op.register, h_op.conditional)
    def test_mixed(self):
        """Test composing on named and unnamed registers."""
        qr = QuantumRegister(1, "my_qr")
        cr = ClassicalRegister(1, "my_cr")
        top = QuantumCircuit(qr, cr)
        top.x(0)
        top.measure(0, 0)

        bottom = QuantumCircuit(2)
        bottom.y(0)
        bottom.z(1)

        expect = QuantumCircuit(qr, *bottom.qregs, cr)
        expect.x(0)
        expect.y(1)
        expect.z(2)
        expect.measure(0, 0)

        self.assertEqual(bottom.tensor(top), expect)
Ejemplo n.º 20
0
    def setUp(self):
        qreg1 = QuantumRegister(3, 'lqr_1')
        qreg2 = QuantumRegister(2, 'lqr_2')
        creg = ClassicalRegister(2, 'lcr')

        self.circuit_left = QuantumCircuit(qreg1, qreg2, creg)
        self.circuit_left.h(qreg1[0])
        self.circuit_left.x(qreg1[1])
        self.circuit_left.u1(0.1, qreg1[2])
        self.circuit_left.cx(qreg2[0], qreg2[1])

        self.left_qubit0 = qreg1[0]
        self.left_qubit1 = qreg1[1]
        self.left_qubit2 = qreg1[2]
        self.left_qubit3 = qreg2[0]
        self.left_qubit4 = qreg2[1]
        self.left_clbit0 = creg[0]
        self.left_clbit1 = creg[1]
        self.condition = (creg, 3)
Ejemplo n.º 21
0
 def test_circuit_with_single_bit_conditions(self):
     """Verify disassemble handles a simple conditional on a single bit of a register."""
     # This circuit would fail to perfectly round-trip if 'cr' below had only one bit in it.
     # This is because the format of QasmQobj is insufficient to disambiguate single-bit
     # conditions from conditions on registers with only one bit. Since single-bit conditions are
     # mostly a hack for the QasmQobj format at all, `disassemble` always prefers to return the
     # register if it can.  It would also fail if registers overlap.
     qr = QuantumRegister(1)
     cr = ClassicalRegister(2)
     qc = QuantumCircuit(qr, cr)
     qc.h(qr[0]).c_if(cr[0], 1)
     qobj = assemble(qc)
     circuits, run_config_out, header = disassemble(qobj)
     run_config_out = RunConfig(**run_config_out)
     self.assertEqual(run_config_out.n_qubits, len(qr))
     self.assertEqual(run_config_out.memory_slots, len(cr))
     self.assertEqual(len(circuits), 1)
     self.assertEqual(circuits[0], qc)
     self.assertEqual({}, header)
Ejemplo n.º 22
0
    def circuit_instruction_circuit_roundtrip(self):
        """test converting between circuit and instruction and back
        preserves the circuit"""
        q = QuantumRegister(4)
        c = ClassicalRegister(4)
        circ1 = QuantumCircuit(q, c, name='circuit1')
        circ1.h(q[0])
        circ1.crz(0.1, q[0], q[1])
        circ1.iden(q[1])
        circ1.u3(0.1, 0.2, -0.2, q[0])
        circ1.barrier()
        circ1.measure(q, c)
        circ1.rz(0.8, q[0]).c_if(c, 6)
        inst = circ1.to_instruction()

        circ2 = QuantumCircuit(q, c, name='circ2')
        circ2.append(inst, q[:])

        self.assertEqual(circ1, circ2)
Ejemplo n.º 23
0
    def test_no_broadcast(self):
        """See https://github.com/Qiskit/qiskit-terra/issues/2777
        When creating custom instructions, do not broadcast parameters"""
        qr = QuantumRegister(2)
        cr = ClassicalRegister(2)
        subcircuit = QuantumCircuit(qr, cr, name='subcircuit')

        subcircuit.x(qr[0])
        subcircuit.h(qr[1])
        subcircuit.measure(qr[0], cr[0])
        subcircuit.measure(qr[1], cr[1])

        inst = subcircuit.to_instruction()
        circuit = QuantumCircuit(qr, cr, name='circuit')
        circuit.append(inst, qr[:], cr[:])
        self.assertEqual(circuit.qregs, [qr])
        self.assertEqual(circuit.cregs, [cr])
        self.assertEqual(circuit.qubits, [qr[0], qr[1]])
        self.assertEqual(circuit.clbits, [cr[0], cr[1]])
Ejemplo n.º 24
0
 def test_dag_depth1(self):
     """Test DAG depth #1
     """
     q1 = QuantumRegister(3, 'q1')
     q2 = QuantumRegister(2, 'q2')
     c = ClassicalRegister(5, 'c')
     qc = QuantumCircuit(q1, q2, c)
     qc.h(q1[0])
     qc.h(q1[1])
     qc.h(q1[2])
     qc.h(q2[0])
     qc.h(q2[1])
     qc.ccx(q2[1], q1[0], q2[0])
     qc.cx(q1[0], q1[1])
     qc.cx(q1[1], q2[1])
     qc.cx(q2[1], q1[2])
     qc.cx(q1[2], q2[0])
     dag = circuit_to_dag(qc)
     self.assertEqual(dag.depth(), 6)
Ejemplo n.º 25
0
    def setUp(self):
        self.dag = DAGCircuit()
        qreg = QuantumRegister(3, 'qr')
        creg = ClassicalRegister(2, 'cr')
        self.dag.add_qreg(qreg)
        self.dag.add_creg(creg)
        self.dag.add_basis_element(name='h', number_qubits=1,
                                   number_classical=0, number_parameters=0)
        self.dag.add_basis_element('cx', 2, 0, 0)
        self.dag.add_basis_element('x', 1, 0, 0)
        self.dag.add_basis_element('measure', 1, 1, 0)
        self.dag.add_basis_element('reset', 1, 0, 0)

        self.qubit0 = qreg[0]
        self.qubit1 = qreg[1]
        self.qubit2 = qreg[2]
        self.clbit0 = creg[0]
        self.clbit1 = creg[1]
        self.condition = (creg, 3)
Ejemplo n.º 26
0
def dag_to_circuit(dag):
    """Build a ``QuantumCircuit`` object from a ``DAGCircuit``.

    Args:
        dag (DAGCircuit): the input dag.

    Return:
        QuantumCircuit: the circuit representing the input dag.
    """
    qregs = collections.OrderedDict()
    for qreg in dag.qregs.values():
        qreg_tmp = QuantumRegister(qreg.size, name=qreg.name)
        qregs[qreg.name] = qreg_tmp
    cregs = collections.OrderedDict()
    for creg in dag.cregs.values():
        creg_tmp = ClassicalRegister(creg.size, name=creg.name)
        cregs[creg.name] = creg_tmp

    name = dag.name or None
    circuit = QuantumCircuit(*qregs.values(), *cregs.values(), name=name)

    for node in dag.nodes_in_topological_order():
        if node.type == 'op':
            qubits = []
            for qubit in node.qargs:
                qubits.append(qregs[qubit[0].name][qubit[1]])

            clbits = []
            for clbit in node.cargs:
                clbits.append(cregs[clbit[0].name][clbit[1]])

            # Get arguments for classical control (if any)
            if node.condition is None:
                control = None
            else:
                control = (node.condition[0], node.condition[1])

            inst = copy.deepcopy(node.op)
            inst.control = control
            circuit.append(inst, qubits, clbits)

    return circuit
Ejemplo n.º 27
0
    def test_do_not_merge_conditioned_gates(self):
        """Validate that classically conditioned gates are never considered for
        inclusion in a block. Note that there are cases where gates conditioned
        on the same (register, value) pair could be correctly merged, but this is
        not yet implemented.

                 ┌─────────┐┌─────────┐┌─────────┐      ┌───┐
        qr_0: |0>┤ U1(0.1) ├┤ U1(0.2) ├┤ U1(0.3) ├──■───┤ X ├────■───
                 └─────────┘└────┬────┘└────┬────┘┌─┴─┐ └─┬─┘  ┌─┴─┐
        qr_1: |0>────────────────┼──────────┼─────┤ X ├───■────┤ X ├─
                                 │          │     └───┘   │    └─┬─┘
        qr_2: |0>────────────────┼──────────┼─────────────┼──────┼───
                              ┌──┴──┐    ┌──┴──┐       ┌──┴──┐┌──┴──┐
         cr_0: 0 ═════════════╡     ╞════╡     ╞═══════╡     ╞╡     ╞
                              │ = 0 │    │ = 0 │       │ = 0 ││ = 1 │
         cr_1: 0 ═════════════╡     ╞════╡     ╞═══════╡     ╞╡     ╞
                              └─────┘    └─────┘       └─────┘└─────┘

        Previously the blocks collected were : [['u1', 'u1', 'u1', 'cx', 'cx', 'cx']]
        This is now corrected to : [['cx']]
        """
        # ref: https://github.com/Qiskit/qiskit-terra/issues/3215

        print("BEGIN MERGE CONDITION ")

        qr = QuantumRegister(3, "qr")
        cr = ClassicalRegister(2, "cr")

        qc = QuantumCircuit(qr, cr)
        qc.u1(0.1, 0)
        qc.u1(0.2, 0).c_if(cr, 0)
        qc.u1(0.3, 0).c_if(cr, 0)
        qc.cx(0, 1)
        qc.cx(1, 0).c_if(cr, 0)
        qc.cx(0, 1).c_if(cr, 1)

        pass_manager = PassManager()
        pass_manager.append(CollectMultiQBlocks())

        pass_manager.run(qc)
        for block in pass_manager.property_set["block_list"]:
            self.assertTrue(len(block) <= 1)
Ejemplo n.º 28
0
    def test_mirror_instruction(self):
        """test mirroring an instruction with conditionals"""
        q = QuantumRegister(4)
        c = ClassicalRegister(4)
        circ = QuantumCircuit(q, c, name='circ')
        circ.t(q[1])
        circ.u3(0.1, 0.2, -0.2, q[0])
        circ.barrier()
        circ.measure(q[0], c[0])
        circ.rz(0.8, q[0]).c_if(c, 6)
        inst = circ.to_instruction()

        circ = QuantumCircuit(q, c, name='circ')
        circ.rz(0.8, q[0]).c_if(c, 6)
        circ.measure(q[0], c[0])
        circ.barrier()
        circ.u3(0.1, 0.2, -0.2, q[0])
        circ.t(q[1])
        inst_mirror = circ.to_instruction()
        self.assertEqual(inst.mirror().definition, inst_mirror.definition)
Ejemplo n.º 29
0
    def test_disassemble_single_circuit(self):
        """Test disassembling a single circuit.
        """
        qr = QuantumRegister(2, name='q')
        cr = ClassicalRegister(2, name='c')
        circ = QuantumCircuit(qr, cr, name='circ')
        circ.h(qr[0])
        circ.cx(qr[0], qr[1])
        circ.measure(qr, cr)

        qobj = assemble(circ, shots=2000, memory=True)
        circuits, run_config_out, headers = disassemble(qobj)
        run_config_out = RunConfig(**run_config_out)
        self.assertEqual(run_config_out.n_qubits, 2)
        self.assertEqual(run_config_out.memory_slots, 2)
        self.assertEqual(run_config_out.shots, 2000)
        self.assertEqual(run_config_out.memory, True)
        self.assertEqual(len(circuits), 1)
        self.assertEqual(circuits[0], circ)
        self.assertEqual({}, headers)
Ejemplo n.º 30
0
    def test_validate_nr_classical_qubits_less_than_nr_qubits_conditional_gate(
            self):
        api = Mock()
        api.create_project.return_value = {'id': 42}
        api.execute_qasm_async.return_value = 42
        api.get_backend_type_by_name.return_value = {
            'max_number_of_shots': 4096
        }
        simulator = QuantumInspireBackend(api, Mock())

        q = QuantumRegister(2, "q")
        c = ClassicalRegister(4, "c")
        qc = QuantumCircuit(q, c, name="conditional")
        qc.cx(q[0], q[1]).c_if(c, 1)
        qc.measure(0, 1)
        self.assertRaisesRegex(
            QiskitBackendError,
            'Number of classical bits must be less than or equal to the'
            ' number of qubits when using conditional gate operations',
            simulator.run, qc)