# Setting up the backend
print("(Aer Backends)")
for backend in BasicAer.backends():
    print(backend.status())
qasm_simulator = BasicAer.get_backend('qasm_simulator')

# Compile and run the circuit on a real device backend
# See a list of available remote backends
print("\n(IBMQ Backends)")
for backend in provider.backends():
    print(backend.status())

try:
    # select least busy available device and execute.
    least_busy_device = least_busy(provider.backends(simulator=False))
except:
    print("All devices are currently unavailable.")

print("Running on current least busy device: ", least_busy_device)

# Transpile the circuits to make them compatible with the experimental backend
[qc1_new, qc2_new] = transpile(circuits=[qc1, qc2], backend=least_busy_device)

print("Bell circuit before transpile:")
print(qc1)
print("Bell circuit after transpile:")
print(qc1_new)
print("Superposition circuit before transpile:")
print(qc2)
print("Superposition circuit after transpile:")
Ejemplo n.º 2
0
    def test_retrieve_job_error(self, provider):
        """Test retrieving an invalid job."""
        backends = provider.backends(simulator=False)
        backend = least_busy(backends)

        self.assertRaises(IBMQBackendError, backend.retrieve_job, 'BAD_JOB_ID')
    # running the job
    job_sim = execute([qc1, qc2], BasicAer.get_backend('qasm_simulator'))
    sim_result = job_sim.result()

    # Show the results
    print(sim_result.get_counts(qc1))
    print(sim_result.get_counts(qc2))

    # see a list of available remote backends
    print("\n(IBMQ Backends)")
    print(IBMQ.backends())

    # Compile and run on a real device backend
    try:
        # select least busy available device and execute.
        least_busy_device = least_busy(IBMQ.backends(simulator=False))
        print("Running on current least busy device: ", least_busy_device)

        # running the job
        job_exp = execute([qc1, qc2],
                          backend=least_busy_device,
                          shots=1024,
                          max_credits=10)

        job_monitor(job_exp)
        exp_result = job_exp.result()

        # Show the results
        print(exp_result.get_counts(qc1))
        print(exp_result.get_counts(qc2))
    except:
Ejemplo n.º 4
0
 def test_filter_least_busy(self, qe_token, qe_url):
     """Test filtering by least busy function"""
     IBMQ.enable_account(qe_token, qe_url)
     backends = IBMQ.backends()
     filtered_backends = least_busy(backends)
     self.assertTrue(filtered_backends)
simulator = Aer.get_backend('qasm_simulator')

# Execute and get counts
result = execute(circ, simulator,
                 shots=simulator.configuration().max_shots).result()
counts = result.get_counts(circ)
display(
    plot_histogram(counts,
                   title='Simulated counts for ' + str(n_gates) +
                   ' SWAP gates.'))
print("Simulated SWAP counts:", counts)
input("Press enter to run on an IBM Q backend...\n")

# Import the least busy backend
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(operational=True, simulator=False))
print("Least busy backend:", backend)

# Execute and get counts
job = execute(circ, backend, shots=backend.configuration().max_shots)
job_monitor(job)
nisq_result = job.result()
nisq_counts = nisq_result.get_counts(circ)
print("NISQ SWAP counts:", nisq_counts)
display(
    plot_histogram(nisq_counts,
                   title='Counts for ' + str(n_gates) + ' SWAP gates on ' +
                   str(backend)))
input("Press enter to transpile the circuit...\n")

# Comparing the circuit with the transpiled circuit
circuit.h(1)
circuit.cx(1,2)
circuit.barrier() 

circuit.cx(0,1)
circuit.h(0)
circuit.barrier() 

circuit.cx(1, 2)
circuit.cz(0, 2)
circuit.barrier() 

circuit.measure([0, 1, 2], [0, 1, 2]) 
print(circuit)

backend1 = Aer.get_backend('qasm_simulator')
job1 = execute(circuit, backend=backend1, shots=1000)
result1 = job1.result()
measurement1 = result1.get_counts(circuit)
plot_histogram(measurement1)

