예제 #1
0
def run_qiskit_pass(fpath: str, backend: str):
    try:
        qsc = QuantumCircuit.from_qasm_file(fpath)
        if backend == _BACKEND_IBM:
            basis_gates = ['u1', 'u2', 'u3', 'cx']
            two_qb_gate = OpType.CX
            cm = CouplingMap(ibm_coupling)
        elif backend == _BACKEND_RIGETTI:
            basis_gates = ['u1', 'u2', 'u3', 'cx']
            two_qb_gate = OpType.CX
            cm = CouplingMap(rigetti_coupling)
        elif backend == _BACKEND_GOOGLE:
            basis_gates = ['u1', 'u2', 'u3', 'cx']
            two_qb_gate = OpType.CX
            cm = CouplingMap(google_coupling)
        else:  # _BACKEND_FULL
            basis_gates = ['u1', 'u2', 'u3', 'cx']
            two_qb_gate = OpType.CX
            cm = None
        if comp_pass == _PASS_QISO1:
            opt_level = 1
        elif comp_pass == _PASS_QISO2:
            opt_level = 2
        elif comp_pass == _PASS_QISO3:
            opt_level = 3
        start_time = time.process_time()
        qsc2 = transpile(qsc,
                         basis_gates=basis_gates,
                         coupling_map=cm,
                         optimization_level=opt_level)
        time_elapsed = time.process_time() - start_time
        print(time_elapsed)
        circ2 = qiskit_to_tk(qsc2)
        return [
            circ2.n_gates,
            circ2.depth(),
            circ2.n_gates_of_type(two_qb_gate),
            circ2.depth_by_type(two_qb_gate), time_elapsed
        ]
    except Exception as e:
        print(e)
        print("qiskit error")
        return [nan, nan, nan, nan, nan]
예제 #2
0
    def run(self, dag:DAGCircuit) -> DAGCircuit:
        """
           Run one pass of optimisation on the circuit and route for the given backend.

        :param dag: The circuit to optimise and route

        :return: The modified circuit
        """

        qc = dag_to_circuit(dag)
        circ = qiskit_to_tk(qc)
        circ, circlay = self.process_circ(circ)
        qc = tk_to_qiskit(circ)
        newdag = circuit_to_dag(qc)
        newdag.name = dag.name 
        finlay = dict()
        for i, qi in enumerate(circlay):
            finlay[('q', i)] = ('q', qi)
        newdag.final_layout = finlay
        return newdag
예제 #3
0
    def generate_rigetti(self):
        import pyquil
        from pyquil.quil import Program
        from pyquil.gates import H, RX, RZ, CZ, RESET, MEASURE
        from pyquil.api import get_qc
        self.rigetti_circuits_list = []
        #Rigettti imports
        import pyquil
        from pyquil.quil import Program
        from pyquil.gates import H, RX, RZ, CZ, RESET, MEASURE
        from pyquil.api import get_qc

        print("Creating Pyquil program list...")
        with open(self.namevar, 'a') as tempfile:
            tempfile.write("Creating Pyquil program list...\n")
        for circuit in self.programs_list:
            p = pyquil.Program(RESET())  #compressed program
            ro = p.declare('ro', memory_type='BIT', memory_size=self.num_spins)
            for gate in circuit.gates:
                if gate.name != "":
                    if gate.name in "X":
                        p.inst(pyquil.gates.X(gate.qubits[0]))
                    elif gate.name in "Y":
                        p.inst(pyquil.gates.Y(gate.qubits[0]))
                    elif gate.name in "Z":
                        p.inst(pyquil.gates.Z(gate.qubits[0]))
                    elif gate.name in "H":
                        p.inst(pyquil.gates.H(gate.qubits[0]))
                    elif gate.name in "RZ":
                        p.inst(pyquil.gates.RZ(gate.angles[0], gate.qubits[0]))
                    elif gate.name in "RX":
                        p.inst(pyquil.gates.RX(gate.angles[0], gate.qubits[0]))
                    elif gate.name in "CNOT":
                        p.inst(
                            pyquil.gates.CNOT(gate.qubits[0], gate.qubits[1]))
                    else:
                        print("Unrecognized gate: {}".format(gate.name))
            for i in range(self.num_spins):
                p.inst(pyquil.gates.MEASURE(i, ro[i]))
            p.wrap_in_numshots_loop(self.shots)
            self.rigetti_circuits_list.append(p)

        if "True" in self.compile:
            if self.QCQS in ["QS"]:
                qc = get_qc(self.device, as_qvm=True)
            else:
                qc = get_qc(self.device)
            qc.compiler.set_timeout(100)

            if self.compiler in "native":
                temp = []
                print("Transpiling circuits...")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Transpiling circuits...\n")
                for circuit in self.rigetti_circuits_list:
                    circ = qc.compile(circuit)
                    temp.append(circ)
                self.rigetti_circuits_list = temp
                print("Circuits transpiled successfully")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Circuits transpiled successfully\n")
            elif self.compiler in "tket":
                temp = []
                from pytket.pyquil import pyquil_to_tk
                from pytket.backends.forest import ForestBackend
                if self.device == "":
                    qvm = '{}q-qvm'.format(self.num_spins)
                    tket_backend = ForestBackend(qvm, simulator=True)
                else:
                    if self.QCQS in ["QC"]:
                        tket_backend = ForestBackend(self.device)
                    else:
                        tket_backend = ForestBackend(self.device,
                                                     simulator=True)
                print("Compiling circuits...")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Compiling circuits...\n")
                for circuit in self.rigetti_circuits_list:
                    tket_circ = qiskit_to_tk(circuit)
                    tket_backend.compile_circuit(tket_circ)
                    temp.append(tket_circ)
                self.ibm_circuits_list = temp
                print("Circuits compiled successfully")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Circuits compiled successfully\n")

        print("Pyquil program list created successfully")
        with open(self.namevar, 'a') as tempfile:
            tempfile.write("Pyquil program list created successfully\n")
