How to use the qiskit.compiler.transpile function in qiskit

To help you get started, we’ve selected a few qiskit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Qiskit / qiskit-terra / test / python / compiler / test_transpiler.py View on Github external
def test_parameter_expression_circuit_for_simulator(self):
        """Verify that a circuit including expressions of parameters can be
        transpiled for a simulator backend."""
        qr = QuantumRegister(2, name='qr')
        qc = QuantumCircuit(qr)

        theta = Parameter('theta')
        square = theta * theta
        qc.rz(square, qr[0])

        transpiled_qc = transpile(qc, backend=BasicAer.get_backend('qasm_simulator'))

        expected_qc = QuantumCircuit(qr)
        expected_qc.u1(square, qr[0])

        self.assertEqual(expected_qc, transpiled_qc)
github Qiskit / qiskit-ibmq-provider / test / ibmq / test_ibmq_job.py View on Github external
def test_run_multiple_device(self, backend):
        """Test running multiple jobs in a real device."""
        num_qubits = 5
        qr = QuantumRegister(num_qubits, 'qr')
        cr = ClassicalRegister(num_qubits, 'cr')
        qc = QuantumCircuit(qr, cr)
        for i in range(num_qubits - 1):
            qc.cx(qr[i], qr[i + 1])
        qc.measure(qr, cr)
        qobj = assemble(transpile(qc, backend=backend), backend=backend)
        num_jobs = 3
        job_array = [backend.run(qobj, validate_qobj=True) for _ in range(num_jobs)]
        time.sleep(3)  # give time for jobs to start (better way?)
        job_status = [job.status() for job in job_array]
        num_init = sum(
            [status is JobStatus.INITIALIZING for status in job_status])
        num_queued = sum([status is JobStatus.QUEUED for status in job_status])
        num_running = sum(
            [status is JobStatus.RUNNING for status in job_status])
        num_done = sum([status is JobStatus.DONE for status in job_status])
        num_error = sum([status is JobStatus.ERROR for status in job_status])
        self.log.info('number of currently initializing jobs: %d/%d',
                      num_init, num_jobs)
        self.log.info('number of currently queued jobs: %d/%d',
                      num_queued, num_jobs)
        self.log.info('number of currently running jobs: %d/%d',
github Qiskit / qiskit-terra / test / python / transpiler / test_resource_estimation_pass.py View on Github external
def test_just_qubits(self):
        """ A dag with 8 operations and no classic bits"""
        qr = QuantumRegister(2)
        circuit = QuantumCircuit(qr)
        circuit.h(qr[0])
        circuit.h(qr[1])
        circuit.cx(qr[0], qr[1])
        circuit.cx(qr[0], qr[1])
        circuit.cx(qr[0], qr[1])
        circuit.cx(qr[0], qr[1])
        circuit.cx(qr[1], qr[0])
        circuit.cx(qr[1], qr[0])

        passmanager = PassManager()
        passmanager.append(ResourceEstimation())
        _ = transpile(circuit, FakeRueschlikon(), pass_manager=passmanager)

        self.assertEqual(passmanager.property_set['size'], 8)
        self.assertEqual(passmanager.property_set['depth'], 7)
        self.assertEqual(passmanager.property_set['width'], 2)
        self.assertDictEqual(passmanager.property_set['count_ops'], {'cx': 6, 'h': 2})
github Qiskit / qiskit / test / benchmarks / qft.py View on Github external
def time_simulator_transpile(self, _):
        transpile(self.circuit, self.sim_backend)
github Qiskit / qiskit-aer / test / benchmark / tools.py View on Github external
for _ in repeat(None, depth):
        # Generate uniformly random permutation Pj of [0...n-1]
        perm = rng.permutation(num_qubits)
        # For each consecutive pair in Pj, generate Haar random SU(4)
        # Decompose each SU(4) into CNOT + SU(2) and add to Ci
        for k in range(math.floor(num_qubits / 2)):
            # Generate random SU(4) matrix
            X = (rng.randn(4, 4) + 1j * rng.randn(4, 4))
            SU4, _ = linalg.qr(X)  # Q is a unitary matrix
            SU4 /= pow(linalg.det(SU4), 1 / 4)  # make Q a special unitary
            qubits = [qr[int(perm[2 * k])], qr[int(perm[2 * k + 1])]]
            circuit.unitary(SU4, qubits)
    if measure is True:
        circuit = _add_measurements(circuit, qr)
    # Transpile to force it into u1,u2,u3,cx basis gates
    return transpile(circuit, basis_gates=['u1', 'u2', 'u3', 'cx'])
github Qiskit / qiskit-terra / test / python / transpiler / test_naming_transpiled_circuits.py View on Github external
def test_multiple_circuits_name_list(self):
        """Test output_name with a list of circuits
        Given multiple circuits and a list for output names, if
        len(list)=len(circuits), then test checks whether transpile func assigns
        each element in list to respective circuit.
        If lengths are not equal, then test checks whether transpile func raises
        error.
        """
        # combining multiple circuits
        circuits = [self.circuit1, self.circuit2, self.circuit3]
        # equal lengths
        names = ['awesome-circ1', 'awesome-circ2', 'awesome-circ3']
        trans_circuits = transpile(circuits, self.backend, output_name=names)
        self.assertEqual(trans_circuits[0].name, 'awesome-circ1')
        self.assertEqual(trans_circuits[1].name, 'awesome-circ2')
        self.assertEqual(trans_circuits[2].name, 'awesome-circ3')
github Qiskit / qiskit-aer / test / terra / noise / test_noise_model.py View on Github external
backend = QasmSimulator()

        # Asymetric readout error on qubit-0 only
        probs_given0 = [0.9, 0.1]
        probs_given1 = [0.3, 0.7]
        noise_model = NoiseModel()
        noise_model.add_readout_error([probs_given0, probs_given1], [0])

        shots = 2000
        target = {
            '0x0': probs_given0[0] * shots / 2,
            '0x1': probs_given0[1] * shots / 2,
            '0x2': probs_given1[0] * shots / 2,
            '0x3': probs_given1[1] * shots / 2
        }
        circuit = transpile(circuit, basis_gates=noise_model.basis_gates)
        qobj = assemble([circuit], backend, shots=shots)
        result = backend.run(qobj, noise_model=noise_model).result()
        self.is_completed(result)
        self.compare_counts(result, [circuit], [target], delta=0.05 * shots)
github Qiskit / qiskit-terra / test / python / aer_provider_integration_test / test_aer_qobj_headers.py View on Github external
def test_job_qobj(self):
        """Test job.qobj()."""
        for backend in qiskit.providers.aer.Aer.backends():
            with self.subTest(backend=backend):
                qc1_new = transpile(self.qc1, backend=backend)
                qobj = assemble(qc1_new, shots=1000)

                job = backend.run(qobj)
                self.assertEqual(job.qobj(), qobj)
github Qiskit / qiskit-aqua / qiskit / aqua / utils / controlled_circuit.py View on Github external
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)

    # get all operations from compiled circuit
    unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id'])
    pm = PassManager(passes=[unroller])
    ops = compiler.transpile(
        circuit,
        BasicAer.get_backend('qasm_simulator'),
        pass_manager=pm
    ).data

    # process all basis gates to add control
    if not qc.has_register(ctl_qubit.register):
        qc.add(ctl_qubit.register)
    for op in ops:
        if op[0].name == 'id':
            apply_cu3(qc, 0, 0, 0, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
        elif op[0].name == 'u1':
            apply_cu1(qc, *op[0].params, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
        elif op[0].name == 'u2':
            apply_cu3(qc, np.pi / 2, *op[0].params, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
        elif op[0].name == 'u3':