IBMQ.save_account('bc0221c2c435408a718744a0e3388325cd4241375e15beefb8909a759a28201db7c6a425e8d07e09e54105e373aceccb175fa8eb46700b4db88ac50dbdc6fa84')
provider = IBMQ.load_account()

backend2 = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True))
job2 = execute(circuit, backend=backend2, shots=1000)
result2 = job2.result()
measurement2 = result2.get_counts(circuit)
plot_histogram(measurement2)

plt.show()
counts = result_sim.get_counts(qc)
print(counts)

#Run on IBMQ
from qiskit import IBMQ

IBMQ.load_accounts()

print("Available backends:")
IBMQ.backends()

from qiskit.providers.ibmq import least_busy

large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration(
).n_qubits > 4 and not x.configuration().simulator)
backend = least_busy(large_enough_devices)
print("The best backend is " + backend.name())

#To run the circuit on the backend

from qiskit.tools.monitor import job_monitor
shots = 1024  # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3  # Maximum number of credits to spend on executions.

job_exp = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)

result_exp = job_exp.result()

counts_exp = result_exp.get_counts(qc)
Ejemplo n.º 8
0
def main(run_mode):
    # graph of city coordinates
    cities = np.array([[0, 0], [0, 1]])  # coordinates of the cities
    num_cities = len(cities)
    num_qubits = num_cities ** 2

    # algorithm properties
    p = 2  # number of time steps
    beta = np.random.uniform(0, np.pi * 2, p)
    gamma = np.random.uniform(0, np.pi * 2, p)

    # create matrix of distances between cities
    distance_mat = tsp.calc_distance(cities).w  # note that this method does integer distances

    # create mixing Hamiltonian. A city may or may not be visited in a timestep
    mixing_hamiltonian = reduce(lambda x, y: x + y,
                                [pauli_x(i, 1, num_qubits) for i in range(num_qubits)])

    # penalty_operators = create_weights_cost_operators(num_cities=num_cities, num_qubits=num_qubits,
    #                                                   dist_mat=distance_mat)
    penalty_operators = create_penalty_operators_for_bilocation(num_qubits=num_qubits, num_cities=num_cities,
                                                                distance_mat=distance_mat)
    penalty_operators += create_penalty_operators_for_repetition(num_qubits=num_qubits, num_cities=num_cities,
                                                                 distance_mat=distance_mat)

    print(penalty_operators)
    cost_hamiltonian = penalty_operators

    # circuit initial state vector. All states in equal superposition
    init_state_vect = [1 for i in range(2 ** num_qubits)]
    init_state = Custom(num_qubits, state_vector=init_state_vect)

    # initialize quantum circuit
    qr = QuantumRegister(num_qubits, name='q')
    init_circ = init_state.construct_circuit('circuit', qr)

    # find optimal beta and gamma
    evaluate = partial(neg_evaluate_circuit, qr=qr, p=p, m_H=mixing_hamiltonian, c_H=cost_hamiltonian,
                       init_circ=init_circ)
    print("Looking for optimal beta and gamma")
    # TODO: maybe we should use a different or faster method of finding the min? Super long even with two cities
    result = minimize(evaluate, np.concatenate([gamma, beta]), method='L-BFGS-B')
    # result = minimize(evaluate, np.concatenate([gamma, beta]))

    print(result)

    # now use the result of the gathered angles to find the answer
    circuit = create_circuit(qr, result['x'][:p], result['x'][p:], p, m_H=mixing_hamiltonian, c_H=cost_hamiltonian,
                             init_circ=init_circ)

    if run_mode == "IBM quantum":
        import secrets
        from qiskit import IBMQ
        from qiskit.providers.ibmq import least_busy

        provider = IBMQ.enable_account(secrets.IBM_TOKEN)
        large_enough_devices = provider.backends(filters=lambda x: x.configuration().n_qubits > 4 and
                                                                   not x.configuration().simulator)
        backend = least_busy(large_enough_devices)
        print("This will be running on the IBM device " + backend.name())

    else:
        print("Preparing to run on local simulator")
        backend = BasicAer.get_backend('statevector_simulator')

    job = execute(circuit, backend)
    state = np.asarray(job.result().get_statevector(circuit))
    print(list_to_easier_vis(np.absolute(state)))
