def ask_for_device ():
    
    d = input("Do you want to play on the real device? (y/n)\n").upper()
    if (d=="Y"):
        device = IBMQ.get_backend('ibmq_5_tenerife') # if real, we use ibmqx4
    else:
        device = Aer.get_backend('qasm_simulator') # otherwise, we use a simulator
        
    return device
 def compute_winner(self):
     """Find overall game winner, by finding winners of each outcome"""
     self.c.size = self.q.size #Make them the same
     self.qc.measure(self.q, self.c) #Measure
     backend = Aer.get_backend('qasm_simulator')
     job_sim = execute(self.qc, backend=backend, shots=100)
     sim_result = job_sim.result()
     print("simulation: ", sim_result)
     print(sim_result.get_counts(self.qc))
     self.counts = sim_result.get_counts(self.qc)
     for count in self.counts: #Takes key names
         c = list(count)[:-1] #splits key '1011' => ['1','0','1','1']
         c = c[::-1] #invert it so it goes 0 up...
         #Ignore the last bit since I dont know how to get rid of it
         #It is zero always.
         #The reason it is included is that I create a quantum register and
         #then start adding operations, quantum registers need at least one bit.
         counter = 0
         weight = self.counts[count]
         empty = np.zeros((self.x,self.y),dtype=str)
         for m in self.moves:
             if m.player == 0:
                 char = 'x'
             elif m.player==1:
                 char = 'o'
             result = []
             if m.q1:
                 result.append(c[counter])
                 counter+=1
             if m.q2:
                 result.append(c[counter])
                 counter+=1
             #print(result)
             if len(result) == len(m.indices):
                 #print(m)
                 if result[0]=='1':
                     empty[m.indices[0][0],m.indices[0][1]] = char
                 if len(result)>1:
                     if result[1]=='1':
                         if result[0]=='1':
                             print('problem! a move appeard in two places.')
                             print(m)
                         empty[m.indices[1][0],m.indices[1][1]] = char
             elif not result: #Then it was a classcal move
                 empty[m.indices[0][0],m.indices[0][1]] = char
         xscore,oscore=self.winners(empty)
         print('X wins: '+str(xscore))
         print('O wins: '+str(oscore))
         print('Shots: '+str(weight))
         print(empty)
Exemplo n.º 3
0
for input in all_inputs:
    qreg3 = QuantumRegister(2)  # quantum register with 2 qubits
    creg3 = ClassicalRegister(2)  # classical register with 2 bits
    mycircuit3 = QuantumCircuit(
        qreg3, creg3)  # quantum circuit with quantum and classical registers

    #initialize the inputs
    if input[0] == '1':
        mycircuit3.x(qreg3[0])  # set the value of the first qubit to |1>
    if input[1] == '1':
        mycircuit3.x(qreg3[1])  # set the value of the second qubit to |1>

    # apply cx(first-qubit,second-qubit)
    mycircuit3.cx(qreg3[0], qreg3[1])
    # apply cx(second-qubit,first-qubit)
    mycircuit3.cx(qreg3[1], qreg3[0])
    # apply cx(first-qubit,second-qubit)
    mycircuit3.cx(qreg3[0], qreg3[1])

    mycircuit3.measure(qreg3, creg3)

    # execute the circuit 100 times in the local simulator
    job = execute(mycircuit3, Aer.get_backend('qasm_simulator'), shots=100)
    counts = job.result().get_counts(mycircuit3)
    for outcome in counts:  # print the reverse of the outcomes
        reverse_outcome = ''
        for i in outcome:
            reverse_outcome = i + reverse_outcome
        print("our input is", input, ": ", reverse_outcome, "is observed",
              counts[outcome], "times")
Exemplo n.º 4
0
    w[u, v] = round(d['weight'], 2)
    w[v, u] = round(d['weight'], 2)
print(w)

# Mapping to the Ising problem
qubitOp, offset = max_cut.get_max_cut_qubitops(w)
algo_input = EnergyInput(qubitOp)

# run quantum algorithm with shots
seed = 10598

spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)

backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend,
                                   shots=1024,
                                   seed_simulator=seed,
                                   seed_transpiler=seed)

