コード例 #1
0
    def test_multi_register_reordering(self, qe_token, qe_url):
        """a more complicated reordering across 3 registers of different sizes"""
        sim, real = self._get_backends(qe_token, qe_url)
        if not sim or real:
            raise unittest.SkipTest('no remote device available')

        qr0 = qiskit.QuantumRegister(2)
        qr1 = qiskit.QuantumRegister(2)
        qr2 = qiskit.QuantumRegister(1)
        cr0 = qiskit.ClassicalRegister(2)
        cr1 = qiskit.ClassicalRegister(2)
        cr2 = qiskit.ClassicalRegister(1)
        circuit = qiskit.QuantumCircuit(qr0, qr1, qr2, cr0, cr1, cr2)
        circuit.h(qr0[0])
        circuit.cx(qr0[0], qr2[0])
        circuit.x(qr1[1])
        circuit.h(qr2[0])
        circuit.cx(qr2[0], qr1[0])
        circuit.barrier()
        circuit.measure(qr0[0], cr2[0])
        circuit.measure(qr0[1], cr0[1])
        circuit.measure(qr1[0], cr0[0])
        circuit.measure(qr1[1], cr1[0])
        circuit.measure(qr2[0], cr1[1])

        shots = 4000
        qobj_real = transpiler.transpile(circuit, real)
        qobj_sim = transpiler.transpile(circuit, sim)
        result_real = real.run(qobj_real).result(timeout=600)
        result_sim = sim.run(qobj_sim).result(timeout=600)
        counts_real = result_real.get_counts()
        counts_sim = result_sim.get_counts()
        threshold = 0.2 * shots
        self.assertDictAlmostEqual(counts_real, counts_sim, threshold)
コード例 #2
0
    def test_final_measurement_barrier_for_devices(self, mock_pass):
        """Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices."""

        circ = QuantumCircuit.from_qasm_file(self._get_resource_path('example.qasm', Path.QASMS))
        layout = Layout.generate_trivial_layout(*circ.qregs)
        transpile(circ, coupling_map=FakeRueschlikon().configuration().coupling_map,
                  initial_layout=layout)

        self.assertTrue(mock_pass.called)
コード例 #3
0
 def time_ibmq_backend_transpile(self, _):
     # Run with ibmq_16_melbourne configuration
     coupling_map = [[1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5,
                                                               4], [5, 6],
                     [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3],
                     [11, 10], [11, 12], [12, 2], [13, 1], [13, 12]]
     transpiler.transpile(self.circuit,
                          basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],
                          coupling_map=coupling_map)
コード例 #4
0
 def assertScheduler(self, dag, passmanager, expected):
     """
     Runs transpiler(dag, passmanager) and checks if the passes run as expected.
     Args:
         dag (DAGCircuit): DAG circuit to transform via transpilation.
         passmanager (PassManager): pass manager instance for the tranpilation process
         expected (list): List of things the passes are logging
     """
     with self.assertLogs(logger, level='INFO') as cm:
         transpile(dag, pass_manager=passmanager)
     self.assertEqual([record.message for record in cm.records], expected)
コード例 #5
0
 def setUp(self):
     self.seed = 88
     self.qasm_filename = self._get_resource_path('qasm/example.qasm')
     with open(self.qasm_filename, 'r') as qasm_file:
         self.qasm_text = qasm_file.read()
         self.qasm_ast = qiskit.qasm.Qasm(data=self.qasm_text).parse()
         self.qasm_be = qiskit.unroll.CircuitBackend(
             ['u1', 'u2', 'u3', 'id', 'cx'])
         self.qasm_circ = qiskit.unroll.Unroller(self.qasm_ast,
                                                 self.qasm_be).execute()
     qr = QuantumRegister(2, 'q')
     cr = ClassicalRegister(2, 'c')
     qc = QuantumCircuit(qr, cr)
     qc.h(qr[0])
     qc.measure(qr[0], cr[0])
     self.qc = qc
     # create qobj
     compiled_circuit1 = transpile(DAGCircuit.fromQuantumCircuit(self.qc),
                                   format='json')
     compiled_circuit2 = transpile(DAGCircuit.fromQuantumCircuit(
         self.qasm_circ),
                                   format='json')
     self.qobj = {
         'id':
         'test_qobj',
         'config': {
             'max_credits': 3,
             'shots': 2000,
             'backend_name': 'local_qasm_simulator_cpp',
             'seed': 1111
         },
         'circuits': [{
             'name': 'test_circuit1',
             'compiled_circuit': compiled_circuit1,
             'basis_gates': 'u1,u2,u3,cx,id',
             'layout': None,
         }, {
             'name': 'test_circuit2',
             'compiled_circuit': compiled_circuit2,
             'basis_gates': 'u1,u2,u3,cx,id',
             'layout': None,
         }]
     }
     self.qobj = Qobj.from_dict(self.qobj)
     # Simulator backend
     try:
         self.backend = QasmSimulatorCpp()
     except FileNotFoundError as fnferr:
         raise unittest.SkipTest('cannot find {} in path'.format(fnferr))
