def qc_approx_sim(x, t1, t2): theta1 = x - t1; theta2 = x - t2; q = QuantumRegister(2, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q, c) qc.h( q[0] ) qc.h( q[1] ) qc.u3(t1, 0.0, 0.0, q[0]); qc.u3(t2, 0.0, 0.0, q[1]); qc.barrier( q ) #qc.measure(q,c) qc.measure( q[0], c[0] ) qc.measure( q[1], c[1] ) job = execute(qc, backend, shots=1024) rslt = job.result() #counts = rslt.get_counts(qc) #print(counts) outputstate = rslt.get_statevector( qc, decimals=13 ) #print(outputstate) qval = outputstate; return qval;
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)
def get_rho(self): # Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. bases = ['ZZ','ZX','XZ','XX'] results = {} for basis in bases: temp_qc = copy.deepcopy(self.qc) for j in range(2): if basis[j]=='X': temp_qc.h(self.qr[j]) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) job = execute(temp_qc, backend=self.backend, shots=self.shots) results[basis] = job.result().get_counts() for string in results[basis]: results[basis][string] = results[basis][string]/self.shots prob = {} # prob of expectation value -1 for single qubit observables for j in range(2): for p in ['X','Z']: pauli = {} for pp in 'IXZ': pauli[pp] = (j==1)*pp + p + (j==0)*pp prob[pauli['I']] = 0 for basis in [pauli['X'],pauli['Z']]: for string in results[basis]: if string[(j+1)%2]=='1': prob[pauli['I']] += results[basis][string]/2 # prob of expectation value -1 for two qubit observables for basis in ['ZZ','ZX','XZ','XX']: prob[basis] = 0 for string in results[basis]: if string[0]!=string[1]: prob[basis] += results[basis][string] for pauli in prob: self.rho[pauli] = 1-2*prob[pauli]
# RIipetiamo oracolo e diffusione il numero calcolato di volte for _ in range(number_of_iterations): circuit += oracle circuit += diffusion return circuit # Applichiamo grover circuit = construct_grover(circuit, oracle, [register], qbits, ancillas) # Inizzializziamo il backend del simulatore backend_sim = q.BasicAer.get_backend('qasm_simulator') # Setuppiamo il circuito per simularlo # Inizzializziamo un registro di qbit classici # I bit normali servono come registi dove il simulatore andra' a salvare il risultato dell'esperimento cbits = q.ClassicalRegister(n_of_qbits, 'classical_values') # Ed aggiungiamoli al circuito circuit.add_register(cbits) circuit.measure(register, cbits) # Otteniamo i risultati organizzati come frequenza degli stati misurati results = q.execute(circuit, backend_sim, shots=int(sys.argv[2])).result().get_counts(circuit) # Stampiamo a schermo il risultato print(results)
# Create a Quantum Circuit qc = QuantumCircuit(q, c) # Add a H gate on qubit 0, putting this qubit in superposition. qc.h(q[0]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. qc.cx(q[0], q[1]) # Add a Measure gate to see the state. qc.measure(q, c) # See a list of available local simulators print("Local backends: ", available_backends({'local': True})) # Compile and run the Quantum circuit on a simulator backend job_sim = execute(qc, "local_qasm_simulator") sim_result = job_sim.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(qc)) # see a list of available remote backends remote_backends = available_backends({'local': False, 'simulator': False}) print("Remote backends: ", remote_backends) # Compile and run the Quantum Program on a real device backend try: best_device = lowest_pending_jobs() print("Running on current least busy device: ", best_device)
qc1 = QuantumCircuit(qubit_reg, clbit_reg) qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg) qc2.h(qubit_reg) qc2.measure(qubit_reg, clbit_reg) # setting up the backend print("(Local Backends)") print(available_backends({'local': True})) # runing the job job_sim = execute([qc1, qc2], "local_qasm_simulator") sim_result = job_sim.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) # see a list of available remote backends print("\n(Remote Backends)") print(available_backends({'local': False})) # Compile and run on a real device backend try: # select least busy available device and execute. best_device = lowest_pending_jobs()
prog.h(input_qubit[2]) # number=55 prog.h(input_qubit[2]) # number=25 prog.h(input_qubit[3]) # number=20 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog if __name__ == '__main__': key = "00000" f = lambda rep: str(int(rep == key)) prog = make_circuit(5, f) backend = BasicAer.get_backend('qasm_simulator') sample_shot = 7924 info = execute(prog, backend=backend, shots=sample_shot).result().get_counts() backend = FakeVigo() circuit1 = transpile(prog, backend, optimization_level=2) writefile = open("../data/startQiskit1692.csv", "w") print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import CompositeGate, available_backends, execute q = QuantumRegister(5, "qr") q2 = QuantumRegister(1, "qr") print(len(q2)) c = ClassicalRegister(5, "cr") qc = QuantumCircuit(q, c) qc.cry = cry qc.cnx = cnx qc.any_x = any_x qc.x_bus = x_bus qc.bus_or = bus_or #qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[-1]) qc.bus_or(qc,q[0],[q[1],q[2],q[3]],[q[4]]) qc.measure(q,c) job_sim = execute(qc, "local_qasm_simulator",shots=100) sim_result = job_sim.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(qc)) print(qc.qasm())
"""111 . x + 1""" a = "111" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) if __name__ == "__main__": n = 2 a = "11" b = "1" f = lambda rep: \ bitwise_xor(bitwise_dot(a, rep), b) prog = build_circuit(n, f) sample_shot = 4000 writefile = open("../data/startQiskit_Class183.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) backend = BasicAer.get_backend('statevector_simulator') circuit1 = transpile(prog, FakeYorktown()) circuit1.h(qubit=2) circuit1.x(qubit=3) info = execute(circuit1, backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
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]:
import QiskitConfig import qiskit as qk from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ qk.IBMQ.enable_account(QiskitConfig.ApiToken) ibmprocessor = qk.IBMQ.get_backend('ibmqx4') Qr1 = qk.QuantumRegister(1) Cr1 = qk.ClassicalRegister(1) Cir1 = qk.QuantumCircuit(Qr1, Cr1) Cir1.measure(Qr1, Cr1) Job = execute(Cir1, ibmprocessor) res = Job.result() print(res)
return prog if __name__ == '__main__': key = "00000" f = lambda rep: str(int(rep == key)) prog = make_circuit(5,f) backend = BasicAer.get_backend('statevector_simulator') sample_shot =7924 info = execute(prog, backend=backend).result().get_statevector() qubits = round(log2(len(info))) info = { np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3) for i in range(2 ** qubits) } backend = FakeVigo() circuit1 = transpile(prog,backend,optimization_level=2) writefile = open("../data/startQiskit_Class1370.csv","w") print(info,file=writefile) print("results end", file=writefile) print(circuit1.depth(),file=writefile) print(circuit1,file=writefile) writefile.close()
except Exception as e: print(e) qx_config = { "APIToken": "b2b686d61de1af50d8ae7cb4fe85fb8dc61279a888b47e290ffe2f1f87d692a7dc65ab295ec957b7c54a24497c2c5138a72f6dbbf93d96d0db8e1018c8418563", "url":"https://quantumexperience.ng.bluemix.net/api" } #set api register(qx_config['APIToken'], qx_config['url']) #Plot dat shit backend = "ibmq_qasm_simulator" shots_sim = 128 job_sim = execute(qc, backend, shots = shots_sim) stats_sim = job_sim.result().get_counts() plot_histogram(stats_sim) #Grphic import matplotlib.pyplot as plt #%matplotlib inline plt.rc('font', family = 'monospace') def plot_smiley (stats, shots): for bitString in stats: char = chr(int(bitString[0:8], 2)) #convert leftmost 8 bits into ascii character char +=chr(int(bitString[8:16], 2)) #convert next 8 bits into ascii and append to first character prob = stats[bitString]/shots
""" Example on how to use: load_qasm_file If you want to use your local cloned repository intead of the one installed via pypi, you have to run like this: examples/python$ PYTHONPATH=$PYTHONPATH:../.. python load_qasm.py """ from qiskit.wrapper import load_qasm_file from qiskit import QISKitError, available_backends, execute try: qc = load_qasm_file("../qasm/entangled_registers.qasm") # See a list of available local simulators print("Local backends: ", available_backends({'local': True})) # Compile and run the Quantum circuit on a local simulator backend job_sim = execute(qc, "local_qasm_simulator") sim_result = job_sim.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(qc)) except QISKitError as ex: print('There was an internal QISKit error. Error = {}'.format(ex))
def eval_op(op): from qiskit import execute backend = BasicAer.get_backend('qasm_simulator') evaluation_circuits = op.construct_evaluation_circuit(qc, False) job = execute(evaluation_circuits, backend, shots=1024) return op.evaluate_with_result(job.result(), False)
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()
# ibmq_qasm_simulator """ Selecting backend of available devices. """ print("\nGetting backend ...") backend_ibmq = IBMQ.get_backend('ibmqx4') """ ####### Compile and run the Quantum circuit on a device backend ######### """ print("\nExecuting ...") job_ibmq = execute(qc, backend=backend_ibmq, shots=1024) # print("\nGo to job monitor") # job_monitor(job_ibmq) # print("\nLeft of the job monitor") """ Getting execution information """ print_job_execution_information(job_ibmq) """ Getting results
""" Select how many times the circuit runs""" number_shots = int(input('Number of times to run the circuit: ')) if number_shots < 1: print('Please run the circuit at least one time...') exit() if number_shots > 1: print('\nIf the circuit takes too long to run, consider running it less times\n') """ Print info to user """ print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots, N, a)) """ Simulate the created Quantum Circuit """ # simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'), shots=number_shots) simulation = execute(circuit, backend=IBMQ.get_backend('ibmq_qasm_simulator'), shots=number_shots) """ to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """ """ to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """ """ Get the results of the simulation in proper structure """ sim_result = simulation.result() counts_result = sim_result.get_counts(circuit) """ Print info to user from the simulation results """ print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format( number_shots)) i = 0 while i < len(counts_result): print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i], list(sim_result.get_counts().values())[i], number_shots))
'f3ab4eb0aa3946185519e07e636619e2e6e2a96f01a2dee60a0a727b354bba7e5a2ade73a410276f3f0c7ae95a260ac0ce4b742d779f2d18e9f020745f0d1e95' ) # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0, 1], [0, 1]) # Execute the circuit on the qasm simulator job = execute(circuit, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(circuit) print("\nTotal count for 00 and 11 are:", counts) # Draw the circuit circuit.draw()
# send qc.cx(alice, ep) qc.h(alice) qc.measure(alice, alice_c) qc.measure(ep, ep_c) qc.barrier() # receive qc.x(bob).c_if(ep_c, 1) qc.z(bob).c_if(alice_c, 1) # verify qc.h(bob) qc.rz(math.radians(-45), bob) qc.h(bob) qc.measure(bob, bob_c) ## That's the program. Everything below runs and draws it. backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() counts = result.get_counts(qc) print('counts:', counts) outputstate = result.get_statevector(qc, decimals=3) print(outputstate) qc.draw() # draw the circuit
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)])