result = vqe.run(quantum_instance)
"""declarative approach, update the param from the previous cell.
params['backend']['provider'] = 'qiskit.BasicAer'
params['backend']['name'] = 'qasm_simulator'
params['backend']['shots'] = 1024
result = run_algorithm(params, algo_input)
"""

x = max_cut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
Exemplo n.º 5
0
circuito_11 = QuantumCircuit(1,1) # 1 alambre cuantico (qubits) un alambre clásico
circuito_11.measure(0,0) # 0 se refiere al índice


# In[7]:


# Dibujamos el circuito
circuito_11.draw(output='mpl')


# In[8]:


#Ejecuto la simulación
simulador = Aer.get_backend('qasm_simulator')
ejecucion = execute(circuito_11, backend=simulador, shots=1)
resultado = ejecucion.result()
conteos = resultado.get_counts()
print(conteos)


# In[9]:


plot_histogram(conteos)


# **1.2. Experimento:** Cuando un qubit esta inicializado en |0> el resultado de la medición debe ser, en teoria, siempre |0>(con probabilidad del 100%). 1000 shots simulado

# In[10]:
Exemplo n.º 6
0
    if (len(x) != len(G.nodes())):
        return np.nan

    C = 0
    for index in E:
        e1 = index[0]
        e2 = index[1]

        w = G[e1][e2]['weight']
        C = C + w * x[e1] * (1 - x[e2]) + w * x[e2] * (1 - x[e1])

    return C


# run on local simulator
backend = Aer.get_backend("qasm_simulator")
shots = 10000

simulate = execute(QAOA, backend=backend, shots=shots)
QAOA_results = simulate.result()

plot_histogram(QAOA_results.get_counts(), figsize=(8, 6), bar_labels=False)

# Evaluate the data from the simulator
counts = QAOA_results.get_counts()

avr_C = 0
max_C = [0, 0]
hist = {}

for k in range(len(G.edges()) + 1):
Exemplo n.º 7
0
def run_circuit(
    circuit,
    measure=True,
    hm_trials=1_000,
    backend=None,
    reverse=False,
    normalize=True,
    fill_zero_counts=True,
    order=True,
    draw=False,
    draw_optimized=False,
    display_job_status=False,
):

    if not backend:
        backend = Aer.get_backend('qasm_simulator')

    elif type(backend) == str:

        if 'state' in backend:
            backend = Aer.get_backend('statevector_simulator')
            state_vector = execute(circuit, backend).result().get_statevector()
            return state_vector

        else:
            try:
                from warnings import filterwarnings
                filterwarnings("ignore")
                IBMQ.load_account()
                provider = IBMQ.get_provider("ibm-q")
                backend = provider.get_backend(backend)
Exemplo n.º 8
0
 def test_qobj_to_circuits_single(self):
     """Check that qobj_to_circuits's result matches the qobj ini."""
     backend = Aer.get_backend('qasm_simulator_py')
     qobj_in = compile(self.circuit, backend, skip_transpiler=True)
     out_circuit = qiskit.wrapper.qobj_to_circuits(qobj_in)
     self.assertEqual(out_circuit[0].qasm(), self.circuit.qasm())
