Пример #1
0
    def process_circuits(
        self,
        circuits: Iterable[Circuit],
        n_shots: Optional[int] = None,
        valid_check: bool = True,
        **kwargs: KwargTypes,
    ) -> List[ResultHandle]:
        """
        See :py:meth:`pytket.backends.Backend.process_circuits`.
        Supported kwargs: none.
        """
        if n_shots is None or n_shots < 1:
            raise ValueError("Parameter n_shots is required for this backend")

        if valid_check:
            self._check_all_circuits(circuits)
        basebody = {
            "machine": self._device_name,
            "language": "OPENQASM 2.0",
            "priority": "normal",
            "count": n_shots,
            "options": None,
        }
        handle_list = []
        for i, circ in enumerate(circuits):
            honeywell_circ = circuit_to_qasm_str(circ, header="hqslib1")
            body = basebody.copy()
            body["name"] = circ.name if circ.name else f"{self._label}_{i}"
            body["program"] = honeywell_circ
            if self._api_handler is None:
                handle_list.append(
                    ResultHandle(_DEBUG_HANDLE_PREFIX +
                                 str((circ.n_qubits, n_shots))))
            else:
                try:
                    res = _submit_job(self._api_handler, body)
                    if res.status_code != HTTPStatus.OK:
                        self.relogin()
                        res = _submit_job(self._api_handler, body)

                    jobdict = res.json()
                    if res.status_code != HTTPStatus.OK:
                        raise HQSAPIError(
                            f'HTTP error submitting job, {jobdict["error"]["text"]}'
                        )
                except ConnectionError:
                    raise ConnectionError(
                        f"{self._label} Connection Error: Error during submit..."
                    )

                # extract job ID from response
                handle = ResultHandle(jobdict["job"])
                handle_list.append(handle)
                self._cache[handle] = dict()

        return handle_list
Пример #2
0
def rebase_gates_ibm(circ: QuantumCircuit) -> QuantumCircuit:
    """
    Helper function to rebase the circuits to IBM gate set

    :param circ:
    :return:
    """
    cu = CompilationUnit(circuit_from_qasm_str(circ.qasm()))
    rebase_ibm = RebaseIBM()
    rebase_ibm.apply(cu)
    circ_out = QuantumCircuit.from_qasm_str(circuit_to_qasm_str(cu.circuit))
    return circ_out
Пример #3
0
    def _optimize(self, c):
        c_tket = pyzx_to_tk(c)
        FullPeepholeOptimise().apply(c_tket)

        # FIXME: Failing equality!
        # RebasePyZX().apply(c_tket)
        # c_opt = tk_to_pyzx(c_tket)

        # FIXME: Failing equality!
        qasm_str = circuit_to_qasm_str(c_tket)
        c_opt = zx.Circuit.from_qasm(qasm_str)

        return c_opt
Пример #4
0
def tket_evaluation(circ: QuantumCircuit) -> QuantumCircuit:
    """
    Evaluation of the cirquit optimizer by tket
    :param circ:
    :return:
    """
    log.warning("Evaluating tket")
    tketpass = FullPeepholeOptimise()
    refine_circs = RebasePyZX()
    cu = CompilationUnit(circuit_from_qasm_str(circ.qasm()))
    tketpass.apply(cu)
    refine_circs.apply(cu)
    res_circ = zx.Circuit.from_qasm(circuit_to_qasm_str(
        cu.circuit)).split_phase_gates()
    circ_out = zx_circuit_to_qiskit_circuit(res_circ)
    log.warning("Done!")
    return circ_out
Пример #5
0
def test_convert() -> None:
    circ = Circuit(4)
    circ.H(0).CX(0, 1)
    circ.add_gate(OpType.noop, [1])
    circ.CRz(0.5, 1, 2)
    circ.add_barrier([2])
    circ.ZZPhase(0.3, 2, 3).CX(3, 0).Tdg(1)
    circ.measure_all()

    RebaseHQS().apply(circ)
    circ_hqs = circuit_to_qasm_str(circ, header="hqslib1")
    qasm_str = circ_hqs.split("\n")[6:-1]
    test = True
    for com in qasm_str:
        test &= any(
            com.startswith(gate)
            for gate in ("rz", "U1q", "ZZ", "measure", "barrier"))
    assert test
Пример #6
0
    def generate_ibm(self):
        #generate IBM-specific circuits
        #IBM imports
        import qiskit as qk
        from qiskit.tools.monitor import job_monitor
        from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout
        from qiskit import Aer, IBMQ, execute
        from qiskit.providers.aer import noise
        from qiskit.providers.aer.noise import NoiseModel
        from qiskit.circuit import quantumcircuit
        from qiskit.circuit import Instruction

        print("Creating IBM quantum circuit objects...")
        with open(self.namevar, 'a') as tempfile:
            tempfile.write("Creating IBM quantum circuit objects...\n")
        name = 0
        self.q_regs = qk.QuantumRegister(self.num_spins, 'q')
        self.c_regs = qk.ClassicalRegister(self.num_spins, 'c')
        backend = self.device
        self.ibm_circuits_list = []
        for program in self.programs_list:
            ibm_circ = get_ibm_circuit(backend, program, self.q_regs,
                                       self.c_regs, self.device)
            self.ibm_circuits_list.append(ibm_circ)
        print("IBM quantum circuit objects created")
        with open(self.namevar, 'a') as tempfile:
            tempfile.write("IBM quantum circuit objects created\n")

        if (self.compile == "True"):
            provider = qk.IBMQ.get_provider(group='open')
            #print(provider.backends())
            device = provider.get_backend(self.device)
            if (self.compiler == "native"):
                print("Transpiling circuits...")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Transpiling circuits...\n")
                temp = qk.compiler.transpile(self.ibm_circuits_list,
                                             backend=device,
                                             optimization_level=2)
                self.ibm_circuits_list = temp
                print("Circuits transpiled successfully")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Circuits transpiled successfully\n")
            elif (self.compiler == "tket"):
                from pytket.qiskit import qiskit_to_tk
                from pytket.backends.ibm import IBMQBackend, IBMQEmulatorBackend, AerBackend
                from pytket.qasm import circuit_to_qasm_str
                if self.device == "":
                    tket_backend = AerBackend()
                else:
                    if (self.QCQS == "QC"):
                        tket_backend = IBMQBackend(self.device)
                    else:
                        tket_backend = IBMQEmulatorBackend(self.device)
                print("Compiling circuits...")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Compiling circuits...\n")
                circs = []
                for circuit in self.ibm_circuit_list:
                    tket_circ = qiskit_to_tk(circuit)
                    tket_backend.compile_circuit(tket_circ)
                    qasm_str = circuit_to_qasm_str(tket_circ)
                    ibm_circ = qk.QuantumCircuit.from_qasm_str(qasm_str)
                    circs.append(tket_circ)
                self.ibm_circuits_list = circs
                print("Circuits compiled successfully")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Circuits compiled successfully\n")
Пример #7
0
def get_circuit_qasm(circuit):
    return circuit_to_qasm_str(circuit)