コード例 #6
0
    def test_commutative_circuit2(self):
        """
        A simple circuit where three CNOTs commute, the first and the last cancel,
        also two X gates cancel and two Rz gates combine.

        qr0:----.---------------.--------     qr0:-------------
                |               |
        qr1:---(+)---(+)--[X]--(+)--[X]--  =  qr1:--------(+)--
                      |                                    |
        qr2:---[Rz]---.---[Rz]-[T]--[S]--     qr2:--[U1]---.---
        """
        qr = QuantumRegister(3, 'qr')
        circuit = QuantumCircuit(qr)
        circuit.cx(qr[0], qr[1])
        circuit.rz(sympy.pi / 3, qr[2])
        circuit.cx(qr[2], qr[1])
        circuit.rz(sympy.pi / 3, qr[2])
        circuit.t(qr[2])
        circuit.s(qr[2])
        circuit.x(qr[1])
        circuit.cx(qr[0], qr[1])
        circuit.x(qr[1])

        passmanager = PassManager()
        passmanager.append(CommutativeCancellation())
        new_circuit = transpile(circuit, pass_manager=passmanager)
        expected = QuantumCircuit(qr)
        expected.u1(sympy.pi * 17 / 12, qr[2])
        expected.cx(qr[2], qr[1])

        self.assertEqual(expected, new_circuit)
コード例 #7
0
    def test_commutative_circuit1(self):
        """A simple circuit where three CNOTs commute, the first and the last cancel.

        qr0:----.---------------.--       qr0:------------
                |               |
        qr1:---(+)-----(+)-----(+)-   =   qr1:-------(+)--
                        |                             |
        qr2:---[H]------.----------       qr2:---[H]--.---
        """
        qr = QuantumRegister(3, 'qr')
        circuit = QuantumCircuit(qr)
        circuit.cx(qr[0], qr[1])
        circuit.h(qr[2])
        circuit.cx(qr[2], qr[1])
        circuit.cx(qr[0], qr[1])

        passmanager = PassManager()
        passmanager.append(CommutativeCancellation())
        new_circuit = transpile(circuit, pass_manager=passmanager)

        expected = QuantumCircuit(qr)
        expected.h(qr[2])
        expected.cx(qr[2], qr[1])

        self.assertEqual(expected, new_circuit)
コード例 #8
0
ファイル: custom.py プロジェクト: artix41/qiskit-aqua
 def _convert_to_basis_gates(circuit):
     # get the circuits from compiled circuit
     unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id'])
     pm = PassManager(passes=[unroller])
     qc = transpiler.transpile(circuit, get_aer_backend('qasm_simulator'),
                               pass_manager=pm)
     return qc
コード例 #9
0
ファイル: run_circuits.py プロジェクト: tigerjack/qiskit-aqua
def _compile_wrapper(circuits, backend, backend_config, compile_config,
                     run_config):
    transpiled_circuits = transpiler.transpile(circuits, backend,
                                               **backend_config,
                                               **compile_config)
    qobj = assemble_circuits(transpiled_circuits, run_config=run_config)
    return qobj, transpiled_circuits