'''
# Useful additional packages
import matplotlib.pyplot as plt
# %matplotlib inline
import numpy as np
from numpy import pi

from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import Aer

# print("Backends list")
# print(Aer.backends())

backend = Aer.get_backend('unitary_simulator')

q = QuantumRegister(4)
# q[4]
# q[3]
# q[2]
# q[1]
# q[0]

qc = QuantumCircuit(q)

# Decomposition of next matrix
# [[1, 0, 0, 0],
#  [0,-1, 0, 0],
#  [0, 0, 1, 0],
#  [0, 0, 0, 1]]
Exemplo n.º 10
0
c = ClassicalRegister(number_of_qubit)

# define our quantum circuit
qc = QuantumCircuit(q, c)

# apply h-gate to all qubits
for i in range(number_of_qubit):
    qc.h(q[i])

# apply z-gate to randomly picked qubits
for i in range(number_of_qubit):
    if randrange(2) == 0:  # the qubit with index i is picked to apply z-gate
        qc.z(q[i])

# apply h-gate to all qubits
for i in range(number_of_qubit):
    qc.h(q[i])

qc.barrier()

# measure all qubits
qc.measure(q, c)

# draw the circuit
qc.draw(output='mpl')

# execute the circuit 1000 times in the local simulator
job = execute(qc, Aer.get_backend('qasm_simulator'), shots=1000)
counts = job.result().get_counts(qc)
print(counts)
Exemplo n.º 11
0
Arquivo: qmnist.py Projeto: y-yu/qwgc
This is archive version of previous qmnist project.
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import execute, Aer
from numpy import pi
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from tqdm import trange

import numpy as np
import random
import copy
import umap.umap_ as umap

THETA_MIN, THETA_MAX = -pi, pi
BACKEND = Aer.get_backend('qasm_simulator')
SHOTS = 2048


class QMNIST:
    """
    QMMIST is for quantum classifier for MNIST

    This
    """
    def __init__(self,
                 encoder,
                 alpha=0.0001,
                 n_particle=20,
                 iteration=50,
                 w=0.8,
Exemplo n.º 12
0
n=2 # Set the number of qubits

#initialise a quantum circuit with (n) qubits
grover_circuit = QuantumCircuit(n)

def initialise_state(qc, qubits):
    for q in qubits:
        qc.h(q)
    return qc

grover_circuit = initialise_state(grover_circuit, [0,1])

#apply the oracle
grover_circuit.cz(0,1)

#apply Grover's Diffusion Operator
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])

# Plot Circuit
diagram = grover_circuit.draw(output='mpl')  # output='mpl', output='latex', scale=0.5
show_figure(diagram)

# SIMULATION
sim = Aer.get_backend('statevector_simulator')
job = execute(grover_circuit, sim)
psi = job.result().get_statevector()
Exemplo n.º 13
0
def getstatevector(circ):
    bkend = Aer.get_backend('statevector_simulator')
    job = execute(circ, bkend)
    result = job.result()
    return result.get_statevector()
Exemplo n.º 14
0
def printcircuitunitary(circ):
    bkend = Aer.get_backend('unitary_simulator')
    job = execute(circ, bkend)
    result = job.result()
    print(result.get_unitary(circ, decimals=3))
Exemplo n.º 15
0
 def setUp(self) -> None:
     backend = Aer.get_backend('qasm_simulator')
     self.instance = QuantumInstance(backend, shots=64)
Exemplo n.º 16
0
def backend_configuration(backend_to_run="qasm_simulator"):
    backend = Aer.get_backend(backend_to_run)
    return backend.configuration().as_dict()
Exemplo n.º 17
0
import numpy as np
from numpy.linalg import eigh, matrix_rank
from scipy.linalg import logm
from math import log
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, QuantumRegister, execute, Aer, ClassicalRegister
from copy import deepcopy
import json

import TensorNetwork
import hamiltonians
import Entangler

sv_backend = Aer.get_backend("statevector_simulator")


def get_state(circ):
    job = execute(circ, sv_backend)
    result = job.result()
    state = result.get_statevector(circ)
    return state


def make_hadamard_test_circuit(circ: QuantumCircuit, q_anc: QuantumRegister,
                               c_anc: ClassicalRegister) -> QuantumCircuit:
    """Takes a circuit, makes it a controlled circuit, and creates a
        Hadamard test circuit of all this stuff"""
    c_circ = make_control_circuit(circ, q_anc, c_anc)
    had_circ = QuantumCircuit()
    for reg in circ.qregs:
        had_circ.add_register(reg)
Exemplo n.º 18
0
theta = angle_between_two_states(u,[1,0])

all_visited_quantum_states =[]


qreg3 = QuantumRegister(1) # quantum register with 1 qubit
creg3 = ClassicalRegister(1) # classical register with 1 bit
mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers


# set the qubit to |u> by rotating it by theta
mycircuit3.ry(2*theta,qreg3[0])

# read and store the current quantum state
current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3)
[x,y] = [current_state[0].real,current_state[1].real]
all_visited_quantum_states.append([x,y,'u'])


# three iterations
for i in range(3): # 4,5,6,7,8,9,10
    # the first reflection
    theta = angle_between_two_states([x,y],[1,0])
    mycircuit3.ry(2*(-2*theta),qreg3[0])

    # read and store the current quantum state
    current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3)
    [x,y] = [current_state[0].real,current_state[1].real]
    all_visited_quantum_states.append([x,y,'r'+str(i+1)])