Exemple #1
0
    def get_counts(self, circuit, shots, fit_to_constraints=True):
        """
        Run the circuit on the backend and accumulate the results into a summary of counts

        :param circuit: The circuit to run
        :param shots: Number of shots (repeats) to run
        :param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True
        :param seed: Random seed to for simulator
        :return: Dictionary mapping bitvectors of results to number of times that result was observed (zero counts are omitted)
        """
        if fit_to_constraints:
            qc = _routed_ibmq_circuit(circuit, self.architecture)
        else:
            qc = tk_to_qiskit(circuit)
        valid, measures = _qiskit_circ_valid(qc, self.coupling)
        if not valid:
            raise RuntimeWarning(
                "QuantumCircuit does not pass validity test, will likely fail on remote backend."
            )
        if not measures:
            raise RuntimeWarning("Measure gates are required for output.")
        qobj = assemble(qc, shots=shots)
        job = self._backend.run(qobj)
        counts = job.result().get_counts(qc)
        return {tuple(_convert_bin_str(b)): c for b, c in counts.items()}
Exemple #2
0
    def run(self,
            circuit: Circuit,
            shots: int,
            fit_to_constraints: bool = True) -> np.ndarray:
        if fit_to_constraints:
            qc = _routed_ibmq_circuit(circuit, self.architecture)
        else:
            qc = tk_to_qiskit(circuit)
        valid, measures = _qiskit_circ_valid(qc, self.coupling)
        if not valid:
            raise RuntimeWarning(
                "QuantumCircuit does not pass validity test, will likely fail on remote backend."
            )
        if not measures:
            raise RuntimeWarning("Measure gates are required for output.")

        qobj = assemble(qc, shots=shots, memory=self.config.memory)
        job = self._backend.run(qobj)
        if self._monitor:
            job_monitor(job)

        shot_list = []
        if self.config.memory:
            shot_list = job.result().get_memory(qc)
        else:
            for string, count in job.result().get_counts().items():
                shot_list += [string] * count
        return np.asarray([_convert_bin_str(shot) for shot in shot_list])
Exemple #3
0
def print_circuit(tk_circuit):
    """Convert circuit to IBM Qiskit supported gates, and print that circuit

    Parameters
    ----------
    tk_circuit : pytket Circuit
        A pytket circuit"""
    print(tk_to_qiskit(tk_circuit))
Exemple #4
0
def simulate(circuit, shots=1024, x="0", verbose=False):
    """simulates circuit with given input

	Args:
	    circuit (QuantumCircuit): Circuit to be simualted
	    shots (int, optional): number of shots to simulate
	    x (str, optional): input string
	    verbose (bool, optional): prints extra output

	Returns:
	    TYPE: dictionary of simulation
	"""
    if type(circuit) == Circuit:  #is a tket circuit
        return simulate(tk_to_qiskit(circuit),
                        shots=shots,
                        x=x,
                        verbose=verbose)  #converts to qiskit
    names = []
    regs = []
    for q in circuit.qubits:
        name = q.register.name
        size = len(q.register)
        if name not in names:
            names.append(name)
            regs.append(size)

    if verbose: print(names, regs)

    #assuming that we only have 2: control + anciallary
    qra = QuantumRegister(regs[0], name=names[0])
    if len(regs) > 1:
        qran = QuantumRegister(regs[1], name=names[1])
        qa = QuantumCircuit(qra, qran)
    else:
        qa = QuantumCircuit(qra)

    if len(x) != sum(regs): x += "0" * (sum(regs) - len(x))
    if verbose: print(x)
    for bit in range(len(x)):
        if verbose: print(x[bit], type(x[bit]))
        if x[bit] != "0":
            qa.x(bit)
    qa.barrier()

    qa.extend(circuit)

    if verbose:
        print(qa)
    """backend_sim = Aer.get_backend('statevector_simulator')
				job_sim = execute(qa, backend_sim)
				statevec = job_sim.result().get_statevector()"""

    backend = BasicAer.get_backend('qasm_simulator')
    results = execute(qa, backend=backend, shots=shots).result()
    answer = results.get_counts()
    return answer
Exemple #5
0
def _routed_ibmq_circuit(circuit: Circuit,
                         arc: Architecture) -> QuantumCircuit:
    c = circuit.copy()
    Transform.RebaseToQiskit().apply(c)
    physical_c = route(c, arc)
    physical_c.decompose_SWAP_to_CX()
    physical_c.redirect_CX_gates(arc)
    Transform.OptimisePostRouting().apply(physical_c)
    qc = tk_to_qiskit(physical_c)

    return qc
Exemple #6
0
def circuit_to_ibm(tk_circuit):
    """Convert circuit to IBM Qiskit compatible verison, given pytket circuit

    Parameters
    ----------
    tk_circuit : pytket Circuit
        A pytket circuit

    Returns
    -------
    pytket Circuit
        An IBM Qiskit compatible pytket circuit"""
    return tk_to_qiskit(tk_circuit)