コード例 #10
0
def compile_ibm(num_qubits, topology, program):
    if topology.lower() == 'ring':
        edge_list = []
        initial_layout = {}
        for i in range(0, num_qubits):
            edge_list.append((i, (i + 1) % num_qubits))
            initial_layout[("qr", i)] = ("qr", i)

        topology = nx.from_edgelist(edge_list)
        executable = transpiler.transpile(circuits=program,
                                          basis_gates="cx,u1,u2,u3",
                                          seed_mapper=1,
                                          coupling_map=edge_list,
                                          initial_layout=initial_layout)
        depth = executable.depth()
        volume = executable.size()
        q2_count = two_qubit_count(executable)
        qasm = executable.qasm()
        print(qasm)
        out_str = qasm
        out_str = out_str + (
            "//DEPTH (returned by QISKIT): %s |VOL.: %s |2Q GATE COUNT: %s \n"
            % (depth, volume, q2_count))
        out_str = out_str + ("//calculated depth (max gates/qubit): %s\n" %
                             (compute_depth_ibm(qasm)))
        print("DEPTH (returned by QISKIT): %s |VOL.: %s |2Q GATE COUNT: %s " %
              (depth, volume, q2_count))
        print("calculated depth (max gates/qubit): %s" %
              (compute_depth_ibm(qasm)))
        print()
        print()
        return out_str
コード例 #11
0
 def test_2q_unitary(self):
     """test 2 qubit unitary matrix"""
     backend = BasicAer.get_backend('qasm_simulator')
     qr = QuantumRegister(2)
     cr = ClassicalRegister(2)
     qc = QuantumCircuit(qr, cr)
     sigmax = numpy.array([[0, 1], [1, 0]])
     sigmay = numpy.array([[0, -1j], [1j, 0]])
     matrix = numpy.kron(sigmax, sigmay)
     qc.x(qr[0])
     uni2q = Unitary(matrix)
     qc.append(uni2q, [qr[0], qr[1]])
     passman = PassManager()
     passman.append(CXCancellation())
     qc2 = transpile(qc, backend, pass_manager=passman)
     # test of qasm output
     self.log.info(qc2.qasm())
     # test of text drawer
     self.log.info(qc2)
     dag = circuit_to_dag(qc)
     nodes = dag.twoQ_nodes()
     self.assertTrue(len(nodes) == 1)
     dnode = nodes[0]
     self.assertIsInstance(dnode.op, Unitary)
     for qubit in dnode.qargs:
         self.assertTrue(qubit[1] in [0, 1])
     self.assertTrue(numpy.allclose(dnode.op._representation, matrix))
     qc3 = dag_to_circuit(dag)
     self.assertEqual(qc2, qc3)
コード例 #12
0
    def test_transpiler_layout_from_intlist(self):
        """A list of ints gives layout to correctly map circuit.
        virtual  physical
         q1_0  -  4   ---[H]---
         q2_0  -  5
         q2_1  -  6   ---[H]---
         q3_0  -  8
         q3_1  -  9
         q3_2  -  10  ---[H]---

        """
        qr1 = QuantumRegister(1, 'qr1')
        qr2 = QuantumRegister(2, 'qr2')
        qr3 = QuantumRegister(3, 'qr3')
        qc = QuantumCircuit(qr1, qr2, qr3)
        qc.h(qr1[0])
        qc.h(qr2[1])
        qc.h(qr3[2])
        layout = [4, 5, 6, 8, 9, 10]

        cmap = [[1, 0], [1, 2], [2, 3], [4, 3], [4, 10],
                [5, 4], [5, 6], [5, 9], [6, 8], [7, 8],
                [9, 8], [9, 10], [11, 3], [11, 10],
                [11, 12], [12, 2], [13, 1], [13, 12]]

        new_circ = transpile(qc, backend=None,
                             coupling_map=cmap,
                             basis_gates=['u2'],
                             initial_layout=layout)
        mapped_qubits = []
        for _, qargs, _ in new_circ.data:
            mapped_qubits.append(qargs[0][1])

        self.assertEqual(mapped_qubits, [4, 6, 10])
コード例 #13
0
ファイル: transpiler.py プロジェクト: jagunnels/qiskit-sdk-py
def transpile(circuits, transpile_config=None):
    """Compile a list of circuits into a list of optimized circuits.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        transpile_config (TranspileConfig): configuration for the transpiler

    Returns:
        circuits: the optimized circuits
    """

    # ------------
    # TODO: This is a hack while we are still using the old transpiler.
    initial_layout = getattr(transpile_config, 'initial_layout', None)
    basis_gates = getattr(transpile_config, 'basis_gates', None)
    coupling_map = getattr(transpile_config, 'coupling_map', None)
    seed_mapper = getattr(transpile_config, 'seed_mapper', None)

    if initial_layout is not None and not isinstance(initial_layout, Layout):
        initial_layout = Layout(initial_layout)

    pass_manager = None
    backend = getattr(transpile_config, 'backend', None)
    new_circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map,
                                        initial_layout, seed_mapper, pass_manager)
    # ---------

    # THE IDEAL CODE HERE WILL BE.
    # 1 set up the pass_manager using transpile_config options
    # pass_manager = PassManager(TranspileConig)
    # run the passes
    # new_circuits = pass_manager.run(circuits)
    return new_circuits