Ejemplo n.º 9
0
qc.barrier()
# Measure all of the qubits in the standard basis
for i in range(num_qubits):
    qc.measure(q[i], c[i])

###############################################################
# Set up the API and execute the program.
###############################################################
try:
    IBMQ.load_accounts()
except:
    print("""WARNING: There's no connection with the API for remote backends.
             Have you initialized a file with your personal token?
             For now, there's only access to local simulator backends...""")

# First version: simulator
sim_backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, sim_backend, shots=1024)
result = job.result()
print('Qasm simulator : ')
print(result.get_counts(qc))

# Second version: real device
least_busy_device = least_busy(IBMQ.backends(simulator=False,
                                             filters=lambda x: x.configuration().n_qubits > 4))
print("Running on current least busy device: ", least_busy_device)
job = execute(qc, least_busy_device, shots=1024)
result = job.result()
print('Physical device (%s) : ' % least_busy_device)
print(result.get_counts(qc))
Ejemplo n.º 10
0
measure_Z.cx(qr[1], qr[3])
# We measure the circuit
measure_Z.measure(qr, cr)

# We add the two circuits to obtain a test result on how many possible
# combinations we have and the probabilities of each combination to be
# exist. These results are mearly theorethical and in a real quantum
# computer, the results may vary.
test_Z = qc + measure_Z

# We run the circuit in the local simulator. For more information on
# the simulators, please visit the Github or read the documentation.
# For more, visit https://qiskit.com
qk.IBMQ.load_accounts(hub=None)

backend = least_busy(
    qk.IBMQ.backends(filters=lambda x: not x.configuration().simulator))
qjob_2 = qk.compile(test_Z, backend, shots=1024)
print(qjob_2)
job_2 = backend.run(qjob_2)

print(job_2.status())

result_1 = job_2.result()

print(result_1.get_counts(test_Z))

plot_histogram(result_1.get_counts(test_Z)).savefig("test_Z.png")

# =====================================================================
# Another example where we use the same starting quantum circuit qc
Ejemplo n.º 11
0
import qiskit
from qiskit import Aer, QuantumRegister, ClassicalRegister, QuantumCircuit, IBMQ
from qiskit.providers import JobStatus
from qiskit.providers.ibmq import least_busy
from qiskit.exceptions import QiskitError
from qiskit.compiler import transpile, assemble
from Scripts.ibmq_account import account_key

IBMQ.enable_account(account_key)
q_device = IBMQ.backends(
    filters=lambda x: x.configuration().n_qubits == 5 and x.configuration(
    ).memory and not x.configuration().simulator)
real_backend = least_busy(q_device)
real_name = real_backend.name()

sim_backend = Aer.get_backend('qasm_simulator')


class CircuitBuilder():
    def __init__(self, register_size):
        self.size = register_size
        self.qr = QuantumRegister(register_size)
        self.cr = ClassicalRegister(register_size)
        self.circuit = QuantumCircuit(self.qr, self.cr)

    def add_operation(self, op, backend):
        op_name = op[0]
        if op_name == 'h':
            self.circuit.h(self.qr[op[1]])
        elif op_name == 'x':
            self.circuit.x(self.qr[op[1]])
Ejemplo n.º 12
0
# Apply the quantum gates
circuit.h(q[0])
circuit.cx(q[0], q[1])

# Finish off with the measurements
circuit.measure(q, c)

# Draw the circuit
circuit.draw(output="mpl")

# First, simulate the circuit
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1024)
result = job.result()

# Then, plot a histogram of the results
counts = result.get_counts(circuit)
plot_histogram(counts)

# Next, find the least-busy IBM device
lb_device = least_busy(IBMQ.backends())