Exemple #7
0
    def get_state(self, circuit, fit_to_constraints=True) :
        """
        Calculate the statevector for a circuit.


        :param circuit: circuit to calculate
        :return: complex numpy array of statevector
        """
        c = circuit.copy()
        if fit_to_constraints :
            Transform.RebaseToQiskit().apply(c)
        qc = tk_to_qiskit(c)
        qobj = assemble(qc)
        job = self._backend.run(qobj)
        return np.asarray(job.result().get_statevector(qc, decimals=16))
Exemple #8
0
 def get_unitary(self, circuit, fit_to_constraints=True) :
     """
     Obtains the unitary for a given quantum circuit
     
     :param circuit: The circuit to inspect
     :type circuit: Circuit
     :param fit_to_constraints: Forces the circuit to be decomposed into the correct gate set, defaults to True
     :type fit_to_constraints: bool, optional
     :return: The unitary of the circuit. Qubits are ordered with qubit 0 as the least significant qubit
     """
     c = circuit.copy()
     if fit_to_constraints :
         Transform.RebaseToQiskit().apply(c)
     qc = tk_to_qiskit(c)
     qobj = assemble(qc)
     job = self._backend.run(qobj)
     return job.result().get_unitary(qc)
Exemple #9
0
    def get_counts(self, circuit, shots, fit_to_constraints=True, seed=None) :
        """
        Run the circuit on the backend and accumulate the results into a summary of counts

        :param circuit: The circuit to run
        :param shots: Number of shots (repeats) to run
        :param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True
        :param seed: Random seed to for simulator
        :return: Dictionary mapping bitvectors of results to number of times that result was observed (zero counts are omitted)
        """
        c = circuit.copy()
        if fit_to_constraints :
            Transform.RebaseToQiskit().apply(c)
        qc = tk_to_qiskit(c)
        qobj = assemble(qc, shots=shots, seed_simulator=seed)
        job = self._backend.run(qobj, noise_model=self.noise_model)
        counts = job.result().get_counts(qc)
        return {tuple(_convert_bin_str(b)) : c for b, c in counts.items()}
Exemple #10
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
Exemple #11
0
 def run(self, circuit:Circuit, shots:int, fit_to_constraints=True, seed:int=None) -> np.ndarray:
     """Run a circuit on Qiskit Aer Qasm simulator.
     
     :param circuit: The circuit to run
     :type circuit: Circuit
     :param shots: Number of shots (repeats) to run
     :type shots: int
     :param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True
     :type fit_to_constraints: bool, optional
     :param seed: random seed to for simulator
     :type seed: int
     :return: Table of shot results, each row is a shot, columns are ordered by qubit ordering. Values are 0 or 1, corresponding to qubit basis states.
     :rtype: numpy.ndarray
     """
     c = circuit.copy()
     if fit_to_constraints :
         Transform.RebaseToQiskit().apply(c)
     qc = tk_to_qiskit(c)
     qobj = assemble(qc, shots=shots, seed_simulator=seed, memory=True)
     job = self._backend.run(qobj, noise_model=self.noise_model)
     shot_list = job.result().get_memory(qc)
     return np.asarray([_convert_bin_str(shot) for shot in shot_list])
    for q in range(nqubits-2):
        oracle.H(q+2)
        oracle.CCX(q,q+1,q+2)
        oracle.H(q+2)

    for q in range(nqubits):
        oracle.X(q)
        oracle.H(q)
    ALALI.print_circuit(oracle)
    return oracle


glycineSmiles = 'C(C(=O)O)N'
oracle = construct_oracle(getAtomicGraph(glycineSmiles))
#need to convert the pytket created circuit into one that IBM can understand
grover_circuit = tk_to_qiskit(runGrovers(oracle))
#need to measure all results
grover_circuit.measure_all()
#Now, we can setup an actual device to try out our search algorithm, yay!
backend = Aer.get_backend('qasm_simulator')
shots = 1024
results = execute(grover_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)

#Okay, now you should see a pretty graph showing you your different qubit states and their respective probabilities. 
#As you can see, this algorithm does show the species within the chemical system that have the most polarity. However, this could 
#be further refined to best actually fit the respecive noises seen by each element involved.


Exemple #13
0
from qiskit import QuantumCircuit
import sys


def tket_run(file_name, device_name):
    connection_list = qcdevice(device_name).connection_list
    circ = circuit_from_qasm(file_name)
    circ.measure_all()
    arc = Architecture(connection_list)
    dev = Device(arc)
    routed_circ = route(circ, arc)
    # cu = CompilationUnit(routed_circ)
    Transform.DecomposeBRIDGE().apply(routed_circ)
    # pass1 = DecomposeSwapsToCXs(dev)
    # pass1.apply(cu)
    # circ2 = cu.circuit
    return routed_circ


file_name = sys.argv[1]
device_name = sys.argv[2]
new_file_name = "result/paper/" + file_name.split('/')[-1].replace(
    '.qasm', "_{}_tket".format(device_name))

original_cx_count = qiskit_info_original(file_name, new_file_name)[1]

routed_circ = tket_run(file_name, device_name)
# circuit_to_qasm(circ, "result/paper/" + file_name.split('/')[-1] + "_tket.qasm")
circ = tk_to_qiskit(routed_circ)
qiskit_info_after(circ, new_file_name, original_cx_count)
Exemple #14
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