コード例 #14
0
ファイル: test_transpiler.py プロジェクト: Styps/qiskit-terra
    def test_already_mapped_1(self):
        """Circuit not remapped if matches topology.

        See: https://github.com/Qiskit/qiskit-terra/issues/342
        """
        backend = FakeRueschlikon()
        coupling_map = backend.configuration().coupling_map
        basis_gates = backend.configuration().basis_gates

        qr = QuantumRegister(16, 'qr')
        cr = ClassicalRegister(16, 'cr')
        qc = QuantumCircuit(qr, cr)
        qc.cx(qr[3], qr[14])
        qc.cx(qr[5], qr[4])
        qc.h(qr[9])
        qc.cx(qr[9], qr[8])
        qc.x(qr[11])
        qc.cx(qr[3], qr[4])
        qc.cx(qr[12], qr[11])
        qc.cx(qr[13], qr[4])
        qc.measure(qr, cr)

        new_qc = transpile(qc,
                           coupling_map=coupling_map,
                           basis_gates=basis_gates)
        cx_qubits = [
            qargs for (gate, qargs, _) in new_qc.data if gate.name == "cx"
        ]
        cx_qubits_physical = [[ctrl[1], tgt[1]] for [ctrl, tgt] in cx_qubits]
        self.assertEqual(sorted(cx_qubits_physical),
                         [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]])