예제 #4
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")
예제 #5
0
from qiskit.test.mock import FakeTokyo, FakeRochester, FakeMelbourne
from qiskit.transpiler import CouplingMap

# Tested with pytket 0.6.1

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

directory = 'benchmarks_qasm/'

qasm_file = 'path to your qasm file'

q_circ = QuantumCircuit.from_qasm_file(qasm_file)

tk_circ = qiskit_to_tk(q_circ)

backend = FakeMelbourne()
coupling_list = backend.configuration().coupling_map
coupling_map = CouplingMap(coupling_list)

characterisation = process_characterisation(backend)
directed_arc = Device(
    characterisation.get("NodeErrors", {}),
    characterisation.get("EdgeErrors", {}),
    characterisation.get("Architecture", Architecture([])),
)

comp_tk = tk_circ.copy()

DecomposeBoxes().apply(comp_tk)
예제 #6
0
def schedule_swaps(environment,
                   circuit,
                   qubit_locations=None,
                   safety_checks_on=False,
                   decompose_cnots=False):
    original_circuit = circuit

    circuit = qiskit_to_tk(circuit.to_qiskit_rep())
    architecture = generate_architecture(environment)

    if qubit_locations is None:
        qubit_locations = list(range(environment.number_of_nodes))
        random.shuffle(qubit_locations)

    initial_index_map = {
        qubit: node
        for node, qubit in enumerate(qubit_locations)
    }
    initial_map = convert_index_mapping(circuit, architecture,
                                        initial_index_map)

    initial_qubit_locations = [-1] * len(qubit_locations)

    for k, v in initial_map.items():
        q = k.index[0]
        n = v.index[0]

        initial_qubit_locations[n] = q

    place_with_map(circuit, initial_map)
    routed_circuit = route(circuit,
                           architecture,
                           swap_lookahead=1000,
                           bridge_interactions=0,
                           bridge_lookahead=0)

    node_circuit = NodeCircuit.from_qiskit_rep(tk_to_qiskit(routed_circuit),
                                               decompose=decompose_cnots)

    if decompose_cnots:
        Transform.DecomposeSWAPtoCX().apply(routed_circuit)
        #Transform.DecomposeBRIDGE().apply(routed_circuit)

    tket_depth = routed_circuit.depth()

    calculated_depth = node_circuit.depth()

    if tket_depth != calculated_depth:
        print('Tket depth:', tket_depth)
        print('Calculated depth:', calculated_depth)
        print()

        exit("Tket depth disagrees with calculated depth")

    layers = assemble_timesteps_from_gates(node_circuit.n_nodes,
                                           node_circuit.gates)

    if safety_checks_on:
        verify_circuit(original_circuit, node_circuit, environment,
                       initial_qubit_locations)

    return layers, tket_depth