# And run the circuit on that device
job = execute(circuit, backend=lb_device, shots=1024)
job_monitor(job)
result = job.result()

# Finally, plot a histogram of the results
counts = result.get_counts(circuit)
plot_histogram(counts)
Ejemplo n.º 13
0
# Authenticate for access to remote backends
try:
    provider = IBMQ.load_account()
except:
    print("""WARNING: No valid IBMQ credentials found on disk.
             You must store your credentials using IBMQ.save_account(token, url).
             For now, there's only access to local simulator backends...""")
    exit(0)

# see a list of available remote backends
ibmq_backends = provider.backends()

print("Remote backends: ", ibmq_backends)
# Compile and run the Quantum Program on a real device backend
# select those with at least 2 qubits
try:
    least_busy_device = least_busy(
        provider.backends(filters=lambda x: x.configuration().n_qubits >= 2,
                          simulator=False))
except:
    print("All devices are currently unavailable.")

print("Running on current least busy device: ", least_busy_device)

#running the job
job_exp = execute(qc, least_busy_device, shots=1024, max_credits=10)
result_exp = job_exp.result()

# Show the results
print('Counts: ', result_exp.get_counts(qc))
Ejemplo n.º 14
0
def leastBusy(minQubits, provider):
    large_enough_devices = provider.backends(filters=lambda x: x.configuration(
    ).n_qubits > minQubits and not x.configuration().simulator)
    leastBusybackend = least_busy(large_enough_devices)
    return leastBusybackend
Ejemplo n.º 15
0
        state = key
    print("The Quantum 8-ball says:")
    if state == '000':
        print('It is certain.')
    elif state == '001':
        print('Without a doubt.')
    elif state == '010':
        print('Yes - deinitely.')
    elif state == '011':
        print('Most likely.')
    elif state == '100':
        print("Don't count on it.")
    elif state == '101':
        print('My reply is no.')
    elif state == '110':
        print('Very doubtful.')
    else:
        print('Concentrate and ask again.')


# Execute the job on the simulator.
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1)
result = job.result().get_counts(qc)
answer(result)

# Execute the program on a real quantum computer.
backend = least_busy(IBMQ.backends(simulator=False))
print("Running on", backend.name())
job = execute(qc, backend, shots=1)
result = job.result().get_counts(qc)
answer(result)
Ejemplo n.º 16
0
    for i in range(n):
        prog.measure(input_qubit[i], classical[i])


    return prog



if __name__ == '__main__':
    a = "111"
    b = "0"
    f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)
    prog = make_circuit(4,f)
    IBMQ.load_account() 
    provider = IBMQ.get_provider(hub='ibm-q') 
    provider.backends()
    backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))
    sample_shot =8000

    info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()
    backend = FakeVigo()
    circuit1 = transpile(prog,backend,optimization_level=2)

    writefile = open("../data/startQiskit_QC2686.csv","w")
    print(info,file=writefile)
    print("results end", file=writefile)
    print(circuit1.__len__(),file=writefile)
    print(circuit1,file=writefile)
    writefile.close()
Ejemplo n.º 17
0
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from math import pi,sqrt
import numpy as np
from matplotlib import cm
import matplotlib.pyplot as plt


import qiskit
qiskit.__qiskit_version__
# use simulator to learn more about entangled quantum states where possible
sim_backend = BasicAer.get_backend('qasm_simulator')
sim_shots = 8192
# use device to test entanglement
device_shots = 1024
device_backend = least_busy(IBMQ.get_provider().backends(operational=True,simulator=False))
print(the backend is " + device_backend.name())


# Creating registers
q = QuantumRegister(2)
c = ClassicalRegister(2)
# quantum circuit to make an entangled bell state
bell = QuantumCircuit(q, c)
bell.h(q[0])
bell.cx(q[0], q[1])
# quantum circuit to measure q in the Z basis
measureZZ = QuantumCircuit(q, c) 
measureZZ.measure(q[0], c[0]) 
measureZZ.measure(q[1], c[1]) 
bellZZ = bell+measureZZ