コード例 #15
0
ファイル: test_transpiler.py プロジェクト: Styps/qiskit-terra
    def test_pass_manager_none(self):
        """Test passing the default (None) pass manager to the transpiler.

        It should perform the default qiskit flow:
        unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates
        and should be equivalent to using tools.compile
        """
        qr = QuantumRegister(2, 'qr')
        circuit = QuantumCircuit(qr)
        circuit.h(qr[0])
        circuit.h(qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.cx(qr[1], qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.cx(qr[1], qr[0])

        coupling_map = [[1, 0]]
        basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']

        backend = BasicAer.get_backend('qasm_simulator')
        circuit2 = transpile(circuit,
                             backend=backend,
                             coupling_map=coupling_map,
                             basis_gates=basis_gates,
                             pass_manager=None)

        qobj = compile(circuit,
                       backend=backend,
                       coupling_map=coupling_map,
                       basis_gates=basis_gates)
        qobj2 = assemble(circuit2,
                         qobj_id=qobj.qobj_id,
                         shots=1024,
                         max_credits=10)
        self.assertEqual(qobj, qobj2)
コード例 #16
0
    def test_a_cx_to_map(self):
        """A single CX needs to be remapped.

         q0:----------m-----
                      |
         q1:-[H]-(+)--|-m---
                  |   | |
         q2:------.---|-|-m-
                      | | |
         c0:----------.-|-|-
         c1:------------.-|-
         c2:--------------.-

         CouplingMap map: [1]<-[0]->[2]

        expected count: '000': 50%
                        '110': 50%
        """
        self.counts = {'000': 512, '110': 512}
        self.shots = 1024
        self.delta = 5
        coupling_map = [[0, 1], [0, 2]]

        qr = QuantumRegister(3, 'q')
        cr = ClassicalRegister(3, 'c')
        circuit = QuantumCircuit(qr, cr, name='a_cx_to_map')
        circuit.h(qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.measure(qr, cr)

        result = transpile(circuit, self.create_backend(), coupling_map=coupling_map,
                           seed_mapper=self.seed_mapper,
                           pass_manager=self.create_passmanager(coupling_map))
        self.assertResult(result, circuit)
コード例 #17
0
ファイル: test_transpiler.py プロジェクト: Styps/qiskit-terra
    def test_move_measurements(self):
        """Measurements applied AFTER swap mapping.
        """
        backend = FakeRueschlikon()
        cmap = backend.configuration().coupling_map
        circ = QuantumCircuit.from_qasm_file(
            self._get_resource_path('move_measurements.qasm', Path.QASMS))

        lay = Layout({
            ('qa', 0): ('q', 0),
            ('qa', 1): ('q', 1),
            ('qb', 0): ('q', 15),
            ('qb', 1): ('q', 2),
            ('qb', 2): ('q', 14),
            ('qN', 0): ('q', 3),
            ('qN', 1): ('q', 13),
            ('qN', 2): ('q', 4),
            ('qc', 0): ('q', 12),
            ('qNt', 0): ('q', 5),
            ('qNt', 1): ('q', 11),
            ('qt', 0): ('q', 6)
        })
        out = transpile(circ, initial_layout=lay, coupling_map=cmap)
        out_dag = circuit_to_dag(out)
        meas_nodes = out_dag.named_nodes('measure')
        for meas_node in meas_nodes:
            is_last_measure = all([
                after_measure.type == 'out'
                for after_measure in out_dag.quantum_successors(meas_node)
            ])
            self.assertTrue(is_last_measure)
コード例 #18
0
    def test_pass_manager_none(self):
        """Test passing the default (None) pass manager to the transpiler.

        It should perform the default qiskit flow:
        unroll, swap_mapper, direction_mapper, cx cancellation, optimize_1q_gates
        and should be equivalent to using wrapper.compile
        """
        q = QuantumRegister(2)
        circ = QuantumCircuit(q)
        circ.h(q[0])
        circ.h(q[0])
        circ.cx(q[0], q[1])
        circ.cx(q[0], q[1])
        circ.cx(q[0], q[1])
        circ.cx(q[0], q[1])

        coupling_map = [[1, 0]]
        basis_gates = 'u1,u2,u3,cx,id'

        dag_circuit = DAGCircuit.fromQuantumCircuit(circ)
        dag_circuit = transpile(dag_circuit, coupling_map=coupling_map,
                                basis_gates=basis_gates, pass_manager=None)
        transpiler_json = DagUnroller(dag_circuit, JsonBackend(dag_circuit.basis)).execute()

        qobj = wrapper.compile(circ, backend='local_qasm_simulator',
                               coupling_map=coupling_map, basis_gates=basis_gates)
        compiler_json = qobj.experiments[0].as_dict()

        # Remove extra Qobj header parameters.
        compiler_json.pop('config')
        compiler_json['header'].pop('name')
        compiler_json['header'].pop('compiled_circuit_qasm')

        self.assertDictEqual(transpiler_json, compiler_json)
コード例 #19
0
def optimize_circuit(circuit, coupling_list=None):
    """Use the qiskit transpiler module to perform a suite of optimizations on
    the given circuit, including imposing swap coupling.
    Args:
    circuit :: qiskit.QuantumCircuit - the circuit to optimize
    coupling_list :: [(int, int)] - the list of connected qubit pairs
                     if None is passed in, will not perform mapping

    Returns:
    optimized_circuit :: qiskit.QuantumCircuit - the optimized circuit
    """
    # TODO: optimize until gates count stays stagnant.
    # TODO: implement rotation merge for clifford gates as pass.
    merge_rotation_gates(circuit)

    coupling_map = None if coupling_list is None else CouplingMap(
        coupling_list)

    pass_manager = PassManager()
    pass_manager.append(HCancellation())
    pass_manager.append(CXCancellation())
    # Some CNOT identities are interleaved between others,
    # for this reason a second pass is required. More passes
    # may be required for other circuits.
    pass_manager.append(CXCancellation())
    if coupling_map is not None:
        pass_manager.append(BasicSwap(coupling_map))

    optimized_circuit = transpile(circuit,
                                  backend=state_backend,
                                  coupling_map=coupling_list,
                                  pass_manager=pass_manager)

    return optimized_circuit
コード例 #20
0
    def test_optimize_undone_swap(self):
        """ Remove redundant swap
            qr0:--X--X--m--       qr0:--m---
                  |  |  |               |
            qr1:--X--X--|--  ==>  qr1:--|--
                        |               |
            cr0:--------.--       cr0:--.--
        """
        qr = QuantumRegister(2, 'qr')
        cr = ClassicalRegister(1, 'cr')
        circuit = QuantumCircuit(qr, cr)
        circuit.swap(qr[0], qr[1])
        circuit.swap(qr[0], qr[1])
        circuit.measure(qr[0], cr[0])

        expected = QuantumCircuit(qr, cr)
        expected.measure(qr[0], cr[0])

        pass_manager = PassManager()
        pass_manager.append(
            [OptimizeSwapBeforeMeasure(),
             DAGFixedPoint()],
            do_while=lambda property_set: not property_set['dag_fixed_point'])
        after = transpile(circuit, pass_manager=pass_manager)

        self.assertEqual(expected, after)
コード例 #21
0
 def parse_circuit(self, circuit):
     dag_circuit = dagcircuit.DAGCircuit.fromQuantumCircuit(
         circuit, expand_gates=False)
     self._ast = transpiler.transpile(dag_circuit,
                                      basis_gates=self._basis,
                                      format='json')
     self._registers()
     self._ops = self._ast['instructions']
コード例 #22
0
def compile(circuits,
            backend,
            config=None,
            basis_gates=None,
            coupling_map=None,
            initial_layout=None,
            shots=1024,
            max_credits=10,
            seed=None,
            qobj_id=None,
            hpc=None,
            skip_transpiler=False,
            seed_mapper=None):
    """Compile a list of circuits into a qobj.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        config (dict): dictionary of parameters (e.g. noise) used by runner
        basis_gates (str): comma-separated basis gate set to compile to
        coupling_map (list): coupling map (perhaps custom) to target in mapping
        initial_layout (list): initial layout of qubits in mapping
        shots (int): number of repetitions of each circuit, for sampling
        max_credits (int): maximum credits to use
        seed (int): random seed for simulators
        seed_mapper (int): random seed for swapper mapper
        qobj_id (int): identifier for the generated qobj
        hpc (dict): HPC simulator parameters
        skip_transpiler (bool): skip most of the compile steps and produce qobj directly

    Returns:
        Qobj: the qobj to be run on the backends

    Raises:
        TranspilerError: in case of bad compile options, e.g. the hpc options.

    """

    pass_manager = None  # default pass manager which executes predetermined passes
    if skip_transpiler:  # empty pass manager which does nothing
        pass_manager = PassManager()

    dags = transpiler.transpile(circuits, backend, basis_gates, coupling_map,
                                initial_layout, seed_mapper, hpc, pass_manager)

    # step 3: Making a qobj
    qobj_standard = dags_2_qobj(dags,
                                backend_name=backend.name(),
                                config=config,
                                shots=shots,
                                max_credits=max_credits,
                                qobj_id=qobj_id,
                                basis_gates=basis_gates,
                                coupling_map=coupling_map,
                                seed=seed)

    return qobj_standard
コード例 #23
0
 def test_compile_quantum_circuit(self):
     """Test instantiating gate with variable parmeters"""
     theta = Parameter('θ')
     qr = QuantumRegister(1)
     qc = QuantumCircuit(qr)
     qc.rx(theta, qr)
     backend = BasicAer.get_backend('qasm_simulator')
     qc_aer = transpile(qc, backend)
     self.assertIn(theta, qc_aer.parameters)
コード例 #24
0
    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        with open(self.qasm_filename, 'r') as qasm_file:
            self.qasm_text = qasm_file.read()
            self.qasm_ast = qiskit.qasm.Qasm(data=self.qasm_text).parse()
            self.qasm_be = qiskit.unroll.CircuitBackend(['u1', 'u2', 'u3', 'id', 'cx'])
            self.qasm_circ = qiskit.unroll.Unroller(self.qasm_ast, self.qasm_be).execute()
        qr = QuantumRegister(2, 'q')
        cr = ClassicalRegister(2, 'c')
        qc = QuantumCircuit(qr, cr)
        qc.h(qr[0])
        qc.measure(qr[0], cr[0])
        self.qc = qc

        # create qobj
        compiled_circuit1 = QobjExperiment.from_dict(
            transpile(DAGCircuit.fromQuantumCircuit(self.qc), format='json'))

        compiled_circuit2 = QobjExperiment.from_dict(
            transpile(DAGCircuit.fromQuantumCircuit(self.qasm_circ),
                      format='json'))

        self.qobj = Qobj(
            qobj_id='test_qobj',
            config=QobjConfig(
                shots=2000, memory_slots=1,
                max_credits=3,
                seed=1111
            ),
            experiments=[compiled_circuit1, compiled_circuit2],
            header=QobjHeader(backend_name='local_qasm_simulator_cpp')
        )
        self.qobj.experiments[0].header.name = 'test_circuit1'
        self.qobj.experiments[0].config = QobjItem(basis_gates='u1,u2,u3,cx,id')
        self.qobj.experiments[1].header.name = 'test_circuit2'
        self.qobj.experiments[1].config = QobjItem(basis_gates='u1,u2,u3,cx,id')

        # Simulator backend
        try:
            self.backend = QasmSimulatorCpp()
        except FileNotFoundError as fnferr:
            raise unittest.SkipTest(
                'cannot find {} in path'.format(fnferr))
コード例 #25
0
 def test_compile_quantum_circuit(self):
     """Test instantiating gate with variable parmeters"""
     theta = sympy.Symbol('θ')
     qr = QuantumRegister(1)
     qc = QuantumCircuit(qr)
     qc.rx(theta, qr)
     backend = BasicAer.get_backend('qasm_simulator')
     qc_aer = transpile(qc, backend)
     qobj = assemble_circuits(qc_aer)
     self.assertIn(theta, qobj.experiments[0].instructions[0].params)
コード例 #26
0
ファイル: run_circuits.py プロジェクト: pistoia/qiskit-aqua
def _compile_wrapper(circuits, backend, backend_config, compile_config,
                     run_config):
    transpiled_circuits = transpiler.transpile(circuits, backend,
                                               **backend_config,
                                               **compile_config)
    qobj = circuits_to_qobj(transpiled_circuits,
                            user_qobj_header=QobjHeader(),
                            run_config=run_config,
                            qobj_id=None)
    return qobj, transpiled_circuits
コード例 #27
0
def compile(circuits, backend,
            config=None, basis_gates=None, coupling_map=None, initial_layout=None,
            shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None,
            pass_manager=None, memory=False):
    """Compile a list of circuits into a qobj.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        config (dict): dictionary of parameters (e.g. noise) used by runner
        basis_gates (list[str]): list of basis gates names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): coupling map (perhaps custom) to target in mapping
        initial_layout (list): initial layout of qubits in mapping
        shots (int): number of repetitions of each circuit, for sampling
        max_credits (int): maximum credits to use
        seed (int): random seed for simulators
        seed_mapper (int): random seed for swapper mapper
        qobj_id (int): identifier for the generated qobj
        pass_manager (PassManager): a pass manger for the transpiler pipeline
        memory (bool): if True, per-shot measurement bitstrings are returned as well

    Returns:
        Qobj: the qobj to be run on the backends

    Raises:
        QiskitError: if the desired options are not supported by backend
    """
    warnings.warn('qiskit.compile() is deprecated and will be removed in Qiskit Terra 0.9. '
                  'Please use qiskit.transpile() to transform circuits '
                  'and qiskit.assemble_circuits() to produce qobj.',
                  DeprecationWarning)

    run_config = RunConfig()

    if config:
        warnings.warn('config is not used anymore. Set all configs in '
                      'run_config.', DeprecationWarning)
    if shots:
        run_config.shots = shots
    if max_credits:
        run_config.max_credits = max_credits
    if seed:
        run_config.seed = seed
    if memory:
        run_config.memory = memory

    new_circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map,
                                        initial_layout, seed_mapper, pass_manager)

    qobj = assemble_circuits(new_circuits, qobj_header=None, run_config=run_config,
                             qobj_id=qobj_id)

    return qobj
コード例 #28
0
    def test_empty_dag(self):
        """ Empty DAG."""
        circuit = QuantumCircuit()
        passmanager = PassManager()
        passmanager.append(ResourceEstimation())
        _ = transpile(circuit, FakeRueschlikon(), pass_manager=passmanager)

        self.assertEqual(passmanager.property_set['size'], 0)
        self.assertEqual(passmanager.property_set['depth'], 0)
        self.assertEqual(passmanager.property_set['width'], 0)
        self.assertDictEqual(passmanager.property_set['count_ops'], {})
コード例 #29
0
    def test_initialize_FakeMelbourne(self):
        """Test that the zero-state resets are remove in a device not supporting them.
        """
        desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)]
        qr = QuantumRegister(3, "qr")
        qc = QuantumCircuit(qr)
        qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])

        out = transpile(qc, backend=FakeMelbourne())
        out_dag = circuit_to_dag(out)
        reset_nodes = out_dag.named_nodes('reset')

        self.assertEqual(reset_nodes, [])
コード例 #30
0
    def test_compile_remote(self, qe_token, qe_url):
        """Test Compiler remote."""
        IBMQ.enable_account(qe_token, qe_url)
        backend = least_busy(IBMQ.backends())

        qubit_reg = QuantumRegister(2, name='q')
        clbit_reg = ClassicalRegister(2, name='c')
        qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)

        circuits = transpile(qc, backend)
        self.assertIsInstance(circuits, QuantumCircuit)