repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_hinton qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3 , 0) qc.rx(np.pi/5, 1) state = DensityMatrix(qc) plot_state_hinton(state, title="New Hinton Plot")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/drobiu/quantum-project
drobiu
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, BasicAer, execute from qiskit.circuit.library import XGate from src.arithmetic.comparator import comparator from src.arithmetic.counter import mincount, count from src.logic.oracles import oracle_a, oracle_b from src.logic.query import query def find_used_colours(n_positions, n_colors, secret_string): n = n_positions k = n_colors s = secret_string a = QuantumRegister(3) b = QuantumRegister(4) c = QuantumRegister(8) d = QuantumRegister(3) e = QuantumRegister(3) f = QuantumRegister(1) g = QuantumRegister(1) h = QuantumRegister(1) cl = ClassicalRegister(4) circuit = QuantumCircuit(a, b, c, d, e, f, g, h, cl) # Step 1 circuit = oracle_a(circuit, c, a, s) # qc.barrier() # Step 2 circuit.h(b[:]) # qc.barrier() # Step 3 circuit = query(circuit, b, c, s) # qc.barrier() # Step 4 circuit = oracle_b(circuit, c, d, s) # qc.barrier() # Step 5 circuit.x(e[-1]) circuit = mincount(circuit, e, b) # qc.barrier() # Step 6 circuit = comparator(circuit, a, e, f, 3) # qc.barrier() # Step 7 circuit.x(g) circuit.x(a[:]) multiply_controlled_x(circuit, a, g) circuit.x(a[:]) # qc.barrier() # Step 8 circuit.x(d[0], h) multiply_controlled_x(circuit, [e[0], f, g], h) circuit.x(f) multiply_controlled_x(circuit, [e[0], f, g], h) multiply_controlled_x(circuit, [b[0], f, g], h) circuit.x(f) # qc.barrier() # Step 9 circuit.z(h) # qc.barrier() # Step 10 circuit.x(f) multiply_controlled_x(circuit, [b[0], f, g], h) multiply_controlled_x(circuit, [e[0], f, g], h) circuit.x(f) multiply_controlled_x(circuit, [e[0], f, g], h) circuit.cx(d[0], h) circuit.x(a[:]) circuit.cx(a[:], g) circuit.x(a[:]) circuit.x(g) circuit = comparator(circuit, a, e, f, 3) circuit = count(circuit, e, b) circuit.x(e[2]) circuit = oracle_b(circuit, c, d, s, do_inverse=True) circuit = query(circuit, b, c, s) # Step 11 circuit.h(b[:]) # qc.barrier() # Step 12 circuit.measure(b[:], cl[:]) # circuit.draw(output='text') print("\nResult from the local Qiskit simulator backend:\n") backend = BasicAer.get_backend("qasm_simulator") job = execute(circuit, backend=backend, shots=1) result = job.result() print(result.get_counts(circuit)) return circuit def multiply_controlled_x(circuit, control, qubit): num_c = len(control) cx = XGate().control(num_c) circuit.append(cx, [*control, qubit]) if __name__ == "__main__": qc = find_used_colours(4, 4, [2, 2, 2, 2])
https://github.com/xtophe388/QISKIT
xtophe388
# checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram #import Qconfig # import basic plotting tools from qiskit.tools.visualization import plot_histogram from qiskit.tools.qcvv.tomography import marginal_counts # create a QuantumProgram object instance. q_program = QuantumProgram() #q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url # backend #backend = 'ibmqx2' backend = 'local_qasm_simulator' # quantum plain addition algorithm for 1-qubit numbers def addition_1bit(circuit, q): circuit.h(q[2]) circuit.cx(q[1], q[2]) circuit.tdg(q[2]) circuit.cx(q[0], q[2]) circuit.t(q[2]) circuit.cx(q[1], q[2]) circuit.tdg(q[2]) circuit.cx(q[0], q[2]) circuit.t(q[2]) circuit.h(q[2]) circuit.t(q[1]) circuit.cx(q[0], q[1]) circuit.t(q[0]) circuit.tdg(q[1]) # n-qubit number input state def number_state(circuit, q, a, b): if a == 1: circuit.x(q[0]) # q[0] contains the value of a if b == 1: circuit.x(q[1]) # q[1] contain the value of b # we define the values (0 or 1) a = 1 b = 1 # one single quantum register which contains 'a' (1 qubit) and 'b' (2 qubits) q = q_program.create_quantum_register("q", 3) # 3 qubits # clasical register c = q_program.create_classical_register("cr", 2) # 2 bits # quantum circuit involving the quantum register and the classical register add1bit_circuit = q_program.create_circuit("add", [q] ,[c]) # create the state containing a and b number_state(add1bit_circuit, q, a, b) # addition addition_1bit(add1bit_circuit, q) # measurements to see the result, which has been written in b (q[1]q[2]) add1bit_circuit.measure(q[1], c[0]) add1bit_circuit.measure(q[2], c[1]) # compile and execute the quantum program in the backend result = q_program.execute(["add"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=999999) # show the results print(result) print(result.get_data("add")) counts = marginal_counts(result.get_counts("add"), [0, 1]) plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module but running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # we define the values a = 9 b = 14 # computing the number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(b)) if n2 > n: n = n2 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # b qubits # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register addnbit_circuit = q_program.create_circuit("add", [qa, qb],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum registers and the classical register addnbit_circuit = q_program.create_circuit("add", [qa, qb, qcar],[c]) # create the state containing a number_state(addnbit_circuit, qa, a, n) # create the state containing b number_state(addnbit_circuit, qb, b, n) # addition addition_nbit(addnbit_circuit, qa, qb, qcar, n) # measurements to see the result for i in range(n+1): addnbit_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["add"], backend=backend, shots=1024, timeout=999999) # show the results. print(result) print(result.get_data("add")) counts = result.get_counts("add") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) def summation_inv(circuit, q0, q1, q2): "summation module running backwards" circuit.cx(q0, q2) circuit.cx(q1, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # quantum plain substraction algorithm for n-qubit numbers def subs_nbit(circuit, qa, qb, qcar, n): "same circuit as the plain addition but going backwards" if n == 1: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qb[1]) else: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) summation_inv(circuit, qcar[0], qa[1], qb[1]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2]) circuit.cx(qa[n-1], qb[n-1]) carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) for i in range(n-2, 0, -1): carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) def cond_toffoli(circuit, qcond, q1, q2, q3): "toffoli gate conditioned by an external qubit" circuit.h(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.h(q3) circuit.t(q2) circuit.ccx(qcond, q1, q2) circuit.t(q1) circuit.tdg(q2) circuit.ccx(qcond, q1, q2) def cond_carry(circuit, q0, q1, q2, q3, qcond): "conditional carry module" cond_toffoli(circuit, qcond, q1, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q0, q2, q3) def cond_carry_inv(circuit, q0, q1, q2, q3, qcond): "conditional carry module running backwards" cond_toffoli(circuit, qcond, q0, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q1, q2, q3) def cond_summation(circuit, q0, q1, q2, qcond): "conditional summation module" circuit.ccx(qcond, q1, q2) circuit.ccx(qcond, q0, q2) def cond_summation_inv(circuit, q0, q1, q2, qcond): "conditional summation module running backwards" circuit.ccx(qcond, q0, q2) circuit.ccx(qcond, q1, q2) # quantum conditional plain addition algorithm for n-qubit numbers def cond_addition_nbit(circuit, qa, qb, qcar, qcond, n): "plain addition algorithm conditioned by an external qubit" if n == 1: cond_toffoli(circuit, qcond[0], qa[0], qb[0], qb[1]) circuit.ccx(qcond[0], qa[0], qb[0]) else: cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) circuit.ccx(qcond[0], qa[0], qb[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond[0]) cond_carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond[0]) circuit.ccx(qcond[0], qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): cond_summation(circuit, qcar[i-1], qa[i], qb[i], qcond[0]) cond_carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1], qcond[0]) cond_summation(circuit, qcar[0], qa[1], qb[1], qcond[0]) circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) circuit.ccx(qcond[0], qa[0], qb[0]) # quantum conditional plain substraction algorithm for n-qubit numbers def cond_subs_nbit(circuit, qa, qb, qcar, qcond, n): "same circuit as the conditional plain addition but going backwards" if n == 1: circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qb[1]) else: circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) circuit.ccx(qcond[0], qa[0], qb[0]) cond_summation_inv(circuit, qcar[0], qa[1], qb[1], qcond[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond[0]) cond_summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2], qcond[0]) circuit.ccx(qcond[0], qa[n-1], qb[n-1]) cond_carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond[0]) for i in range(n-2, 0, -1): cond_carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i], qcond[0]) circuit.ccx(qcond[0], qa[0], qb[0]) cond_toffoli(circuit, qcond[0], qa[0], qb[0], qcar[0]) # quantum modular addition algorithm for n-qubit numbers def mod_addition_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): addition_nbit(circuit, qa, qb, qcar, n) subs_nbit(circuit, qN, qb, qcar, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp[0]) circuit.x(qb[n]) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) addition_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp[0]) addition_nbit(circuit, qa, qb, qcar, n) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # we define the values a = 2 b = 3 N = 3 # computing number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(b)) n3 = len("{0:b}".format(N)) if n2 > n: n = n2 if n3 > n: n = n3 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # b qubits qN = q_program.create_quantum_register("qN", n+1) # N qubits qNtemp = q_program.create_quantum_register("qNtemp", n) # temporary N qubits qtemp = q_program.create_quantum_register("qtemp", 1) # temporary qubit # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register mod_add_circuit = q_program.create_circuit("mod_add", [qa, qb, qN, qNtemp, qtemp],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum registers and the classical register mod_add_circuit = q_program.create_circuit("mod_add", [qa, qb, qN, qcar, qNtemp, qtemp],[c]) # create the state containing 'a' number_state(mod_add_circuit, qa, a, n) # create the state containing 'b' number_state(mod_add_circuit, qb, b, n) # create the state containing 'N' number_state(mod_add_circuit, qN, N, n) # create the temporary state containing 'N' number_state(mod_add_circuit, qNtemp, N, n) # modular addition mod_addition_nbit(mod_add_circuit, qa, qb, qN, qNtemp, qcar, qtemp, n) # measurements to see the result for i in range(n+1): mod_add_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["mod_add"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=999999) # show the results. print(result) print(result.get_data("mod_add")) counts = result.get_counts("mod_add") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) def summation_inv(circuit, q0, q1, q2): "summation module running backwards" circuit.cx(q0, q2) circuit.cx(q1, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # quantum plain substraction algorithm for n-qubit numbers def subs_nbit(circuit, qa, qb, qcar, n): "same circuit as the addition but going backwards" if n == 1: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qb[1]) else: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) summation_inv(circuit, qcar[0], qa[1], qb[1]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2]) circuit.cx(qa[n-1], qb[n-1]) carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) for i in range(n-2, 0, -1): carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) def cond_toffoli(circuit, qcond, q1, q2, q3): "toffoli gate conditioned by an external qubit" circuit.h(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.h(q3) circuit.t(q2) circuit.ccx(qcond, q1, q2) circuit.t(q1) circuit.tdg(q2) circuit.ccx(qcond, q1, q2) def cond_carry(circuit, q0, q1, q2, q3, qcond): "conditional carry module" cond_toffoli(circuit, qcond, q1, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q0, q2, q3) def cond_carry_inv(circuit, q0, q1, q2, q3, qcond): "conditional carry module running backwards" cond_toffoli(circuit, qcond, q0, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q1, q2, q3) def cond_summation(circuit, q0, q1, q2, qcond): "conditional summation module" circuit.ccx(qcond, q1, q2) circuit.ccx(qcond, q0, q2) def cond_summation_inv(circuit, q0, q1, q2, qcond): "conditional summation module running backwards" circuit.ccx(qcond, q0, q2) circuit.ccx(qcond, q1, q2) # quantum conditional plain addition algorithm for n-qubit numbers def cond_addition_nbit(circuit, qa, qb, qcar, qcond, n): if n == 1: cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) circuit.ccx(qcond, qa[0], qb[0]) else: cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): cond_summation(circuit, qcar[i-1], qa[i], qb[i], qcond) cond_carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1], qcond) cond_summation(circuit, qcar[0], qa[1], qb[1], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) # quantum conditional plain substraction algorithm for n-qubit numbers def cond_subs_nbit(circuit, qa, qb, qcar, qcond, n): "same circuit as the conditional plain addition but going backwards" if n == 1: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) else: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) cond_summation_inv(circuit, qcar[0], qa[1], qb[1], qcond) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) cond_carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) for i in range(n-2, 0, -1): cond_carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) # quantum modular addition algorithm for n-qubit numbers def mod_addition_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): addition_nbit(circuit, qa, qb, qcar, n) subs_nbit(circuit, qN, qb, qcar, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp) circuit.x(qb[n]) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) addition_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp) addition_nbit(circuit, qa, qb, qcar, n) # quantum controlled modular multiplication algorithm for n-qubit numbers def cont_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, qX, qext, N, n): for i in range(n): for j in range(n): classical_mod = (2**(i+j))%N cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) mod_addition_nbit(circuit, qtempst, qb, qN, qNtemp, qcar, qtemp, n) cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) circuit.x(qext) cond_addition_nbit(circuit, qX, qb, qcar, qext, n) circuit.x(qext) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # n-qubit number input state, controlled by 2 control qubits def cond_number_state(circuit, q, x, ext, control1, control2, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: cond_toffoli(circuit, ext, control1, control2, q[i]) # we define the values a = 1 x = 1 N = 1 # computing number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(x)) n3 = len("{0:b}".format(N)) if n2 > n: n = n2 if n3 > n: n = n3 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # result register qN = q_program.create_quantum_register("qN", n+1) # N qubits qNtemp = q_program.create_quantum_register("qNtemp", n) # temporary N qubits qtemp = q_program.create_quantum_register("qtemp", 1) # temporary qubit qtempst = q_program.create_quantum_register("qtempst", n) # temporary register qX = q_program.create_quantum_register("qX", n) # x register qext = q_program.create_quantum_register("qext", 1) # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register mod_mult_circuit = q_program.create_circuit("mod_mult", [qa, qb, qN, qNtemp, qtemp, qtempst, qX, qext],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum register and the classical register mod_mult_circuit = q_program.create_circuit("mod_mult", [qa, qb, qN, qcar, qNtemp, qtemp, qtempst, qX, qext],[c]) # create the state containing 'a' number_state(mod_mult_circuit, qa, a, n) # create the state containing 'b' number_state(mod_mult_circuit, qX, x, n) # create the state containing 'N' number_state(mod_mult_circuit, qN, N, n+1) # create a temporary state containing 'N' number_state(mod_mult_circuit, qNtemp, N, n) mod_mult_circuit.x(qext[0]) # we set the control qubit to |1> # controlled modular multiplication cont_mod_mult_nbit(mod_mult_circuit, qa, qb, qN, qNtemp, qcar, qtemp[0], qtempst, qX, qext[0], N, n) # measurements to see the result for i in range(n+1): mod_mult_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["mod_mult"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=999999) # show the results. print(result) print(result.get_data("mod_mult")) counts = result.get_counts("mod_mult") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2))) # checking the version of PYTHON; only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') # importing QISKit from qiskit import QuantumProgram # import basic plotting tools from qiskit.tools.visualization import plot_histogram # create a QuantumProgram object instance. q_program = QuantumProgram() # backend backend = 'local_qasm_simulator' def carry(circuit, q0, q1, q2, q3): "carry module" circuit.ccx(q1, q2, q3) circuit.cx(q1, q2) circuit.ccx(q0, q2, q3) def carry_inv(circuit, q0, q1, q2, q3): "carry module running backwards" circuit.ccx(q0, q2, q3) circuit.cx(q1, q2) circuit.ccx(q1, q2, q3) def summation(circuit, q0, q1, q2): "summation module" circuit.cx(q1, q2) circuit.cx(q0, q2) def summation_inv(circuit, q0, q1, q2): "summation module running backwards" circuit.cx(q0, q2) circuit.cx(q1, q2) # quantum plain addition algorithm for n-qubit numbers def addition_nbit(circuit, qa, qb, qcar, n): if n == 1: circuit.ccx(qa[0], qb[0], qb[1]) circuit.cx(qa[0], qb[0]) else: circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) circuit.cx(qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): summation(circuit, qcar[i-1], qa[i], qb[i]) carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1]) summation(circuit, qcar[0], qa[1], qb[1]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) # quantum plain substraction algorithm for n-qubit numbers def subs_nbit(circuit, qa, qb, qcar, n): "same as the plain addition but running backwards" if n == 1: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qb[1]) else: circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) circuit.cx(qa[0], qb[0]) summation_inv(circuit, qcar[0], qa[1], qb[1]) for i in range(n-2): carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1]) summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2]) circuit.cx(qa[n-1], qb[n-1]) carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n]) for i in range(n-2, 0, -1): carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i]) circuit.cx(qa[0], qb[0]) circuit.ccx(qa[0], qb[0], qcar[0]) def cond_toffoli(circuit, qcond, q1, q2, q3): "conditional toffoli gate" circuit.h(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.ccx(qcond, q2, q3) circuit.tdg(q3) circuit.ccx(qcond, q1, q3) circuit.t(q3) circuit.h(q3) circuit.t(q2) circuit.ccx(qcond, q1, q2) circuit.t(q1) circuit.tdg(q2) circuit.ccx(qcond, q1, q2) def cond_carry(circuit, q0, q1, q2, q3, qcond): "conditional carry module" cond_toffoli(circuit, qcond, q1, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q0, q2, q3) def cond_carry_inv(circuit, q0, q1, q2, q3, qcond): "conditional carry module running backwards" cond_toffoli(circuit, qcond, q0, q2, q3) circuit.ccx(qcond, q1, q2) cond_toffoli(circuit, qcond, q1, q2, q3) def cond_summation(circuit, q0, q1, q2, qcond): "conditional summation" circuit.ccx(qcond, q1, q2) circuit.ccx(qcond, q0, q2) def cond_summation_inv(circuit, q0, q1, q2, qcond): "conditional summation running backwards" circuit.ccx(qcond, q0, q2) circuit.ccx(qcond, q1, q2) # quantum conditional plain addition algorithm for n-qubit numbers def cond_addition_nbit(circuit, qa, qb, qcar, qcond, n): if n == 1: cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) circuit.ccx(qcond, qa[0], qb[0]) else: cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_carry(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) for i in range(n-1, 1, -1): cond_summation(circuit, qcar[i-1], qa[i], qb[i], qcond) cond_carry_inv(circuit, qcar[i-2], qa[i-1], qb[i-1], qcar[i-1], qcond) cond_summation(circuit, qcar[0], qa[1], qb[1], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) # quantum conditional plain substraction algorithm for n-qubit numbers def cond_subs_nbit(circuit, qa, qb, qcar, qcond, n): "same as conditional plain addition but running backwards" if n == 1: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qb[1]) else: circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) circuit.ccx(qcond, qa[0], qb[0]) cond_summation_inv(circuit, qcar[0], qa[1], qb[1], qcond) for i in range(n-2): cond_carry(circuit, qcar[i], qa[i+1], qb[i+1], qcar[i+1], qcond) cond_summation_inv(circuit, qcar[i+1], qa[i+2], qb[i+2], qcond) circuit.ccx(qcond, qa[n-1], qb[n-1]) cond_carry_inv(circuit, qcar[n-2], qa[n-1], qb[n-1], qb[n], qcond) for i in range(n-2, 0, -1): cond_carry_inv(circuit, qcar[i-1], qa[i], qb[i], qcar[i], qcond) circuit.ccx(qcond, qa[0], qb[0]) cond_toffoli(circuit, qcond, qa[0], qb[0], qcar[0]) # quantum modular addition algorithm for n-qubit numbers def mod_addition_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): addition_nbit(circuit, qa, qb, qcar, n) subs_nbit(circuit, qN, qb, qcar, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp) circuit.x(qb[n]) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) addition_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp) addition_nbit(circuit, qa, qb, qcar, n) # quantum modular substraction algorithm for n-qubit numbers def mod_subs_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, n): "same as modular addition but running backwards" subs_nbit(circuit, qa, qb, qcar, n) circuit.cx(qb[n], qtemp) addition_nbit(circuit, qa, qb, qcar, n) cond_subs_nbit(circuit, qNtemp, qN, qcar, qtemp, n) subs_nbit(circuit, qN, qb, qcar, n) cond_addition_nbit(circuit, qNtemp, qN, qcar, qtemp, n) circuit.x(qb[n]) circuit.cx(qb[n], qtemp) circuit.x(qb[n]) addition_nbit(circuit, qN, qb, qcar, n) subs_nbit(circuit, qa, qb, qcar, n) # quantum controlled modular multiplication algorithm for n-qubit numbers def cont_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, qX, qext, N, n): for i in range(n): for j in range(n): classical_mod = (2**(i+j))%N cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) mod_addition_nbit(circuit, qtempst, qb, qN, qNtemp, qcar, qtemp, n) cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) circuit.x(qext) cond_addition_nbit(circuit, qX, qb, qcar, qext, n) circuit.x(qext) def cont_inv_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, qX, qext, N, n): "same as the controlled modular multiplication but running backwards" circuit.x(qext) cond_subs_nbit(circuit, qX, qb, qcar, qext, n) circuit.x(qext) for i in range(n): for j in range(n): classical_mod = (2**(i+j))%N cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) mod_subs_nbit(circuit, qtempst, qb, qN, qNtemp, qcar, qtemp, n) cond_number_state(circuit, qtempst, classical_mod, qext, qa[i], qX[j], n) # quantum modular exponentiation algorithm for n-qubit numbers def mod_exp_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, q1, qX, N, a, n): for k in range(len(qX)): clas_value = (a**(2**(k)))%N if k % 2 == 0: number_state(circuit, qa, clas_value, n) cont_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, q1, qX[k], N, n) number_state(circuit, qa, clas_value, n) clas_value = modinv(a**(2**(k)), N) number_state(circuit, qa, clas_value, n) cont_inv_mod_mult_nbit(circuit, qa, q1, qN, qNtemp, qcar, qtemp, qtempst, qb, qX[k], N, n) number_state(circuit, qa, clas_value, n) else: number_state(circuit, qa, clas_value, n) cont_mod_mult_nbit(circuit, qa, q1, qN, qNtemp, qcar, qtemp, qtempst, qb, qX[k], N, n) number_state(circuit, qa, clas_value, n) clas_value = modinv(a**(2**(k)), N) number_state(circuit, qa, clas_value, n) cont_inv_mod_mult_nbit(circuit, qa, qb, qN, qNtemp, qcar, qtemp, qtempst, q1, qX[k], N, n) number_state(circuit, qa, clas_value, n) # n-qubit number input state def number_state(circuit, q, x, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: circuit.x(q[i]) # n-qubit number input state, controlled by 2 control qubits def cond_number_state(circuit, q, x, ext, control1, control2, n): # integer to binary x = "{0:b}".format(x) x = x.zfill(n) # creating the state for i in range(n): if int(x[n-1-i]) == 1: cond_toffoli(circuit, ext, control1, control2, q[i]) # efficient algorithm for computing the modular multiplicative inverse a^-1 mod m def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m # we define the values, a and N must be coprimes a = 1 x = 1 N = 1 # computing number of qubits n needed n = len("{0:b}".format(a)) n2 = len("{0:b}".format(x)) n3 = len("{0:b}".format(N)) if n3 > n: n = n3 # classical register with n+1 bits. c = q_program.create_classical_register("cr", n+1) # quantum registers qa = q_program.create_quantum_register("qa", n) # a qubits qb = q_program.create_quantum_register("qb", n+1) # initial state |0> qN = q_program.create_quantum_register("qN", n+1) # N qubits qNtemp = q_program.create_quantum_register("qNtemp", n) # temporary N qubits qtemp = q_program.create_quantum_register("qtemp", 1) # temporary qubit qtempst = q_program.create_quantum_register("qtempst", n) # temporary register q1 = q_program.create_quantum_register("q1", n+1) # initial state |1> qX = q_program.create_quantum_register("qX", n2) # x register # if n = 1, no need of carry register if n == 1: qcar = 0 # quantum circuit involving the quantum registers and the classical register mod_exp_circuit = q_program.create_circuit("mod_exp", [qa, qb, qN, qNtemp, qtemp, qtempst, q1, qX],[c]) else: qcar = q_program.create_quantum_register("qcar", n-1) # carry qubits # quantum circuit involving the quantum registers and the classical register mod_exp_circuit = q_program.create_circuit("mod_exp", [qa, qb, qN, qcar, qNtemp, qtemp, qtempst, q1, qX],[c]) # create the initial state |1>. If N = 1, initial state is |0> if N != 1: number_state(mod_exp_circuit, q1, 1, 1) # create the state containing 'x' number_state(mod_exp_circuit, qX, x, n2) # create the state containing 'N' number_state(mod_exp_circuit, qN, N, n+1) # create a temporary state containing 'N' number_state(mod_exp_circuit, qNtemp, N, n) # modular exponentiation mod_exp_nbit(mod_exp_circuit, qa, qb, qN, qNtemp, qcar, qtemp[0], qtempst, q1, qX, N, a, n) # measurements to see the result, the result would be in one of those registers, q1 or qb if n2 % 2 == 0: for i in range(n+1): mod_exp_circuit.measure(q1[i], c[i]) else: for i in range(n+1): mod_exp_circuit.measure(qb[i], c[i]) # compile and execute the quantum program in the backend result = q_program.execute(["mod_exp"], backend=backend, shots=1024, max_credits=3, wait=10, timeout=9999999) # show the results. print(result) print(result.get_data("mod_exp")) counts = result.get_counts("mod_exp") plot_histogram(counts) print("Backend:", backend) print("Highest probability outcome: {}".format(int(max(counts, key = lambda x: counts[x]).replace(" ", ""), 2)))
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw()
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
%load_ext autoreload %autoreload 2 # to use dataframe and load csv file import pandas as pd # to use for mathematical operations import numpy as np # split the set in 2 set, common train and test from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler # plot different designs import matplotlib.pyplot as plt %matplotlib inline np.random.seed(123) data = pd.read_csv("dataset/BackOrders.csv",header=0) data.shape data.head() for col in ['potential_issue', 'deck_risk', 'oe_constraint', 'ppap_risk', 'stop_auto_buy', 'rev_stop', 'went_on_backorder']: data[col]=pd.factorize(data[col])[0] data.describe(include='all') data['perf_6_month_avg']=data['perf_6_month_avg'].replace(-99, np.NaN) data['perf_12_month_avg']=data['perf_12_month_avg'].replace(-99, np.NaN) varnames=list(data)[1:] correlations = data[varnames].corr() fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(correlations, vmin=-1, vmax=1) fig.colorbar(cax) ticks = np.arange(0,22,1) ax.set_xticks(ticks) ax.set_yticks(ticks) ax.set_xticklabels(varnames,rotation=90) ax.set_yticklabels(varnames) plt.show() data.drop('rev_stop', axis=1, inplace=True) data.drop('oe_constraint', axis=1, inplace=True) data.drop('potential_issue', axis=1, inplace=True) data.drop('stop_auto_buy', axis=1, inplace=True) data.drop('deck_risk', axis=1, inplace=True) def check_missing(data): tot = data.isnull().sum().sort_values(ascending=False) perc = ( round(100*data.isnull().sum()/data.isnull().count(),1) ).sort_values(ascending=False) missing_data = pd.concat([tot, perc], axis=1, keys=['Missing', 'Percent']) return missing_data[:3] check_missing(data) data.fillna(data.median(), inplace=True) data check_missing(data) data.drop('sku', axis=1, inplace=True) data X, y = data.loc[:,data.columns!='went_on_backorder'].values, data.loc[:,'went_on_backorder'].values X,y X_train_1, X_test, y_train_1, y_test = train_test_split(X, y, test_size=0.1, random_state=123, stratify = data['went_on_backorder']) print(X_train_1.shape) print(X_test.shape) print(pd.value_counts(y_train)/y_train.size * 100) print(pd.value_counts(y_test)/y_test.size * 100) def balance_split(X_train_1,y_train_1,flag=""): X_train0 = [] X_train1 = [] y_train0 = [] y_train1 = [] for i in range(len(y_train_1)): if y_train_1[i] == 0: X_train0.append(X_train_1[i]) y_train0.append(y_train_1[i]) else: X_train1.append(X_train_1[i]) y_train1.append(y_train_1[i]) X_train =[] y_train = [] if flag == "fair": X_train = X_train0[:1000] + X_train1[:1000] y_train = y_train0[:1000] + y_train1[:1000] else: X_train = X_train0[:10000] + X_train1 y_train = y_train0[:10000] + y_train1 return np.asarray(X_train),np.asarray(y_train) def save_data(X_train_1,y_train_1,flag="",name=""): if flag == "fair": X_train,y_train = balance_split(X_train_1,y_train_1,flag) df_train = pd.concat([pd.DataFrame(X_train), pd.DataFrame(y_train)], axis=1) df_train.to_csv("dataset/fair_"+name+".csv", index=False) else: X_train,y_train = balance_split(X_train_1,y_train_1) df_train = pd.concat([pd.DataFrame(X_train), pd.DataFrame(y_train)], axis=1) df_train.to_csv("dataset/classic_"+name+".csv", index=False) #classic data save_data(X_train_1,y_train_1,flag="classic",name="train") #fair data save_data(X_train_1,y_train_1,flag="fair",name="train") #classic data save_data(X_test,y_test,flag="classic",name="test") data = pd.read_csv("dataset/classic_train.csv") X,y = data[data.columns[:16]].values, data[data.columns[16]].values X.shape, y.shape data = pd.read_csv("dataset/fair_train.csv") X,y = data[data.columns[:16]].values, data[data.columns[16]].values X.shape, y.shape data = pd.read_csv("dataset/classic_test.csv") X,y = data[data.columns[:16]].values, data[data.columns[16]].values X.shape, y.shape
https://github.com/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
import sys sys.path.append('../') from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\ sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\ sampleCircuitF from entanglement import Ent import warnings warnings.filterwarnings('ignore') labels = [ 'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3', 'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F' ] samplers = [ sampleCircuitA, sampleCircuitB1, sampleCircuitB2, sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE, sampleCircuitF ] q = 4 for layer in range(1, 4): print(f'qubtis: {q}') print('-' * 25) for (label, sampler) in zip(labels, samplers): expr = Ent(sampler, layer=layer, epoch=3000) print(f'{label}(layer={layer}): {expr}') print()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler # Initialize the problem by defining the parameters n = 3 # number of nodes + depot (n+1) K = 2 # number of vehicles # Get the data class Initializer: def __init__(self, n): self.n = n def generate_instance(self): n = self.n # np.random.seed(33) np.random.seed(1543) xc = (np.random.rand(n) - 0.5) * 10 yc = (np.random.rand(n) - 0.5) * 10 instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance # Initialize the problem by randomly generating the instance initializer = Initializer(n) xc, yc, instance = initializer.generate_instance() class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.15, yc[i]), size=16, color="r") plt.plot(xc[0], yc[0], "r*", ms=20) plt.grid() for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n plt.arrow( xc[ix], yc[ix], xc[iy] - xc[ix], yc[iy] - yc[ix], length_includes_head=True, head_width=0.25, ) plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) result = optimizer.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) # Put the solution in a way that is compatible with the classical variables x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 # visualize the solution visualize_solution(xc, yc, x_quantum, quantum_cost, n, K, "Quantum") # and visualize the classical for comparison if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's controlled gate operation.""" import unittest from test import combine import numpy as np from numpy import pi from ddt import ddt, data, unpack from qiskit import QuantumRegister, QuantumCircuit, execute, BasicAer, QiskitError from qiskit.test import QiskitTestCase from qiskit.circuit import ControlledGate, Parameter, Gate from qiskit.circuit.exceptions import CircuitError from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.states import Statevector import qiskit.circuit.add_control as ac from qiskit.transpiler.passes import Unroller from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit from qiskit.quantum_info import Operator from qiskit.circuit.library import ( CXGate, XGate, YGate, ZGate, U1Gate, CYGate, CZGate, CU1Gate, SwapGate, PhaseGate, CCXGate, HGate, RZGate, RXGate, CPhaseGate, RYGate, CRYGate, CRXGate, CSwapGate, UGate, U3Gate, CHGate, CRZGate, CU3Gate, CUGate, SXGate, CSXGate, MSGate, Barrier, RCCXGate, RC3XGate, MCU1Gate, MCXGate, MCXGrayCode, MCXRecursive, MCXVChain, C3XGate, C3SXGate, C4XGate, MCPhaseGate, GlobalPhaseGate, ) from qiskit.circuit._utils import _compute_control_matrix import qiskit.circuit.library.standard_gates as allGates from qiskit.extensions import UnitaryGate from qiskit.circuit.library.standard_gates.multi_control_rotation_gates import _mcsu2_real_diagonal from .gate_utils import _get_free_params @ddt class TestControlledGate(QiskitTestCase): """Tests for controlled gates and the ControlledGate class.""" def test_controlled_x(self): """Test creation of controlled x gate""" self.assertEqual(XGate().control(), CXGate()) def test_controlled_y(self): """Test creation of controlled y gate""" self.assertEqual(YGate().control(), CYGate()) def test_controlled_z(self): """Test creation of controlled z gate""" self.assertEqual(ZGate().control(), CZGate()) def test_controlled_h(self): """Test the creation of a controlled H gate.""" self.assertEqual(HGate().control(), CHGate()) def test_controlled_phase(self): """Test the creation of a controlled U1 gate.""" theta = 0.5 self.assertEqual(PhaseGate(theta).control(), CPhaseGate(theta)) def test_double_controlled_phase(self): """Test the creation of a controlled phase gate.""" theta = 0.5 self.assertEqual(PhaseGate(theta).control(2), MCPhaseGate(theta, 2)) def test_controlled_u1(self): """Test the creation of a controlled U1 gate.""" theta = 0.5 self.assertEqual(U1Gate(theta).control(), CU1Gate(theta)) circ = QuantumCircuit(1) circ.append(U1Gate(theta), circ.qregs[0]) unroller = Unroller(["cx", "u", "p"]) ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control() ctrl_circ = QuantumCircuit(2) ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0]) ctrl_circ = ctrl_circ.decompose().decompose() self.assertEqual(ctrl_circ.size(), 1) def test_controlled_rz(self): """Test the creation of a controlled RZ gate.""" theta = 0.5 self.assertEqual(RZGate(theta).control(), CRZGate(theta)) def test_control_parameters(self): """Test different ctrl_state formats for control function.""" theta = 0.5 self.assertEqual( CRYGate(theta).control(2, ctrl_state="01"), CRYGate(theta).control(2, ctrl_state=1) ) self.assertEqual( CRYGate(theta).control(2, ctrl_state=None), CRYGate(theta).control(2, ctrl_state=3) ) self.assertEqual(CCXGate().control(2, ctrl_state="01"), CCXGate().control(2, ctrl_state=1)) self.assertEqual(CCXGate().control(2, ctrl_state=None), CCXGate().control(2, ctrl_state=3)) def test_controlled_ry(self): """Test the creation of a controlled RY gate.""" theta = 0.5 self.assertEqual(RYGate(theta).control(), CRYGate(theta)) def test_controlled_rx(self): """Test the creation of a controlled RX gate.""" theta = 0.5 self.assertEqual(RXGate(theta).control(), CRXGate(theta)) def test_controlled_u(self): """Test the creation of a controlled U gate.""" theta, phi, lamb = 0.1, 0.2, 0.3 self.assertEqual(UGate(theta, phi, lamb).control(), CUGate(theta, phi, lamb, 0)) def test_controlled_u3(self): """Test the creation of a controlled U3 gate.""" theta, phi, lamb = 0.1, 0.2, 0.3 self.assertEqual(U3Gate(theta, phi, lamb).control(), CU3Gate(theta, phi, lamb)) circ = QuantumCircuit(1) circ.append(U3Gate(theta, phi, lamb), circ.qregs[0]) unroller = Unroller(["cx", "u", "p"]) ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control() ctrl_circ = QuantumCircuit(2) ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0]) ctrl_circ = ctrl_circ.decompose().decompose() self.assertEqual(ctrl_circ.size(), 1) def test_controlled_cx(self): """Test creation of controlled cx gate""" self.assertEqual(CXGate().control(), CCXGate()) def test_controlled_swap(self): """Test creation of controlled swap gate""" self.assertEqual(SwapGate().control(), CSwapGate()) def test_special_cases_equivalent_to_controlled_base_gate(self): """Test that ``ControlledGate`` subclasses for more efficient representations give equivalent matrices and definitions to the naive ``base_gate.control(n)``.""" # Angles used here are not important, we just pick slightly strange values to ensure that # there are no coincidental equivalences. tests = [ (CXGate(), 1), (CCXGate(), 2), (C3XGate(), 3), (C4XGate(), 4), (MCXGate(5), 5), (CYGate(), 1), (CZGate(), 1), (CPhaseGate(np.pi / 7), 1), (MCPhaseGate(np.pi / 7, 2), 2), (CSwapGate(), 1), (CSXGate(), 1), (C3SXGate(), 3), (CHGate(), 1), (CU1Gate(np.pi / 7), 1), (MCU1Gate(np.pi / 7, 2), 2), # `CUGate` takes an extra "global" phase parameter compared to `UGate`, and consequently # is only equal to `base_gate.control()` when this extra phase is 0. (CUGate(np.pi / 7, np.pi / 5, np.pi / 3, 0), 1), (CU3Gate(np.pi / 7, np.pi / 5, np.pi / 3), 1), (CRXGate(np.pi / 7), 1), (CRYGate(np.pi / 7), 1), (CRZGate(np.pi / 7), 1), ] for special_case_gate, n_controls in tests: with self.subTest(gate=special_case_gate.name): naive_operator = Operator(special_case_gate.base_gate.control(n_controls)) # Ensure that both the array form (if the gate overrides `__array__`) and the # circuit-definition form are tested. self.assertTrue(Operator(special_case_gate).equiv(naive_operator)) if not isinstance(special_case_gate, CXGate): # CX is treated like a primitive within Terra, and doesn't have a definition. self.assertTrue(Operator(special_case_gate.definition).equiv(naive_operator)) def test_global_phase_control(self): """Test creation of a GlobalPhaseGate.""" base = GlobalPhaseGate(np.pi / 7) expected_1q = PhaseGate(np.pi / 7) self.assertEqual(Operator(base.control()), Operator(expected_1q)) expected_2q = PhaseGate(np.pi / 7).control() self.assertEqual(Operator(base.control(2)), Operator(expected_2q)) expected_open = QuantumCircuit(1) expected_open.x(0) expected_open.p(np.pi / 7, 0) expected_open.x(0) self.assertEqual(Operator(base.control(ctrl_state=0)), Operator(expected_open)) def test_circuit_append(self): """Test appending a controlled gate to a quantum circuit.""" circ = QuantumCircuit(5) inst = CXGate() circ.append(inst.control(), qargs=[0, 2, 1]) circ.append(inst.control(2), qargs=[0, 3, 1, 2]) circ.append(inst.control().control(), qargs=[0, 3, 1, 2]) # should be same as above self.assertEqual(circ[1].operation, circ[2].operation) self.assertEqual(circ.depth(), 3) self.assertEqual(circ[0].operation.num_ctrl_qubits, 2) self.assertEqual(circ[1].operation.num_ctrl_qubits, 3) self.assertEqual(circ[2].operation.num_ctrl_qubits, 3) self.assertEqual(circ[0].operation.num_qubits, 3) self.assertEqual(circ[1].operation.num_qubits, 4) self.assertEqual(circ[2].operation.num_qubits, 4) for instr in circ: self.assertTrue(isinstance(instr.operation, ControlledGate)) def test_swap_definition_specification(self): """Test the instantiation of a controlled swap gate with explicit definition.""" swap = SwapGate() cswap = ControlledGate( "cswap", 3, [], num_ctrl_qubits=1, definition=swap.definition, base_gate=swap ) self.assertEqual(swap.definition, cswap.definition) def test_multi_controlled_composite_gate(self): """Test a multi controlled composite gate.""" num_ctrl = 3 # create composite gate sub_q = QuantumRegister(2) cgate = QuantumCircuit(sub_q, name="cgate") cgate.h(sub_q[0]) cgate.crz(pi / 2, sub_q[0], sub_q[1]) cgate.swap(sub_q[0], sub_q[1]) cgate.u(0.1, 0.2, 0.3, sub_q[1]) cgate.t(sub_q[0]) num_target = cgate.width() gate = cgate.to_gate() cont_gate = gate.control(num_ctrl_qubits=num_ctrl) control = QuantumRegister(num_ctrl) target = QuantumRegister(num_target) qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat)) def test_single_controlled_composite_gate(self): """Test a singly controlled composite gate.""" num_ctrl = 1 # create composite gate sub_q = QuantumRegister(2) cgate = QuantumCircuit(sub_q, name="cgate") cgate.h(sub_q[0]) cgate.cx(sub_q[0], sub_q[1]) num_target = cgate.width() gate = cgate.to_gate() cont_gate = gate.control(num_ctrl_qubits=num_ctrl) control = QuantumRegister(num_ctrl, "control") target = QuantumRegister(num_target, "target") qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat)) def test_control_open_controlled_gate(self): """Test control(2) vs control.control where inner gate has open controls.""" gate1pre = ZGate().control(1, ctrl_state=0) gate1 = gate1pre.control(1, ctrl_state=1) gate2 = ZGate().control(2, ctrl_state=1) expected = Operator(_compute_control_matrix(ZGate().to_matrix(), 2, ctrl_state=1)) self.assertEqual(expected, Operator(gate1)) self.assertEqual(expected, Operator(gate2)) def test_multi_control_z(self): """Test a multi controlled Z gate.""" qc = QuantumCircuit(1) qc.z(0) ctr_gate = qc.to_gate().control(2) ctr_circ = QuantumCircuit(3) ctr_circ.append(ctr_gate, range(3)) ref_circ = QuantumCircuit(3) ref_circ.h(2) ref_circ.ccx(0, 1, 2) ref_circ.h(2) self.assertEqual(ctr_circ.decompose(), ref_circ) def test_multi_control_u3(self): """Test the matrix representation of the controlled and controlled-controlled U3 gate.""" from qiskit.circuit.library.standard_gates import u3 num_ctrl = 3 # U3 gate params alpha, beta, gamma = 0.2, 0.3, 0.4 u3gate = u3.U3Gate(alpha, beta, gamma) cu3gate = u3.CU3Gate(alpha, beta, gamma) # cnu3 gate cnu3 = u3gate.control(num_ctrl) width = cnu3.num_qubits qr = QuantumRegister(width) qcnu3 = QuantumCircuit(qr) qcnu3.append(cnu3, qr, []) # U3 gate qu3 = QuantumCircuit(1) qu3.append(u3gate, [0]) # CU3 gate qcu3 = QuantumCircuit(2) qcu3.append(cu3gate, [0, 1]) # c-cu3 gate width = 3 qr = QuantumRegister(width) qc_cu3 = QuantumCircuit(qr) c_cu3 = cu3gate.control(1) qc_cu3.append(c_cu3, qr, []) # Circuit unitaries mat_cnu3 = Operator(qcnu3).data mat_u3 = Operator(qu3).data mat_cu3 = Operator(qcu3).data mat_c_cu3 = Operator(qc_cu3).data # Target Controlled-U3 unitary target_cnu3 = _compute_control_matrix(mat_u3, num_ctrl) target_cu3 = np.kron(mat_u3, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) target_c_cu3 = np.kron(mat_cu3, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) tests = [ ("check unitary of u3.control against tensored unitary of u3", target_cu3, mat_cu3), ( "check unitary of cu3.control against tensored unitary of cu3", target_c_cu3, mat_c_cu3, ), ("check unitary of cnu3 against tensored unitary of u3", target_cnu3, mat_cnu3), ] for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): self.assertTrue(matrix_equal(target, decomp, atol=1e-8, rtol=1e-5)) def test_multi_control_u1(self): """Test the matrix representation of the controlled and controlled-controlled U1 gate.""" from qiskit.circuit.library.standard_gates import u1 num_ctrl = 3 # U1 gate params theta = 0.2 u1gate = u1.U1Gate(theta) cu1gate = u1.CU1Gate(theta) # cnu1 gate cnu1 = u1gate.control(num_ctrl) width = cnu1.num_qubits qr = QuantumRegister(width) qcnu1 = QuantumCircuit(qr) qcnu1.append(cnu1, qr, []) # U1 gate qu1 = QuantumCircuit(1) qu1.append(u1gate, [0]) # CU1 gate qcu1 = QuantumCircuit(2) qcu1.append(cu1gate, [0, 1]) # c-cu1 gate width = 3 qr = QuantumRegister(width) qc_cu1 = QuantumCircuit(qr) c_cu1 = cu1gate.control(1) qc_cu1.append(c_cu1, qr, []) job = execute( [qcnu1, qu1, qcu1, qc_cu1], BasicAer.get_backend("unitary_simulator"), basis_gates=["u1", "u2", "u3", "id", "cx"], ) result = job.result() # Circuit unitaries mat_cnu1 = result.get_unitary(0) # trace out ancillae mat_u1 = result.get_unitary(1) mat_cu1 = result.get_unitary(2) mat_c_cu1 = result.get_unitary(3) # Target Controlled-U1 unitary target_cnu1 = _compute_control_matrix(mat_u1, num_ctrl) target_cu1 = np.kron(mat_u1, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) target_c_cu1 = np.kron(mat_cu1, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) tests = [ ("check unitary of u1.control against tensored unitary of u1", target_cu1, mat_cu1), ( "check unitary of cu1.control against tensored unitary of cu1", target_c_cu1, mat_c_cu1, ), ("check unitary of cnu1 against tensored unitary of u1", target_cnu1, mat_cnu1), ] for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): self.log.info(info) self.assertTrue(matrix_equal(target, decomp)) @data(1, 2, 3, 4) def test_multi_controlled_u1_matrix(self, num_controls): """Test the matrix representation of the multi-controlled CU1 gate. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcu1.py """ # registers for the circuit q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] lam = 0.3165354 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) qc.mcp(lam, q_controls, q_target[0]) # for idx in subset: for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) base = PhaseGate(lam).to_matrix() expected = _compute_control_matrix(base, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) @data(1, 2, 3, 4) def test_multi_control_toffoli_matrix_clean_ancillas(self, num_controls): """Test the multi-control Toffoli gate with clean ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ # set up circuit q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) if num_controls > 2: num_ancillas = num_controls - 2 q_ancillas = QuantumRegister(num_controls) qc.add_register(q_ancillas) else: num_ancillas = 0 q_ancillas = None # apply hadamard on control qubits and toffoli gate qc.mct(q_controls, q_target[0], q_ancillas, mode="basic") # execute the circuit and obtain statevector result backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) # compare to expectation if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected)) @data(1, 2, 3, 4, 5) def test_multi_control_toffoli_matrix_basic_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (basic-dirty-ancilla). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) q_ancillas = None if num_controls <= 2: num_ancillas = 0 else: num_ancillas = num_controls - 2 q_ancillas = QuantumRegister(num_ancillas) qc.add_register(q_ancillas) qc.mct(q_controls, q_target[0], q_ancillas, mode="basic-dirty-ancilla") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) @data(1, 2, 3, 4, 5) def test_multi_control_toffoli_matrix_advanced_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (advanced). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) q_ancillas = None if num_controls <= 4: num_ancillas = 0 else: num_ancillas = 1 q_ancillas = QuantumRegister(num_ancillas) qc.add_register(q_ancillas) qc.mct(q_controls, q_target[0], q_ancillas, mode="advanced") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) @data(1, 2, 3) def test_multi_control_toffoli_matrix_noancilla_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (noancilla). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) qc.mct(q_controls, q_target[0], None, mode="noancilla") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) def test_mcsu2_real_diagonal(self): """Test mcsu2_real_diagonal""" num_ctrls = 6 theta = 0.3 ry_matrix = RYGate(theta).to_matrix() qc = _mcsu2_real_diagonal(ry_matrix, num_ctrls) mcry_matrix = _compute_control_matrix(ry_matrix, 6) self.assertTrue(np.allclose(mcry_matrix, Operator(qc).to_matrix())) @combine(num_controls=[1, 2, 4], base_gate_name=["x", "y", "z"], use_basis_gates=[True, False]) def test_multi_controlled_rotation_gate_matrices( self, num_controls, base_gate_name, use_basis_gates ): """Test the multi controlled rotation gates without ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) # call mcrx/mcry/mcrz if base_gate_name == "y": qc.mcry( theta, q_controls, q_target[0], None, mode="noancilla", use_basis_gates=use_basis_gates, ) else: # case 'x' or 'z' only support the noancilla mode and do not have this keyword getattr(qc, "mcr" + base_gate_name)( theta, q_controls, q_target[0], use_basis_gates=use_basis_gates ) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) if use_basis_gates: with self.subTest(msg="check only basis gates used"): gates_used = set(qc.count_ops().keys()) self.assertTrue(gates_used.issubset({"x", "u", "p", "cx"})) backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) if base_gate_name == "x": rot_mat = RXGate(theta).to_matrix() elif base_gate_name == "y": rot_mat = RYGate(theta).to_matrix() else: # case 'z' rot_mat = RZGate(theta).to_matrix() expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) @combine(num_controls=[1, 2, 4], use_basis_gates=[True, False]) def test_multi_controlled_y_rotation_matrix_basic_mode(self, num_controls, use_basis_gates): """Test the multi controlled Y rotation using the mode 'basic'. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ # get the number of required ancilla qubits if num_controls <= 2: num_ancillas = 0 else: num_ancillas = num_controls - 2 q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi if num_ancillas > 0: q_ancillas = QuantumRegister(num_ancillas) qc = QuantumCircuit(q_controls, q_target, q_ancillas) else: qc = QuantumCircuit(q_controls, q_target) q_ancillas = None for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) qc.mcry( theta, q_controls, q_target[0], q_ancillas, mode="basic", use_basis_gates=use_basis_gates, ) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) rot_mat = RYGate(theta).to_matrix() backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) def test_mcry_defaults_to_vchain(self): """Test mcry defaults to the v-chain mode if sufficient work qubits are provided.""" circuit = QuantumCircuit(5) control_qubits = circuit.qubits[:3] target_qubit = circuit.qubits[3] additional_qubits = circuit.qubits[4:] circuit.mcry(0.2, control_qubits, target_qubit, additional_qubits) # If the v-chain mode is selected, all qubits are used. If the noancilla mode would be # selected, the bottom qubit would remain unused. dag = circuit_to_dag(circuit) self.assertEqual(len(list(dag.idle_wires())), 0) @data(1, 2) def test_mcx_gates_yield_explicit_gates(self, num_ctrl_qubits): """Test the creating a MCX gate yields the explicit definition if we know it.""" cls = MCXGate(num_ctrl_qubits).__class__ explicit = {1: CXGate, 2: CCXGate} self.assertEqual(cls, explicit[num_ctrl_qubits]) @data(1, 2, 3, 4) def test_mcxgraycode_gates_yield_explicit_gates(self, num_ctrl_qubits): """Test creating an mcx gate calls MCXGrayCode and yeilds explicit definition.""" qc = QuantumCircuit(num_ctrl_qubits + 1) qc.mcx(list(range(num_ctrl_qubits)), [num_ctrl_qubits]) explicit = {1: CXGate, 2: CCXGate, 3: C3XGate, 4: C4XGate} self.assertEqual(type(qc[0].operation), explicit[num_ctrl_qubits]) @data(3, 4, 5, 8) def test_mcx_gates(self, num_ctrl_qubits): """Test the mcx gates.""" backend = BasicAer.get_backend("statevector_simulator") reference = np.zeros(2 ** (num_ctrl_qubits + 1)) reference[-1] = 1 for gate in [ MCXGrayCode(num_ctrl_qubits), MCXRecursive(num_ctrl_qubits), MCXVChain(num_ctrl_qubits, False), MCXVChain(num_ctrl_qubits, True), ]: with self.subTest(gate=gate): circuit = QuantumCircuit(gate.num_qubits) if num_ctrl_qubits > 0: circuit.x(list(range(num_ctrl_qubits))) circuit.append(gate, list(range(gate.num_qubits)), []) statevector = execute(circuit, backend).result().get_statevector() # account for ancillas if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: corrected = np.zeros(2 ** (num_ctrl_qubits + 1), dtype=complex) for i, statevector_amplitude in enumerate(statevector): i = int(bin(i)[2:].zfill(circuit.num_qubits)[gate.num_ancilla_qubits :], 2) corrected[i] += statevector_amplitude statevector = corrected np.testing.assert_array_almost_equal(statevector.real, reference) @data(1, 2, 3, 4) def test_inverse_x(self, num_ctrl_qubits): """Test inverting the controlled X gate.""" cnx = XGate().control(num_ctrl_qubits) inv_cnx = cnx.inverse() result = Operator(cnx).compose(Operator(inv_cnx)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3) def test_inverse_gate(self, num_ctrl_qubits): """Test inverting a controlled gate based on a circuit definition.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.rx(np.pi / 4, [0, 1, 2]) gate = qc.to_gate() cgate = gate.control(num_ctrl_qubits) inv_cgate = cgate.inverse() result = Operator(cgate).compose(Operator(inv_cgate)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3) def test_inverse_circuit(self, num_ctrl_qubits): """Test inverting a controlled gate based on a circuit definition.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.rx(np.pi / 4, [0, 1, 2]) cqc = qc.control(num_ctrl_qubits) cqc_inv = cqc.inverse() result = Operator(cqc).compose(Operator(cqc_inv)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3, 4, 5) def test_controlled_unitary(self, num_ctrl_qubits): """Test the matrix data of an Operator, which is based on a controlled gate.""" num_target = 1 q_target = QuantumRegister(num_target) qc1 = QuantumCircuit(q_target) # for h-rx(pi/2) theta, phi, lamb = 1.57079632679490, 0.0, 4.71238898038469 qc1.u(theta, phi, lamb, q_target[0]) base_gate = qc1.to_gate() # get UnitaryGate version of circuit base_op = Operator(qc1) base_mat = base_op.data cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(is_unitary_matrix(base_mat)) self.assertTrue(matrix_equal(cop_mat, test_op.data)) @data(1, 2, 3, 4, 5) def test_controlled_random_unitary(self, num_ctrl_qubits): """Test the matrix data of an Operator based on a random UnitaryGate.""" num_target = 2 base_gate = random_unitary(2**num_target).to_instruction() base_mat = base_gate.to_matrix() cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(matrix_equal(cop_mat, test_op.data)) @combine(num_ctrl_qubits=[1, 2, 3], ctrl_state=[0, None]) def test_open_controlled_unitary_z(self, num_ctrl_qubits, ctrl_state): """Test that UnitaryGate with control returns params.""" umat = np.array([[1, 0], [0, -1]]) ugate = UnitaryGate(umat) cugate = ugate.control(num_ctrl_qubits, ctrl_state=ctrl_state) ref_mat = _compute_control_matrix(umat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cugate), Operator(ref_mat)) def test_controlled_controlled_rz(self): """Test that UnitaryGate with control returns params.""" qc = QuantumCircuit(1) qc.rz(0.2, 0) controlled = QuantumCircuit(2) controlled.compose(qc.control(), inplace=True) self.assertEqual(Operator(controlled), Operator(CRZGate(0.2))) self.assertEqual(Operator(controlled), Operator(RZGate(0.2).control())) def test_controlled_controlled_unitary(self): """Test that global phase in iso decomposition of unitary is handled.""" umat = np.array([[1, 0], [0, -1]]) ugate = UnitaryGate(umat) cugate = ugate.control() ccugate = cugate.control() ccugate2 = ugate.control(2) ref_mat = _compute_control_matrix(umat, 2) self.assertTrue(Operator(ccugate2).equiv(Operator(ref_mat))) self.assertTrue(Operator(ccugate).equiv(Operator(ccugate2))) @data(1, 2, 3) def test_open_controlled_unitary_matrix(self, num_ctrl_qubits): """test open controlled unitary matrix""" # verify truth table num_target_qubits = 2 num_qubits = num_ctrl_qubits + num_target_qubits target_op = Operator(XGate()) for i in range(num_target_qubits - 1): target_op = target_op.tensor(XGate()) for i in range(2**num_qubits): input_bitstring = bin(i)[2:].zfill(num_qubits) input_target = input_bitstring[0:num_target_qubits] input_ctrl = input_bitstring[-num_ctrl_qubits:] phi = Statevector.from_label(input_bitstring) cop = Operator( _compute_control_matrix(target_op.data, num_ctrl_qubits, ctrl_state=input_ctrl) ) for j in range(2**num_qubits): output_bitstring = bin(j)[2:].zfill(num_qubits) output_target = output_bitstring[0:num_target_qubits] output_ctrl = output_bitstring[-num_ctrl_qubits:] psi = Statevector.from_label(output_bitstring) cxout = np.dot(phi.data, psi.evolve(cop).data) if input_ctrl == output_ctrl: # flip the target bits cond_output = "".join([str(int(not int(a))) for a in input_target]) else: cond_output = input_target if cxout == 1: self.assertTrue((output_ctrl == input_ctrl) and (output_target == cond_output)) else: self.assertTrue( ((output_ctrl == input_ctrl) and (output_target != cond_output)) or output_ctrl != input_ctrl ) def test_open_control_cx_unrolling(self): """test unrolling of open control gates when gate is in basis""" qc = QuantumCircuit(2) qc.cx(0, 1, ctrl_state=0) dag = circuit_to_dag(qc) unroller = Unroller(["u3", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) ref_circuit = QuantumCircuit(2) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) ref_circuit.cx(0, 1) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) self.assertEqual(uqc, ref_circuit) def test_open_control_cy_unrolling(self): """test unrolling of open control gates when gate is in basis""" qc = QuantumCircuit(2) qc.cy(0, 1, ctrl_state=0) dag = circuit_to_dag(qc) unroller = Unroller(["u3", "cy"]) uqc = dag_to_circuit(unroller.run(dag)) ref_circuit = QuantumCircuit(2) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) ref_circuit.cy(0, 1) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) self.assertEqual(uqc, ref_circuit) def test_open_control_ccx_unrolling(self): """test unrolling of open control gates when gate is in basis""" qreg = QuantumRegister(3) qc = QuantumCircuit(qreg) ccx = CCXGate(ctrl_state=0) qc.append(ccx, [0, 1, 2]) dag = circuit_to_dag(qc) unroller = Unroller(["x", "ccx"]) unrolled_dag = unroller.run(dag) # ┌───┐ ┌───┐ # q0_0: ┤ X ├──■──┤ X ├ # ├───┤ │ ├───┤ # q0_1: ┤ X ├──■──┤ X ├ # └───┘┌─┴─┐└───┘ # q0_2: ─────┤ X ├───── # └───┘ ref_circuit = QuantumCircuit(qreg) ref_circuit.x(qreg[0]) ref_circuit.x(qreg[1]) ref_circuit.ccx(qreg[0], qreg[1], qreg[2]) ref_circuit.x(qreg[0]) ref_circuit.x(qreg[1]) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_ccx_ctrl_state_consistency(self): """Test the consistency of parameters ctrl_state in CCX See issue: https://github.com/Qiskit/qiskit-terra/issues/6465 """ qreg = QuantumRegister(3) qc = QuantumCircuit(qreg) qc.ccx(qreg[0], qreg[1], qreg[2], ctrl_state=0) ref_circuit = QuantumCircuit(qreg) ccx = CCXGate(ctrl_state=0) ref_circuit.append(ccx, [qreg[0], qreg[1], qreg[2]]) self.assertEqual(qc, ref_circuit) def test_open_control_composite_unrolling(self): """test unrolling of open control gates when gate is in basis""" # create composite gate qreg = QuantumRegister(2) qcomp = QuantumCircuit(qreg, name="bell") qcomp.h(qreg[0]) qcomp.cx(qreg[0], qreg[1]) bell = qcomp.to_gate() # create controlled composite gate cqreg = QuantumRegister(3) qc = QuantumCircuit(cqreg) qc.append(bell.control(ctrl_state=0), qc.qregs[0][:]) dag = circuit_to_dag(qc) unroller = Unroller(["x", "u1", "cbell"]) unrolled_dag = unroller.run(dag) # create reference circuit ref_circuit = QuantumCircuit(cqreg) ref_circuit.x(cqreg[0]) ref_circuit.append(bell.control(), [cqreg[0], cqreg[1], cqreg[2]]) ref_circuit.x(cqreg[0]) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) @data(*ControlledGate.__subclasses__()) def test_standard_base_gate_setting(self, gate_class): """Test all gates in standard extensions which are of type ControlledGate and have a base gate setting. """ num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * i for i in range(num_free_params)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 base_gate = gate_class(*free_params) cgate = base_gate.control() # the base gate of CU is U (3 params), the base gate of CCU is CU (4 params) if gate_class == CUGate: self.assertListEqual(cgate.base_gate.params[:3], base_gate.base_gate.params[:3]) else: self.assertEqual(base_gate.base_gate, cgate.base_gate) @combine( gate=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)], num_ctrl_qubits=[1, 2], ctrl_state=[None, 0, 1], ) def test_all_inverses(self, gate, num_ctrl_qubits, ctrl_state): """Test all gates in standard extensions except those that cannot be controlled or are being deprecated. """ if not (issubclass(gate, ControlledGate) or issubclass(gate, allGates.IGate)): # only verify basic gates right now, as already controlled ones # will generate differing definitions try: numargs = len(_get_free_params(gate)) args = [2] * numargs gate = gate(*args) self.assertEqual( gate.inverse().control(num_ctrl_qubits, ctrl_state=ctrl_state), gate.control(num_ctrl_qubits, ctrl_state=ctrl_state).inverse(), ) except AttributeError: # skip gates that do not have a control attribute (e.g. barrier) pass @data(2, 3) def test_relative_phase_toffoli_gates(self, num_ctrl_qubits): """Test the relative phase Toffoli gates. This test compares the matrix representation of the relative phase gate classes (i.e. RCCXGate().to_matrix()), the matrix obtained from the unitary simulator, and the exact version of the gate as obtained through `_compute_control_matrix`. """ # get target matrix (w/o relative phase) base_mat = XGate().to_matrix() target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) # build the matrix for the relative phase toffoli using the unitary simulator circuit = QuantumCircuit(num_ctrl_qubits + 1) if num_ctrl_qubits == 2: circuit.rccx(0, 1, 2) else: # num_ctrl_qubits == 3: circuit.rcccx(0, 1, 2, 3) simulator = BasicAer.get_backend("unitary_simulator") simulated_mat = execute(circuit, simulator).result().get_unitary() # get the matrix representation from the class itself if num_ctrl_qubits == 2: repr_mat = RCCXGate().to_matrix() else: # num_ctrl_qubits == 3: repr_mat = RC3XGate().to_matrix() # test up to phase # note, that all entries may have an individual phase! (as opposed to a global phase) self.assertTrue(matrix_equal(np.abs(simulated_mat), target_mat)) # compare simulated matrix with the matrix representation provided by the class self.assertTrue(matrix_equal(simulated_mat, repr_mat)) def test_open_controlled_gate(self): """ Test controlled gates with control on '0' """ base_gate = XGate() base_mat = base_gate.to_matrix() num_ctrl_qubits = 3 ctrl_state = 5 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = None cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = 0 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = 7 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = "110" cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) def test_open_controlled_gate_raises(self): """ Test controlled gates with open controls raises if ctrl_state isn't allowed. """ base_gate = XGate() num_ctrl_qubits = 3 with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state=-1) with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state=2**num_ctrl_qubits) with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state="201") def test_base_gate_params_reference(self): """ Test all gates in standard extensions which are of type ControlledGate and have a base gate setting have params which reference the one in their base gate. """ num_ctrl_qubits = 1 for gate_class in ControlledGate.__subclasses__(): with self.subTest(i=repr(gate_class)): num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * (i + 1) for i in range(num_free_params)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 base_gate = gate_class(*free_params) if base_gate.params: cgate = base_gate.control(num_ctrl_qubits) self.assertIs(cgate.base_gate.params, cgate.params) def test_assign_parameters(self): """Test assigning parameters to quantum circuit with controlled gate.""" qc = QuantumCircuit(2, name="assign") ptest = Parameter("p") gate = CRYGate(ptest) qc.append(gate, [0, 1]) subs1, subs2 = {ptest: Parameter("a")}, {ptest: Parameter("b")} bound1 = qc.assign_parameters(subs1, inplace=False) bound2 = qc.assign_parameters(subs2, inplace=False) self.assertEqual(qc.parameters, {ptest}) self.assertEqual(bound1.parameters, {subs1[ptest]}) self.assertEqual(bound2.parameters, {subs2[ptest]}) @data(-1, 0, 1.4, "1", 4, 10) def test_improper_num_ctrl_qubits(self, num_ctrl_qubits): """ Test improperly specified num_ctrl_qubits. """ num_qubits = 4 with self.assertRaises(CircuitError): ControlledGate( name="cgate", num_qubits=num_qubits, params=[], num_ctrl_qubits=num_ctrl_qubits ) def test_improper_num_ctrl_qubits_base_gate(self): """Test that the allowed number of control qubits takes the base gate into account.""" with self.assertRaises(CircuitError): ControlledGate( name="cx?", num_qubits=2, params=[], num_ctrl_qubits=2, base_gate=XGate() ) self.assertIsInstance( ControlledGate( name="cx?", num_qubits=2, params=[], num_ctrl_qubits=1, base_gate=XGate() ), ControlledGate, ) self.assertIsInstance( ControlledGate( name="p", num_qubits=1, params=[np.pi], num_ctrl_qubits=1, base_gate=Gate("gphase", 0, [np.pi]), ), ControlledGate, ) def test_open_controlled_equality(self): """ Test open controlled gates are equal if their base gates and control states are equal. """ self.assertEqual(XGate().control(1), XGate().control(1)) self.assertNotEqual(XGate().control(1), YGate().control(1)) self.assertNotEqual(XGate().control(1), XGate().control(2)) self.assertEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="0")) self.assertNotEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="1")) def test_cx_global_phase(self): """ Test controlling CX with global phase """ theta = pi / 2 circ = QuantumCircuit(2, global_phase=theta) circ.cx(0, 1) cx = circ.to_gate() self.assertNotEqual(Operator(CXGate()), Operator(cx)) ccx = cx.control(1) base_mat = Operator(cx).data target = _compute_control_matrix(base_mat, 1) self.assertEqual(Operator(ccx), Operator(target)) expected = QuantumCircuit(*ccx.definition.qregs) expected.ccx(0, 1, 2) expected.p(theta, 0) self.assertEqual(ccx.definition, expected) @data(1, 2) def test_controlled_global_phase(self, num_ctrl_qubits): """ Test controlled global phase on base gate. """ theta = pi / 4 circ = QuantumCircuit(2, global_phase=theta) base_gate = circ.to_gate() base_mat = Operator(base_gate).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) cgate = base_gate.control(num_ctrl_qubits) ccirc = circ.control(num_ctrl_qubits) self.assertEqual(Operator(cgate), Operator(target)) self.assertEqual(Operator(ccirc), Operator(target)) @data(1, 2) def test_rz_composite_global_phase(self, num_ctrl_qubits): """ Test controlling CX with global phase """ theta = pi / 4 circ = QuantumCircuit(2, global_phase=theta) circ.rz(0.1, 0) circ.rz(0.2, 1) ccirc = circ.control(num_ctrl_qubits) base_gate = circ.to_gate() cgate = base_gate.control(num_ctrl_qubits) base_mat = Operator(base_gate).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertEqual(Operator(cgate), Operator(target)) self.assertEqual(Operator(ccirc), Operator(target)) @data(1, 2) def test_nested_global_phase(self, num_ctrl_qubits): """ Test controlling a gate with nested global phase. """ theta = pi / 4 circ = QuantumCircuit(1, global_phase=theta) circ.z(0) v = circ.to_gate() qc = QuantumCircuit(1) qc.append(v, [0]) ctrl_qc = qc.control(num_ctrl_qubits) base_mat = Operator(qc).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertEqual(Operator(ctrl_qc), Operator(target)) @data(1, 2) def test_control_zero_operand_gate(self, num_ctrl_qubits): """Test that a zero-operand gate (such as a make-shift global-phase gate) can be controlled.""" gate = QuantumCircuit(global_phase=np.pi).to_gate() controlled = gate.control(num_ctrl_qubits) self.assertIsInstance(controlled, ControlledGate) self.assertEqual(controlled.num_ctrl_qubits, num_ctrl_qubits) self.assertEqual(controlled.num_qubits, num_ctrl_qubits) target = np.eye(2**num_ctrl_qubits, dtype=np.complex128) target.flat[-1] = -1 self.assertEqual(Operator(controlled), Operator(target)) @ddt class TestOpenControlledToMatrix(QiskitTestCase): """Test controlled_gates implementing to_matrix work with ctrl_state""" @combine(gate_class=ControlledGate.__subclasses__(), ctrl_state=[0, None]) def test_open_controlled_to_matrix(self, gate_class, ctrl_state): """Test open controlled to_matrix.""" num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * i for i in range(1, num_free_params + 1)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 cgate = gate_class(*free_params) cgate.ctrl_state = ctrl_state base_mat = Operator(cgate.base_gate).data if gate_class == CUGate: # account for global phase base_mat = np.array(base_mat) * np.exp(1j * cgate.params[3]) target = _compute_control_matrix(base_mat, cgate.num_ctrl_qubits, ctrl_state=ctrl_state) try: actual = cgate.to_matrix() except CircuitError as cerr: self.skipTest(str(cerr)) self.assertTrue(np.allclose(actual, target)) @ddt class TestSingleControlledRotationGates(QiskitTestCase): """Test the controlled rotation gates controlled on one qubit.""" from qiskit.circuit.library.standard_gates import u1, rx, ry, rz num_ctrl = 2 num_target = 1 theta = pi / 2 gu1 = u1.U1Gate(theta) grx = rx.RXGate(theta) gry = ry.RYGate(theta) grz = rz.RZGate(theta) ugu1 = ac._unroll_gate(gu1, ["p", "u", "cx"]) ugrx = ac._unroll_gate(grx, ["p", "u", "cx"]) ugry = ac._unroll_gate(gry, ["p", "u", "cx"]) ugrz = ac._unroll_gate(grz, ["p", "u", "cx"]) ugrz.params = grz.params cgu1 = ugu1.control(num_ctrl) cgrx = ugrx.control(num_ctrl) cgry = ugry.control(num_ctrl) cgrz = ugrz.control(num_ctrl) @data((gu1, cgu1), (grx, cgrx), (gry, cgry), (grz, cgrz)) @unpack def test_single_controlled_rotation_gates(self, gate, cgate): """Test the controlled rotation gates controlled on one qubit.""" if gate.name == "rz": iden = Operator.from_label("I") zgen = Operator.from_label("Z") op_mat = (np.cos(0.5 * self.theta) * iden - 1j * np.sin(0.5 * self.theta) * zgen).data else: op_mat = Operator(gate).data ref_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, self.num_ctrl) self.assertTrue(matrix_equal(cop_mat, ref_mat)) cqc = QuantumCircuit(self.num_ctrl + self.num_target) cqc.append(cgate, cqc.qregs[0]) dag = circuit_to_dag(cqc) unroller = Unroller(["u", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) self.log.info("%s gate count: %d", cgate.name, uqc.size()) self.log.info("\n%s", str(uqc)) # these limits could be changed if gate.name == "ry": self.assertLessEqual(uqc.size(), 32, f"\n{uqc}") elif gate.name == "rz": self.assertLessEqual(uqc.size(), 43, f"\n{uqc}") else: self.assertLessEqual(uqc.size(), 20, f"\n{uqc}") def test_composite(self): """Test composite gate count.""" qreg = QuantumRegister(self.num_ctrl + self.num_target) qc = QuantumCircuit(qreg, name="composite") qc.append(self.grx.control(self.num_ctrl), qreg) qc.append(self.gry.control(self.num_ctrl), qreg) qc.append(self.gry, qreg[0 : self.gry.num_qubits]) qc.append(self.grz.control(self.num_ctrl), qreg) dag = circuit_to_dag(qc) unroller = Unroller(["u", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) self.log.info("%s gate count: %d", uqc.name, uqc.size()) self.assertLessEqual(uqc.size(), 96, f"\n{uqc}") # this limit could be changed @ddt class TestControlledStandardGates(QiskitTestCase): """Tests for control standard gates.""" @combine( num_ctrl_qubits=[1, 2, 3], gate_class=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)], ) def test_controlled_standard_gates(self, num_ctrl_qubits, gate_class): """Test controlled versions of all standard gates.""" theta = pi / 2 ctrl_state_ones = 2**num_ctrl_qubits - 1 ctrl_state_zeros = 0 ctrl_state_mixed = ctrl_state_ones >> int(num_ctrl_qubits / 2) numargs = len(_get_free_params(gate_class)) args = [theta] * numargs if gate_class in [MSGate, Barrier]: args[0] = 2 elif gate_class in [MCU1Gate, MCPhaseGate]: args[1] = 2 elif issubclass(gate_class, MCXGate): args = [5] gate = gate_class(*args) for ctrl_state in (ctrl_state_ones, ctrl_state_zeros, ctrl_state_mixed): with self.subTest(i=f"{gate_class.__name__}, ctrl_state={ctrl_state}"): if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: # skip matrices that include ancilla qubits continue try: cgate = gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) except (AttributeError, QiskitError): # 'object has no attribute "control"' # skipping Id and Barrier continue base_mat = Operator(gate).data target_mat = _compute_control_matrix( base_mat, num_ctrl_qubits, ctrl_state=ctrl_state ) self.assertEqual(Operator(cgate), Operator(target_mat)) @ddt class TestParameterCtrlState(QiskitTestCase): """Test gate equality with ctrl_state parameter.""" @data( (RXGate(0.5), CRXGate(0.5)), (RYGate(0.5), CRYGate(0.5)), (RZGate(0.5), CRZGate(0.5)), (XGate(), CXGate()), (YGate(), CYGate()), (ZGate(), CZGate()), (U1Gate(0.5), CU1Gate(0.5)), (PhaseGate(0.5), CPhaseGate(0.5)), (SwapGate(), CSwapGate()), (HGate(), CHGate()), (U3Gate(0.1, 0.2, 0.3), CU3Gate(0.1, 0.2, 0.3)), (UGate(0.1, 0.2, 0.3), CUGate(0.1, 0.2, 0.3, 0)), ) @unpack def test_ctrl_state_one(self, gate, controlled_gate): """Test controlled gates with ctrl_state See https://github.com/Qiskit/qiskit-terra/pull/4025 """ self.assertEqual( Operator(gate.control(1, ctrl_state="1")), Operator(controlled_gate.to_matrix()) ) @ddt class TestControlledGateLabel(QiskitTestCase): """Tests for controlled gate labels.""" gates_and_args = [ (XGate, []), (YGate, []), (ZGate, []), (HGate, []), (CXGate, []), (CCXGate, []), (C3XGate, []), (C3SXGate, []), (C4XGate, []), (MCXGate, [5]), (PhaseGate, [0.1]), (U1Gate, [0.1]), (CYGate, []), (CZGate, []), (CPhaseGate, [0.1]), (CU1Gate, [0.1]), (SwapGate, []), (SXGate, []), (CSXGate, []), (CCXGate, []), (RZGate, [0.1]), (RXGate, [0.1]), (RYGate, [0.1]), (CRYGate, [0.1]), (CRXGate, [0.1]), (CSwapGate, []), (UGate, [0.1, 0.2, 0.3]), (U3Gate, [0.1, 0.2, 0.3]), (CHGate, []), (CRZGate, [0.1]), (CUGate, [0.1, 0.2, 0.3, 0.4]), (CU3Gate, [0.1, 0.2, 0.3]), (MSGate, [5, 0.1]), (RCCXGate, []), (RC3XGate, []), (MCU1Gate, [0.1, 1]), (MCXGate, [5]), ] @data(*gates_and_args) @unpack def test_control_label(self, gate, args): """Test gate(label=...).control(label=...)""" cgate = gate(*args, label="a gate").control(label="a controlled gate") self.assertEqual(cgate.label, "a controlled gate") self.assertEqual(cgate.base_gate.label, "a gate") @data(*gates_and_args) @unpack def test_control_label_1(self, gate, args): """Test gate(label=...).control(1, label=...)""" cgate = gate(*args, label="a gate").control(1, label="a controlled gate") self.assertEqual(cgate.label, "a controlled gate") self.assertEqual(cgate.base_gate.label, "a gate") if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Testing legacy instruction alignment pass.""" from qiskit import QuantumCircuit, pulse from qiskit.test import QiskitTestCase from qiskit.transpiler import InstructionDurations from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import ( AlignMeasures, ValidatePulseGates, ALAPSchedule, TimeUnitConversion, ) class TestAlignMeasures(QiskitTestCase): """A test for measurement alignment pass.""" def setUp(self): super().setUp() instruction_durations = InstructionDurations() instruction_durations.update( [ ("rz", (0,), 0), ("rz", (1,), 0), ("x", (0,), 160), ("x", (1,), 160), ("sx", (0,), 160), ("sx", (1,), 160), ("cx", (0, 1), 800), ("cx", (1, 0), 800), ("measure", None, 1600), ] ) self.time_conversion_pass = TimeUnitConversion(inst_durations=instruction_durations) # reproduce old behavior of 0.20.0 before #7655 # currently default write latency is 0 self.scheduling_pass = ALAPSchedule( durations=instruction_durations, clbit_write_latency=1600, conditional_latency=0, ) self.align_measure_pass = AlignMeasures(alignment=16) def test_t1_experiment_type(self): """Test T1 experiment type circuit. (input) ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 (aligned) ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 This type of experiment slightly changes delay duration of interest. However the quantization error should be less than alignment * dt. """ circuit = QuantumCircuit(1, 1) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(1, 1) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.measure(0, 0) self.assertEqual(aligned_circuit, ref_circuit) def test_hanh_echo_experiment_type(self): """Test Hahn echo experiment type circuit. (input) ┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌─┐ q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤M├ └────┘└────────────────┘└───┘└────────────────┘└────┘└╥┘ c: 1/══════════════════════════════════════════════════════╩═ 0 (output) ┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌──────────────┐┌─┐ q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤ Delay(8[dt]) ├┤M├ └────┘└────────────────┘└───┘└────────────────┘└────┘└──────────────┘└╥┘ c: 1/══════════════════════════════════════════════════════════════════════╩═ 0 This type of experiment doesn't change duration of interest (two in the middle). However induces slight delay less than alignment * dt before measurement. This might induce extra amplitude damping error. """ circuit = QuantumCircuit(1, 1) circuit.sx(0) circuit.delay(100, 0, unit="dt") circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.sx(0) circuit.measure(0, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(1, 1) ref_circuit.sx(0) ref_circuit.delay(100, 0, unit="dt") ref_circuit.x(0) ref_circuit.delay(100, 0, unit="dt") ref_circuit.sx(0) ref_circuit.delay(8, 0, unit="dt") ref_circuit.measure(0, 0) self.assertEqual(aligned_circuit, ref_circuit) def test_mid_circuit_measure(self): """Test circuit with mid circuit measurement. (input) ┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(120[dt]) ├┤M├ └───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘ c: 2/════════════════════════╩══════════════════════════════════════════╩═ 0 1 (output) ┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(134[dt]) ├┤M├ └───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘ c: 2/════════════════════════╩══════════════════════════════════════════╩═ 0 1 Extra delay is always added to the existing delay right before the measurement. Delay after measurement is unchanged. """ circuit = QuantumCircuit(1, 2) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) circuit.delay(10, 0, unit="dt") circuit.x(0) circuit.delay(120, 0, unit="dt") circuit.measure(0, 1) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(1, 2) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.measure(0, 0) ref_circuit.delay(10, 0, unit="dt") ref_circuit.x(0) ref_circuit.delay(134, 0, unit="dt") ref_circuit.measure(0, 1) self.assertEqual(aligned_circuit, ref_circuit) def test_mid_circuit_multiq_gates(self): """Test circuit with mid circuit measurement and multi qubit gates. (input) ┌───┐┌────────────────┐┌─┐ ┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──■───────■──┤M├ └───┘└────────────────┘└╥┘┌─┴─┐┌─┐┌─┴─┐└╥┘ q_1: ────────────────────────╫─┤ X ├┤M├┤ X ├─╫─ ║ └───┘└╥┘└───┘ ║ c: 2/════════════════════════╩═══════╩═══════╩═ 0 1 0 (output) ┌───┐ ┌────────────────┐┌─┐ ┌─────────────────┐ ┌─┐» q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├──■──┤ Delay(1600[dt]) ├──■──┤M├» ┌──────┴───┴──────┐└────────────────┘└╥┘┌─┴─┐└───────┬─┬───────┘┌─┴─┐└╥┘» q_1: ┤ Delay(1872[dt]) ├───────────────────╫─┤ X ├────────┤M├────────┤ X ├─╫─» └─────────────────┘ ║ └───┘ └╥┘ └───┘ ║ » c: 2/══════════════════════════════════════╩═══════════════╩═══════════════╩═» 0 1 0 » « «q_0: ─────────────────── « ┌─────────────────┐ «q_1: ┤ Delay(1600[dt]) ├ « └─────────────────┘ «c: 2/═══════════════════ « Delay for the other channel paired by multi-qubit instruction is also scheduled. Delay (1872dt) = X (160dt) + Delay (100dt + extra 12dt) + Measure (1600dt). """ circuit = QuantumCircuit(2, 2) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) circuit.cx(0, 1) circuit.measure(1, 1) circuit.cx(0, 1) circuit.measure(0, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(2, 2) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.measure(0, 0) ref_circuit.delay(160 + 112 + 1600, 1, unit="dt") ref_circuit.cx(0, 1) ref_circuit.delay(1600, 0, unit="dt") ref_circuit.measure(1, 1) ref_circuit.cx(0, 1) ref_circuit.delay(1600, 1, unit="dt") ref_circuit.measure(0, 0) self.assertEqual(aligned_circuit, ref_circuit) def test_alignment_is_not_processed(self): """Test avoid pass processing if delay is aligned.""" circuit = QuantumCircuit(2, 2) circuit.x(0) circuit.delay(160, 0, unit="dt") circuit.measure(0, 0) circuit.cx(0, 1) circuit.measure(1, 1) circuit.cx(0, 1) circuit.measure(0, 0) # pre scheduling is not necessary because alignment is skipped # this is to minimize breaking changes to existing code. transpiled = self.align_measure_pass(circuit, property_set={"time_unit": "dt"}) self.assertEqual(transpiled, circuit) def test_circuit_using_clbit(self): """Test a circuit with instructions using a common clbit. (input) ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├────────────── └───┘└────────────────┘└╥┘ ┌───┐ q_1: ────────────────────────╫────┤ X ├────── ║ └─╥─┘ ┌─┐ q_2: ────────────────────────╫──────╫─────┤M├ ║ ┌────╨────┐└╥┘ c: 1/════════════════════════╩═╡ c_0 = T ╞═╩═ 0 └─────────┘ 0 (aligned) ┌───┐ ┌────────────────┐┌─┐┌────────────────┐ q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├┤ Delay(160[dt]) ├─── ┌──────┴───┴──────┐└────────────────┘└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1872[dt]) ├───────────────────╫───────┤ X ├────────── └┬────────────────┤ ║ └─╥─┘ ┌─┐ q_2: ─┤ Delay(432[dt]) ├───────────────────╫─────────╫─────────┤M├ └────────────────┘ ║ ┌────╨────┐ └╥┘ c: 1/══════════════════════════════════════╩════╡ c_0 = T ╞═════╩═ 0 └─────────┘ 0 Looking at the q_0, the total schedule length T becomes 160 (x) + 112 (aligned delay) + 1600 (measure) + 160 (delay) = 2032. The last delay comes from ALAP scheduling called before the AlignMeasure pass, which aligns stop times as late as possible, so the start time of x(1).c_if(0) and the stop time of measure(0, 0) become T - 160. """ circuit = QuantumCircuit(3, 1) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) circuit.x(1).c_if(0, 1) circuit.measure(2, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) self.assertEqual(aligned_circuit.duration, 2032) ref_circuit = QuantumCircuit(3, 1) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.delay(1872, 1, unit="dt") # 2032 - 160 ref_circuit.delay(432, 2, unit="dt") # 2032 - 1600 ref_circuit.measure(0, 0) ref_circuit.x(1).c_if(0, 1) ref_circuit.delay(160, 0, unit="dt") ref_circuit.measure(2, 0) self.assertEqual(aligned_circuit, ref_circuit) class TestPulseGateValidation(QiskitTestCase): """A test for pulse gate validation pass.""" def setUp(self): super().setUp() self.pulse_gate_validation_pass = ValidatePulseGates(granularity=16, min_length=64) def test_invalid_pulse_duration(self): """Kill pass manager if invalid pulse gate is found.""" # this is invalid duration pulse # this will cause backend error since this doesn't fit with waveform memory chunk. custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) with self.assertRaises(TranspilerError): self.pulse_gate_validation_pass(circuit) def test_short_pulse_duration(self): """Kill pass manager if invalid pulse gate is found.""" # this is invalid duration pulse # this will cause backend error since this doesn't fit with waveform memory chunk. custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) with self.assertRaises(TranspilerError): self.pulse_gate_validation_pass(circuit) def test_short_pulse_duration_multiple_pulse(self): """Kill pass manager if invalid pulse gate is found.""" # this is invalid duration pulse # however total gate schedule length is 64, which accidentally satisfies the constraints # this should fail in the validation custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True ) custom_gate.insert( 32, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) with self.assertRaises(TranspilerError): self.pulse_gate_validation_pass(circuit) def test_valid_pulse_duration(self): """No error raises if valid calibration is provided.""" # this is valid duration pulse custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(160, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) # just not raise an error self.pulse_gate_validation_pass(circuit) def test_no_calibration(self): """No error raises if no calibration is addedd.""" circuit = QuantumCircuit(1) circuit.x(0) # just not raise an error self.pulse_gate_validation_pass(circuit)
https://github.com/iqm-finland/qiskit-on-iqm
iqm-finland
# Copyright 2023 Qiskit on IQM developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transpilation tool to optimize the decomposition of single-qubit gates tailored to IQM hardware.""" import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary from qiskit.circuit.library import RGate from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passes import BasisTranslator, Optimize1qGatesDecomposition, RemoveBarriers from qiskit.transpiler.passmanager import PassManager class IQMOptimizeSingleQubitGates(TransformationPass): r"""Optimize the decomposition of single-qubit gates for the IQM gate set. This optimisation pass expects the circuit to be correctly layouted and translated to the IQM architecture and raises an error otherwise. The optimisation logic follows the steps: 1. Convert single-qubit gates to :math:`U` gates and combine all neighbouring :math:`U` gates. 2. Convert :math:`U` gates according to :math:`U(\theta , \phi , \lambda) ~ RZ(\phi + \lambda) R(\theta, \pi / 2 - \lambda)`. 3. Commute `RZ` gates to the end of the circuit using the fact that `RZ` and `CZ` gates commute, and :math:`R(\theta , \phi) RZ(\lambda) = RZ(\lambda) R(\theta, \phi - \lambda)`. 4. Drop `RZ` gates immediately before measurements, and otherwise replace them according to :math:`RZ(\lambda) = R(\pi, \lambda / 2) R(- \pi, 0)`. Args: drop_final_rz: Drop terminal RZ gates even if there are no measurements following them (since they do not affect the measurement results). Note that this will change the unitary propagator of the circuit. ignore_barriers (bool): Removes the barriers from the circuit before optimization (default = False). """ def __init__(self, drop_final_rz: bool = False, ignore_barriers: bool = False): super().__init__() self._basis = ['r', 'cz'] self._intermediate_basis = ['u', 'cz'] self._drop_final_rz = drop_final_rz self._ignore_barriers = ignore_barriers def run(self, dag: DAGCircuit) -> DAGCircuit: self._validate_ops(dag) # accumulated RZ angles for each qubit, from the beginning of the circuit to the current gate rz_angles: list[float] = [0] * dag.num_qubits() if self._ignore_barriers: dag = RemoveBarriers().run(dag) # convert all gates in the circuit to U and CZ gates dag = BasisTranslator(SessionEquivalenceLibrary, self._intermediate_basis).run(dag) # combine all sequential U gates into one dag = Optimize1qGatesDecomposition(self._intermediate_basis).run(dag) for node in dag.topological_op_nodes(): if node.name == 'u': qubit_index = dag.find_bit(node.qargs[0])[0] dag.substitute_node( node, RGate(node.op.params[0], np.pi / 2 - node.op.params[2] - rz_angles[qubit_index]) ) phase = node.op.params[1] + node.op.params[2] dag.global_phase += phase / 2 rz_angles[qubit_index] += phase elif node.name == 'measure': for qubit in node.qargs: rz_angles[dag.find_bit(qubit)[0]] = 0 if not self._drop_final_rz: for qubit_index, rz_angle in enumerate(rz_angles): if rz_angle != 0: qubit = dag.qubits[qubit_index] dag.apply_operation_back(RGate(-np.pi, 0), qargs=(qubit,)) dag.apply_operation_back(RGate(np.pi, rz_angles[qubit_index] / 2), qargs=(qubit,)) return dag def _validate_ops(self, dag: DAGCircuit): for node in dag.op_nodes(): if node.name not in self._basis + ['measure', 'barrier']: raise ValueError( f"""Invalid operation '{node.name}' found in IQMOptimize1QbDecomposition pass, expected operations {self._basis + ['measure', 'barrier']}""" ) def optimize_single_qubit_gates( circuit: QuantumCircuit, drop_final_rz: bool = True, ignore_barriers: bool = False ) -> QuantumCircuit: """Optimize number of single-qubit gates in a transpiled circuit exploiting the IQM specific gate set. Args: circuit: quantum circuit to optimise drop_final_rz: Drop terminal RZ gates even if there are no measurements following them (since they do not affect the measurement results). Note that this will change the unitary propagator of the circuit. ignore_barriers (bool): Removes barriers from the circuit if they exist (default = False) before optimization. Returns: optimised circuit """ return PassManager(IQMOptimizeSingleQubitGates(drop_final_rz, ignore_barriers)).run(circuit)
https://github.com/Cgrubick/GroversSearchAlgorithm
Cgrubick
# HONR 293W Quantum Computing for Fun Clayton Grubick # complete program written in Qiskit for searching a # two-qubit quantum database using Grover’s search # algorithm. # from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from numpy import random from matplotlib import pyplot as plt def DB_function(QC, color_code): #if color_code == 0: do nothing if color_code == 1: QC.ccx(0,1,3) elif color_code == 2: QC.ccx(0,1,2) elif color_code == 3: QC.ccx(0,1,2) QC.ccx(0,1,3) color_codes = [0,1,2,3] random.shuffle(color_codes) database = {} for i in range(4): database[i]= color_codes[i] desired_color_code = 2 DB = QuantumCircuit(5) #for when index = 0 = 00 DB.x(0) DB.x(1) DB_function(DB, database[0]) DB.x(0) DB.x(1) #for when index = 1 = 01 DB.x(0) DB_function(DB, database[1]) DB.x(0) #for when index = 2 = 10 DB.x(1) DB_function(DB, database[2]) DB.x(1) #for when index = 3 = 11 DB_function(DB, database[3]) MG = QuantumCircuit(5) if desired_color_code == 0: MG.x(2) MG.x(3) MG.ccx(2,3,4) MG.x(2) MG.x(3) elif desired_color_code == 1: MG.x(2) MG.ccx(2,3,4) MG.x(2) elif desired_color_code == 2: MG.x(3) MG.ccx(2,3,4) MG.x(3) elif desired_color_code == 3: MG.ccx(2,3,4) oracle = QuantumCircuit(5) oracle.compose(DB, inplace=True) oracle.compose(MG, inplace=True) oracle.compose(DB, inplace=True) phase = QuantumCircuit(5) phase.x(0) phase.x(1) phase.h(1) phase.cx(0,1) phase.h(1) phase.x(0) phase.x(1) Grover = QuantumCircuit(5) Grover.compose(oracle, inplace=True) Grover.h(0) Grover.h(1) Grover.compose(phase, inplace=True) Grover.h(0) Grover.h(1) circuit = QuantumCircuit(5,2) circuit.x(4) circuit.h(0) circuit.h(1) circuit.h(4) circuit.compose(Grover, inplace=True) circuit.measure(0,1) circuit.measure(1,0) sim = Aer.get_backend('qasm_simulator') results = execute(circuit,sim,shots = 1000) counts = results.result().get_counts() print("Done") plot_histogram(counts) plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXDebugging())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import datetime import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt plt.rcParams.update({"text.usetex": True}) plt.rcParams["figure.figsize"] = (6,4) mpl.rcParams["figure.dpi"] = 200 from qiskit_ibm_runtime import Estimator, Session, QiskitRuntimeService, Options from qiskit.quantum_info import SparsePauliOp from qiskit import QuantumCircuit service = QiskitRuntimeService() backend_simulator = "backend_simulator" backend = "ibmq_montreal" qubits = 4 trotter_layer = QuantumCircuit(qubits) trotter_layer.rx(0.1, range(qubits)) trotter_layer.cx(0, 1) trotter_layer.cx(2, 3) trotter_layer.rz(-0.2, [1, 3]) trotter_layer.cx(0, 1) trotter_layer.cx(2, 3) trotter_layer.cx(1, 2) trotter_layer.rz(-0.2, 2) trotter_layer.cx(1, 2) num_steps = 6 trotter_circuit_list = [] for i in range(1, num_steps): trotter_circuit = QuantumCircuit(qubits) for _ in range(i): trotter_circuit = trotter_circuit.compose(trotter_layer) trotter_circuit_list.append(trotter_circuit) print(f'Trotter circuit with {i} Trotter steps`) display(trotter_circuit.draw(fold=-1)) obs = SparsePauliOp("Z"*qubits) obs_list = [obs]*len(trotter_circuit_list) options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 0 # No mitigation with Session(service=service, backend=backend_simulator) as session: estimator_sim = Estimator(session=session, options=options) job_sim = estimator_sim.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_sim.job_id) print(job_sim.result()) expvals_ideal = job_sim.result().values expvals_ideal_variance = [metadata['variance']/metadata['shots'] for metadata in job_sim.result().metadata] std_error_ideal = np.sqrt(expvals_ideal_variance) options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 0 # No error mitigation with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job.job_id) print(job.result()) expvals_unmit = job.result().values expvals_unmit_variance = [metadata['variance']/metadata['shots'] for metadata in job.result().metadata] std_error_unmit = np.sqrt(expvals_unmit_variance) options = Options() options.execution.shots = 1000 options.optimization_level = 3 # Dynamical decoupling options.resilience_level = 0 # No error mitigation with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_dd = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_dd.job_id) print(job_dd.result()) expvals_unmit_dd = job_dd.result().values expvals_unmit_dd_variance = [metadata['variance']/metadata['shots'] for metadata in job_dd.result().metadata] std_error_dd = np.sqrt(expvals_unmit_dd_variance) plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_dd, std_error_dd, fmt = 'o', linestyle = '-', capsize=4, c='blue', label='Dynamical decoupling') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.resilience_level = 1 # T-REx options.optimization_level = 0 # No optimization options.execution.shots = 1000 with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_trex = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_trex.job_id) print(job_trex.result()) expvals_unmit_trex = job_trex.result().values expvals_unmit_trex_variance = [metadata['variance']/metadata['shots'] for metadata in job_trex.result().metadata] std_error_trex = np.sqrt(expvals_unmit_trex_variance) plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 2 # ZNE with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_zne = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_zne.job_id) print(job_zne.result()) expvals_unmit_zne = job_zne.result().values # Standard error: coming soon! plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE') plt.xlabel('No. Trotter Steps') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() def interim_results_callback(job_id, result): now = datetime.datetime.now() print(now, "*** Callback ***", result, "\n") options = Options() options.optimization_level = 0 # No optimization options.execution.shots = 100 options.resilience_level = 3 # PEC options.environment.callback = interim_results_callback with Session(service=service, backend=backend) as session: estimator_pec = Estimator(session=session, options=options) job_pec = estimator_pec.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_pec.job_id) expvals_pec = job_pec.result().values std_error_pec = [metadata['standard_error'] for metadata in job_pec.result().metadata] plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() print(job_pec.result()) pec_metadata = job_pec.result().metadata fig, ax = plt.subplots() fig.subplots_adjust(right=0.75) twin1 = ax.twinx() twin2 = ax.twinx() twin3 = ax.twinx() twin2.spines.right.set_position(("axes", 1.2)) twin3.spines.right.set_position(("axes", 1.4)) p1, = ax.plot(range(1, num_steps), [m["total_mitigated_layers"] for m in pec_metadata] , "b-", label="Total mitigated layers") p2, = twin1.plot(range(1, num_steps), [m["sampling_overhead"] for m in pec_metadata], "r-", label="Sampling overhead") p3, = twin2.plot(range(1, num_steps), [m["samples"] for m in pec_metadata], "g-", label="Samples") p4, = twin3.plot(range(1, num_steps), [m["shots"] for m in pec_metadata], "c-", label="Shots") ax.set_ylim(0, 20) twin1.set_ylim(0, 2.8) twin2.set_ylim(0, 300) twin3.set_ylim(0, 35000) ax.set_xlabel("No. Trotter Steps") ax.set_ylabel("Total mitigated layers") twin1.set_ylabel("Sampling overhead") twin2.set_ylabel("Samples") twin3.set_ylabel("Shots") ax.yaxis.label.set_color(p1.get_color()) twin1.yaxis.label.set_color(p2.get_color()) twin2.yaxis.label.set_color(p3.get_color()) twin3.yaxis.label.set_color(p4.get_color()) tkw = dict(size=4, width=1.5) ax.tick_params(axis='y', colors=p1.get_color(), **tkw) twin1.tick_params(axis='y', colors=p2.get_color(), **tkw) twin2.tick_params(axis='y', colors=p3.get_color(), **tkw) twin3.tick_params(axis='y', colors=p4.get_color(), **tkw) plt.xticks([1, 2, 3, 4, 5]) ax.legend(handles=[p1, p2, p3, p4]) plt.title('PEC metadata') plt.show() from matplotlib.pyplot import figure plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx') plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE') plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC') plt.title('Trotter circuits expectation value') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.execution.shots = 1000 options.optimization_level = 0 # no optimization options.resilience_level = 2 # ZNE options.resilience.noise_factors = [1, 2, 3, 4] options.resilience.noise_amplifier = "LocalFoldingAmplifier" options.resilience.extrapolator = "QuadraticExtrapolator" with Session(service=service, backend='ibmq_montreal') as session: estimator = Estimator(session=session, options=options) job_zne_options = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_zne_options.job_id) print(job_zne_options.result()) from qiskit.tools import jupyter %qiskit_version_table %qiskit_copyright
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors=scale_factors, fac_type="lin") target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/MetalKyubit/Quantum-Algorithms-in-Qiskit
MetalKyubit
# initialization import numpy as np # importing Qiskit from qiskit import * # import basic plot tools from qiskit.visualization import plot_histogram from qiskit.providers.fake_provider import FakeJakarta from qiskit.providers.fake_provider import FakeNairobi #defining a function to create the Grovers Algorithm circuit. Function takes in the oracle and number or qubits # and ouputs the circuit def Grover_function(oracle,n): # n input qubits qc = QuantumCircuit(n,n) # creating superposition of all the inputs for i in range(n): qc.h(i) qc.barrier() # Grovers function is implemented for m times as it is basically a rotation function applied for m times. # m calculated by finding approximately the angle of the total superposition with the "B" set and the number #of times the superposition has to be rotated by twice of that angle to reach the "A" state. m=int(np.round(np.pi*np.sqrt(2**n)/4 - 0.5)) for i in range(m): # applying the oracle that has the funciton encoded in it to the circuit qc.append(oracle, range(n)) qc.barrier() # applying the second set of hadamard gates for i in range(n): qc.h(i) # implementing the Z_0 gate (all x followed by one hadamard followed by mcx #followed by hadamard followed by all x) for i in range(n): qc.x(i) qc.h(0) qubit=[] for i in range(n-1): qubit.append(i+1) qc.mcx(qubit, 0) qc.h(0) for i in range(n): qc.x(i) #applying the hadamard gates again to collapse the superposition to one state that has the final result #encoded in it. for i in range(n): qc.h(i) # measuring the input qubits to find the final result. qc.measure(range(n),range(n)) return (qc) # Function for generating a general grover's oracle (Zf) for n qubits and # inp: input string such that f(inp) = 1 def Grover_oracle(n, inp): cir = QuantumCircuit(n) # Applying X gate where ever the string is zero to convert the whole string to n 1's and then applying # controlled z gate to phase flip the particular state for i in range(n): if inp[i]=='0': cir.x(n-i-1) # Multiple controlled Z gate using MCX cir.h(0) cir.mcx([i for i in range(1,n)], 0) cir.h(0) # Applying X gates to reverse the effect of above applied X gates for i in range(len(inp)): if inp[i]=='0': cir.x(n-i-1) return cir # Testing the algorithm for n=3 and f('101') = 1 n = 3 oracle = Grover_oracle(n, '101') oracle.draw('mpl') q1 = Grover_function(oracle, n) q1.draw('mpl') # Running on non-noisy simulator backend = Aer.get_backend('aer_simulator') job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Running on noisy simulator backend = FakeJakarta() job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Running on noisy simulator backend = FakeNairobi() job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Testing the algorithm n = 5 oracle = Grover_oracle(n, '10101') oracle.draw('mpl') q1 = Grover_function(oracle, n) q1.draw('mpl') # Running on non-noisy simulator backend = Aer.get_backend('aer_simulator') job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Running on noisy simulator backend = FakeJakarta() job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts) # Running on noisy simulator backend = FakeNairobi() job = execute(q1,backend) results = job.result() counts = results.get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.qasm3 program = """ OPENQASM 3.0; include "stdgates.inc"; input float[64] a; qubit[3] q; bit[2] mid; bit[3] out; let aliased = q[0:1]; gate my_gate(a) c, t { gphase(a / 2); ry(a) c; cx c, t; } gate my_phase(a) c { ctrl @ inv @ gphase(a) c; } my_gate(a * 2) aliased[0], q[{1, 2}][0]; measure q[0] -> mid[0]; measure q[1] -> mid[1]; while (mid == "00") { reset q[0]; reset q[1]; my_gate(a) q[0], q[1]; my_phase(a - pi/2) q[1]; mid[0] = measure q[0]; mid[1] = measure q[1]; } if (mid[0]) { let inner_alias = q[{0, 1}]; reset inner_alias; } out = measure q; """ circuit = qiskit.qasm3.loads(program) circuit.draw("mpl")
https://github.com/jeevesh2002/QuantumKatasQiskit
jeevesh2002
%kata T1_ApplyY operation ApplyY (q : Qubit) : Unit is Adj+Ctl { Y(q); // As simple as that } %kata T2_GlobalPhaseI operation GlobalPhaseI (q : Qubit) : Unit is Adj+Ctl { Z(q); Y(q); X(q); } %kata T3_SignFlipOnZero operation SignFlipOnZero (q : Qubit) : Unit is Adj+Ctl { X(q); // Flip the qubit Z(q); // Apply negative phase on the |1> state X(q); // Flip the qubit back } %kata T4_PrepareMinus operation PrepareMinus (q : Qubit) : Unit is Adj+Ctl { X(q); // Turn |0> into |1> H(q); // Turn |1> into |-> } %kata T5_ThreeQuatersPiPhase operation ThreeQuatersPiPhase (q : Qubit) : Unit is Adj+Ctl { S(q); T(q); } %kata T6_PrepareRotatedState open Microsoft.Quantum.Math; operation PrepareRotatedState (alpha : Double, beta : Double, q : Qubit) : Unit is Adj+Ctl { Rx(2.0 * ArcTan2(beta, alpha), q); } %kata T7_PrepareArbitraryState open Microsoft.Quantum.Math; operation PrepareArbitraryState (alpha : Double, beta : Double, theta : Double, q : Qubit) : Unit is Adj+Ctl { Ry(2.0 * ArcTan2(beta, alpha), q); // Step 1 R1(theta, q); // Step 2 }
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import time import warnings import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals from qiskit_machine_learning.circuit.library import RawFeatureVector from qiskit_machine_learning.neural_networks import SamplerQNN algorithm_globals.random_seed = 42 def ansatz(num_qubits): return RealAmplitudes(num_qubits, reps=5) num_qubits = 5 circ = ansatz(num_qubits) circ.decompose().draw("mpl") def auto_encoder_circuit(num_latent, num_trash): qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True) circuit.barrier() auxiliary_qubit = num_latent + 2 * num_trash # swap test circuit.h(auxiliary_qubit) for i in range(num_trash): circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i) circuit.h(auxiliary_qubit) circuit.measure(auxiliary_qubit, cr[0]) return circuit num_latent = 3 num_trash = 2 circuit = auto_encoder_circuit(num_latent, num_trash) circuit.draw("mpl") def domain_wall(circuit, a, b): # Here we place the Domain Wall to qubits a - b in our circuit for i in np.arange(int(b / 2), int(b)): circuit.x(i) return circuit domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5) domain_wall_circuit.draw("mpl") ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") # Here we define our interpret for our SamplerQNN def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=[], weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_domain(params_values): probabilities = qnn.forward([], params_values) # we pick a probability of getting 1 as the output of the network cost = np.sum(probabilities[:, 1]) # plotting part clear_output(wait=True) objective_func_vals.append(cost) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() return cost opt = COBYLA(maxiter=150) initial_point = algorithm_globals.random.random(ae.num_parameters) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(cost_func_domain, initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(domain_wall_circuit) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) test_qc.draw("mpl") test_qc = test_qc.assign_parameters(opt_result.x) domain_wall_state = Statevector(domain_wall_circuit).data output_state = Statevector(test_qc).data fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2) print("Fidelity of our Output State with our Input State: ", fidelity.real) def zero_idx(j, i): # Index for zero pixels return [ [i, j], [i - 1, j - 1], [i - 1, j + 1], [i - 2, j - 1], [i - 2, j + 1], [i - 3, j - 1], [i - 3, j + 1], [i - 4, j - 1], [i - 4, j + 1], [i - 5, j], ] def one_idx(i, j): # Index for one pixels return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]] def get_dataset_digits(num, draw=True): # Create Dataset containing zero and one train_images = [] train_labels = [] for i in range(int(num / 2)): # First we introduce background noise empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the one for i, j in one_idx(2, 6): empty[j][i] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(1) if draw: plt.title("This is a One") plt.imshow(train_images[-1]) plt.show() for i in range(int(num / 2)): empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the zero for k, j in zero_idx(2, 6): empty[k][j] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(0) if draw: plt.imshow(train_images[-1]) plt.title("This is a Zero") plt.show() train_images = np.array(train_images) train_images = train_images.reshape(len(train_images), 32) for i in range(len(train_images)): sum_sq = np.sum(train_images[i] ** 2) train_images[i] = train_images[i] / np.sqrt(sum_sq) return train_images, train_labels train_images, __ = get_dataset_digits(2) num_latent = 3 num_trash = 2 fm = RawFeatureVector(2 ** (num_latent + num_trash)) ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(fm, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=fm.parameters, weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_digits(params_values): probabilities = qnn.forward(train_images, params_values) cost = np.sum(probabilities[:, 1]) / train_images.shape[0] # plotting part clear_output(wait=True) objective_func_vals.append(cost) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() return cost with open("12_qae_initial_point.json", "r") as f: initial_point = json.load(f) opt = COBYLA(maxiter=150) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") # Test test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(fm) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) # sample new images test_images, test_labels = get_dataset_digits(2, draw=False) for image, label in zip(test_images, test_labels): original_qc = fm.assign_parameters(image) original_sv = Statevector(original_qc).data original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4)) param_values = np.concatenate((image, opt_result.x)) output_qc = test_qc.assign_parameters(param_values) output_sv = Statevector(output_qc).data output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4)) fig, (ax1, ax2) = plt.subplots(1, 2) ax1.imshow(original_sv) ax1.set_title("Input Data") ax2.imshow(output_sv) ax2.set_title("Output Data") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/dnnagy/qintro
dnnagy
import math import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.visualization import plot_bloch_multivector from qiskit.visualization import plot_bloch_vector from qiskit.visualization import plot_histogram qbackend = Aer.get_backend('qasm_simulator') sbackend = Aer.get_backend('statevector_simulator') ubackend = Aer.get_backend('unitary_simulator') qiskit.__version__ qreg = QuantumRegister(1) creg = ClassicalRegister(1) circ = QuantumCircuit(qreg,creg) circ.measure(0,0) circ.draw(output='mpl') job = execute( circ, qbackend, shots=1000 ) counts = job.result().get_counts() fig, ax = plt.subplots() plot_histogram(counts, ax = ax) n_shots=1000 measure_psi = QuantumCircuit(1,1) amps_psi = (1.0/np.sqrt(2))*np.array([1.0+0.0j, 0.0+1.0j]) measure_psi.initialize(amps_psi, 0) measure_psi.measure(0,0) job_psi = execute( measure_psi, qbackend, shots=n_shots ) counts_psi = job_psi.result().get_counts() print("counts_psi =", counts_psi) measure_phi = QuantumCircuit(1,1) amps_phi = (1.0/np.sqrt(2))*np.array([0.0+1.0j, -1.0+0.0j]) measure_phi.initialize(amps_phi, 0) measure_phi.measure(0,0) job_phi = execute( measure_phi, qbackend, shots=n_shots ) counts_phi = job_phi.result().get_counts() print("counts_phi =", counts_phi) fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,5), dpi=96) plot_histogram(counts_psi, ax=axes[0]) axes[0].set_title(r'$\psi$') plot_histogram(counts_phi, ax=axes[1]) axes[1].set_title(r'$\phi$'); n_shots=10000 measure_psi = QuantumCircuit(1,1) amps_psi = [np.sqrt(0.45), np.sqrt(0.55)] measure_psi.initialize(amps_psi, 0) measure_psi.measure(0,0) job_psi = execute( measure_psi, qbackend, shots=n_shots ) counts_psi = job_psi.result().get_counts() print("counts_psi =", counts_psi) measure_phi = QuantumCircuit(1,1) amps_phi = [np.sqrt(0.5), np.sqrt(0.5)] measure_phi.initialize(amps_phi, 0) measure_phi.measure(0,0) job_phi = execute( measure_phi, qbackend, shots=n_shots ) counts_phi = job_phi.result().get_counts() print("counts_phi =", counts_phi) fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,5), dpi=96) plot_histogram(counts_psi, ax=axes[0]) axes[0].set_title(r'$\psi$') plot_histogram(counts_phi, ax=axes[1]) axes[1].set_title(r'$\phi$'); qreg = QuantumRegister(1) creg = ClassicalRegister(1) circ = QuantumCircuit(qreg,creg) # Apply gates circ.x(0) # Measure circ.barrier(qreg) circ.measure(0,0) circ.draw(output='mpl') job = execute( circ, qbackend, shots=10000 ) state = job.result().get_counts() print("Counts:", state) plot_histogram(state) qreg = QuantumRegister(1) creg = ClassicalRegister(1) circ = QuantumCircuit(qreg,creg) # Apply gates circ.h(0) # Measure circ.barrier(qreg) circ.measure(0,0) circ.draw(output='mpl') job = execute( circ, qbackend, shots=10000 ) state = job.result().get_counts() print("Counts:", state) plot_histogram(state) qreg = QuantumRegister(1) creg = ClassicalRegister(1) circ = QuantumCircuit(qreg,creg) # Apply gates circ.z(0) circ.x(0) circ.h(0) # Measure circ.barrier(qreg) circ.measure(0,0) circ.draw(output='mpl') job = execute( circ, qbackend, shots=10000 ) state = job.result().get_counts() print("Counts:", state) plot_histogram(state) ps = np.array([0.1, 0.2, .5, .2]) amplitudes = np.sqrt(ps) qreg = QuantumRegister(2) creg = ClassicalRegister(2) circ = QuantumCircuit(qreg,creg) circ.initialize(amplitudes, qreg) circ.measure(qreg,creg) circ.draw(output='mpl') job = execute( circ, qbackend, shots=10000 ) state = job.result().get_counts() print("Counts:", state) plot_histogram(state) # Random 4-qubit state ps = np.random.randint(0, 255, 16) ps = ps/ps.sum() amplitudes = np.sqrt(ps) # Setup qreg = QuantumRegister(4) creg = ClassicalRegister(4) circ = QuantumCircuit(qreg,creg) circ.initialize(amplitudes, qreg) # Measure m = QuantumCircuit(qreg, creg) m.measure(qreg, creg) job = execute( circ+m, qbackend, shots=10000 ) counts = job.result().get_counts() m.draw(output='mpl') plot_histogram(counts) qreg = QuantumRegister(2) creg = ClassicalRegister(2) circ = QuantumCircuit(qreg,creg) circ.x(0) circ.h(0) circ.cx(0,1) circ.barrier(qreg) circ.measure(qreg,creg) circ.draw(output='mpl') job = execute( circ, qbackend, shots=10000 ) counts = job.result().get_counts() plot_histogram(counts) # Create the quantum circuit with 2 qubits and 2 classical bits qc = QuantumCircuit(2, 2) qc.barrier() # First generate the entangled pair between Alice and Bob (Remember: Hadamard followed by CX generates a Bell pair) # At this point, qubit 1 goes to Bob and qubit 2 goes to Alice qc.h(0) qc.cx(0, 1) qc.barrier() # Next, Alice encodes her message. First, we need to prepare the state Alice will like to send, # In this tutorial, Alice is sending 11: qc.x(0) qc.z(0) qc.barrier() # Alice then sends her qubit to Bob. # After recieving qubit 0, Bob applies the recovery protocol: qc.cx(0, 1) qc.h(0) # Let's take a measurement to see which classical bit of information Bob receives: qc.barrier() qc.measure(0, 0) qc.measure(1, 1) # Draw our output qc.draw(output = "mpl") job = execute( qc, qbackend, shots=10000 ) counts = job.result().get_counts() plot_histogram(counts) q1 = QuantumCircuit(1,1) q1.x(0) q1.measure(0,0) q1.draw(output = 'mpl') q2 = QuantumCircuit(1,1) q2.h(0) q2.measure(0,0) q2.draw(output = 'mpl') q = q1 + q2 q.draw(output = 'mpl')
https://github.com/bertolinocastro/quantum-computing-algorithms
bertolinocastro
# A Quantum Circuit to Construct All Maximal Cliques Using Grover’s Search Algorithm ## Chu Ryang Wie ### DOI: https://arxiv.org/abs/1711.06146v2 import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt from qiskit import * # IBMQ.load_account() from qiskit.visualization import * n = 3 # size of network psi = QuantumRegister(n, name='psi') # cliques states data = QuantumRegister(n**2, name='data') # data A+I states ancl = QuantumRegister(n**2, name='ancl') # ancilla states cpsi = ClassicalRegister(n, name='cpsi') # classical register for measurement cdata = ClassicalRegister(n**2, name='cdata') # classical register for measurement cancl = ClassicalRegister(n**2, name='cancl') # classical register for measurement #extra_ancl = QuantumRegister(n**2, name='extra_ancl') qc = QuantumCircuit(psi, data, ancl, cpsi, cdata, cancl, name='maximal cliques') import numpy as np A = np.array([ # creating adjacency matrix [0,1,0], [1,0,1], [0,1,0] ], dtype=np.int) AI = A+ np.eye(n, dtype=np.int) # setting network structure on data qubits for ij, cij in enumerate(AI.flatten()): if cij: qc.x(data[ij]) # putting cliques on uniform superposition for j in range(n): qc.h(psi[j]) def V(): for j in range(n): for i in range(n): # applying 'intersect operator' as defined in paper qc.barrier() # standard toffoli qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # toffoli variant - 1st ctrl qbit works when 0 qc.x(psi[j]) qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # toffoli variant - 1st & 2nd ctrl qbit work when 0 qc.x(data[j*n+i]) qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # undoing NOT operations qc.x(psi[j]) qc.x(data[j*n+i]) def W(): for j in range(n): # trying to use multi-controlled toffoli gate available in qiskit (not sure if it works) #qc.mct(ancl[j::n], psi[j], extra_ancl) #QuantumCircuit.mct(q_controls, q_target, q_ancilla, mode='basic') qc.barrier() qc.mct(ancl[j::n], psi[j], None, mode='noancilla') def flip_ket_0(): for j in range(n): qc.x(psi[j]) qc.h(psi[n-1]) qc.barrier() qc.mct(psi[:-1], psi[-1], None, mode='noancilla') qc.barrier() qc.h(psi[n-1]) for j in range(n): qc.x(psi[j]) def O(): qc.barrier() V() qc.barrier() W() qc.barrier() flip_ket_0() qc.barrier() W() qc.barrier() V() def G(): qc.barrier() for j in range(n): qc.h(psi[j]) qc.barrier() for j in range(n): qc.x(psi[j]) qc.barrier() qc.h(psi[-1]) qc.barrier() qc.mct(psi[:-1],psi[-1],None,mode='noancilla') qc.barrier() qc.h(psi[-1]) qc.barrier() for j in range(n): qc.x(psi[j]) qc.barrier() for j in range(n): qc.h(psi[j]) O() G() qc.barrier() qc.measure(psi, cpsi) qc.measure(data, cdata) qc.measure(ancl, cancl) fig = circuit_drawer(qc, output='mpl', filename='circuit.pdf', fold=300) #fig res = execute(qc, Aer.get_backend('qasm_simulator'), shots=4096).result() print(res) print(res.get_counts()) plot_histogram(res.get_counts()) # Running on IBMQ Experience # saving account credentials first #IBMQ.save_account('MY_TOKEN_ID') # loading IBMQ session provider = IBMQ.load_account() backend = provider.backends(simulator=True,operational=True)[0] res = execute(qc, backend, shots=8192).result() plot_histogram(res.get_counts()) # TODO: create circuit for n=2 network and test it on melbourne qpu.
https://github.com/Seanaventure/HighErrorRateRouting
Seanaventure
import matplotlib.pyplot as plt import networkx as nx import qiskit import HERR from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes.routing import BasicSwap from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.converters import dag_to_circuit from math import pi from qiskit.compiler import transpile, assemble from qiskit.providers.aer.noise import NoiseModel import qiskit.providers.aer.noise as noise from qiskit.tools.visualization import dag_drawer import random from qiskit.circuit.instruction import Instruction from qiskit.transpiler.passes.routing import * import time def countTwoQubitGates(transpiledCircuit): num = 0 for gate in transpiledCircuit.data: # print(type(gate[0])) if issubclass(type(gate[0]), Instruction): if gate[0].name == "cx": num += 1 return num couplingList = list() for i in range(3): for j in range(3): if i is not j: couplingList.append([i, j]) squareCouplingList = list() for i in range(4): for j in range(4): if i is not j: if abs(i-j) == 1: squareCouplingList.append([i, j]) squareCouplingList.append(([0, 3])) squareCouplingList.append(([3, 0])) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_lima') basis_gates = backend.configuration().basis_gates squareCouplingMap = CouplingMap(squareCouplingList) couplingMap = CouplingMap(couplingList) qcHERR = QuantumCircuit(4) qcHERR.x(0) qcHERR.x(1) qcHERR.ccx(0, 1, 2) qcHERR.measure_all() qcHERR = qcHERR.decompose() nonHERR = QuantumCircuit(4) nonHERR.x(0) nonHERR.x(1) nonHERR.ccx(0, 1, 2) nonHERR.measure_all() circDag = circuit_to_dag(qcHERR) targetCouplingMap = squareCouplingMap bSwap = BasicSwap(targetCouplingMap) baseTime = time.perf_counter() bSwap.run(circDag) bSwapTime = time.perf_counter() - baseTime sabreSwap = SabreSwap(targetCouplingMap) baseTime = time.perf_counter() sabreSwap.run(circDag) sabreSwapTime = time.perf_counter() - baseTime stochasticSwap = StochasticSwap(targetCouplingMap) baseTime = time.perf_counter() stochasticSwap.run(circDag) stochasticSwapTime = time.perf_counter() - baseTime lookAheadSwap = LookaheadSwap(targetCouplingMap) baseTime = time.perf_counter() lookAheadSwap.run(circDag) lookAheadSwapTime = time.perf_counter() - baseTime for i in range(200): # Create a noise model for the simulations noise_model = noise.NoiseModel() errorRates = list() qiskitErrors = list() for i in range(len(squareCouplingList)//2): errorRates.append(random.randrange(1, 10, 1)/100.0) qiskitErrors.append(noise.depolarizing_error(errorRates[i], 2)) edges = targetCouplingMap.get_edges() uniqueEdges = set() for edge in edges: uniqueEdges.add(tuple(sorted(edge))) noiseGraph = nx.Graph() noiseGraph.add_nodes_from([0, 7]) errorIdex = 0 for edge in uniqueEdges: noise_model.add_quantum_error(qiskitErrors[errorIdex], ['cx'], edge) noiseGraph.add_edge(edge[0], edge[1], weight=1-errorRates[errorIdex]) errorIdex += 1 herr = HERR.HERR(targetCouplingMap, noiseGraph) basSwap = BasicSwap(targetCouplingMap) #print(gridCouplingMap) # Run HERR baseTime = time.perf_counter() HERRRes = herr.run(circDag) HERRSwapTime = time.perf_counter() - baseTime updatedCirc = dag_to_circuit(HERRRes) print(str(HERRSwapTime) + " " + str(bSwapTime) + " " + str(sabreSwapTime) + " " + str(stochasticSwapTime) + " " + str(lookAheadSwapTime))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
#importing array and useful math functions import numpy as np #importing circuits and registers from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister #importing backends and running environment from qiskit import BasicAer, execute
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford, random_clifford qc = QuantumCircuit(3) cliff = random_clifford(2) qc.append(cliff, [0, 1]) qc.ccx(0, 1, 2) qc.draw('mpl')
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
import sys import os current_dir = os.getcwd() sys.path.append(current_dir) from quantum_circuit import QuantumCircuit # import qiskit.providers.fake_provider from qiskit.transpiler import CouplingMap import qiskit_ibm_runtime.fake_provider from Backend.backend import Backend class FakeBackend(Backend): def __init__(self, backend_name : str) -> None: self.backend = FakeBackend.get_ibm_fake_backend(backend_name=backend_name) @staticmethod def get_ibm_fake_backend_name_list() -> list[str]: ibm_dir = dir(qiskit_ibm_runtime.fake_provider) return [val for val in ibm_dir if '__' not in val and 'Fake' in val] @staticmethod def get_ibm_fake_backend(backend_name : str): try: return getattr(qiskit_ibm_runtime.fake_provider, backend_name)() except: pass fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: if backend.name == backend_name: return backend except: pass return None @staticmethod def get_ibm_fake_backend_names_with_limit(min_qubit : int = 1, max_qubit: int = float('inf')) -> list[str]: limited_backend = [] fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: num_qubit = backend.num_qubits if num_qubit >= min_qubit and num_qubit <= max_qubit: limited_backend.append(backend.name) except: pass return limited_backend if __name__ == "__main__": print(FakeBackend.get_ibm_fake_backend_name_list()) backend = FakeBackend('fake_auckland') qc = QuantumCircuit(2) qc.x(0) qc.h(1) qc.measure_all() print(qc.draw()) job = backend.run(qc) print(job.result()) qc_transpile = backend.traspile_qiskit(qc)[0] print(qc_transpile.draw()) job = backend.run(qc_transpile) print(job.result())
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
1 + 1 a = 1 b = 0.5 a + b an_integer = 42 # Just an integer a_float = 0.1 # A non-integer number, up to a fixed precision a_boolean = True # A value that can be True or False a_string = '''just enclose text between two 's, or two "s, or do what we did for this string''' # Text none_of_the_above = None # The absence of any actual value or variable type a_list = [0,1,2,3] a_list = [ 42, 0.5, True, [0,1], None, 'Banana' ] a_list[0] a_tuple = ( 42, 0.5, True, [0,1], None, 'Banana' ) a_tuple[0] a_list[5] = 'apple' print(a_list) a_tuple[5] = 'apple' a_list.append( 3.14 ) print(a_list) a_dict = { 1:'This is the value, for the key 1', 'This is the key for a value 1':1, False:':)', (0,1):256 } a_dict['This is the key for a value 1'] a_dict['new key'] = 'new_value' for j in range(5): print(j) for j in a_list: print(j) for key in a_dict: value = a_dict[key] print('key =',key) print('value =',value) print() if 'strawberry' in a_list: print('We have a strawberry!') elif a_list[5]=='apple': print('We have an apple!') else: print('Not much fruit here!') import numpy numpy.sin( numpy.pi/2 ) import numpy as np np.sin( np.pi/2 ) from numpy import * sin( pi/2 ) def do_some_maths ( Input1, Input2 ): the_answer = Input1 + Input2 return the_answer x = do_some_maths(1,72) print(x) def add_sausages ( input_list ): if 'sausages' not in input_list: input_list.append('sausages') print('List before the function') print(a_list) add_sausages(a_list) # function called without an output print('\nList after the function') print(a_list) import random for j in range(5): print('* Results from sample',j+1) print('\n Random number from 0 to 1:', random.random() ) print("\n Random choice from our list:", random.choice( a_list ) ) print('\n')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
#!/usr/bin/env python # coding: utf-8 # In[1]: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') # In[2]: from qiskit import IBMQ from qiskit.providers.ibmq.visualization import iplot_gate_map IBMQ.load_account() provider = IBMQ.get_provider(group='open', project='main') backend = provider.get_backend('ibmq_vigo') iplot_gate_map(backend, as_widget=True)
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
%load_ext autoreload %autoreload 2 import qiskit_metal as metal from qiskit_metal import designs, draw from qiskit_metal import MetalGUI, Dict design = designs.DesignPlanar() design.overwrite_enabled = True gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket q1options = dict( connection_pads=dict( # pin connectors a = dict(loc_W=+1,loc_H=+1), b = dict(loc_W=-1,loc_H=+1), c = dict(loc_W=+1,loc_H=-1), d = dict(loc_W=-1,loc_H=-1) ) ) q1 = TransmonPocket(design, options = q1options) # this line only creates the object in memory and executes its __init__(), but does not "implement" gui.rebuild() # this updates the QComponent tables by running make() gui.autoscale() q1.default_options q1.options design.rename_component(q1.id,'Q1') q1.options.pos_x='-1.5mm' q2 = design.copy_qcomponent(q1, 'Q2') q2.options.pos_x='1.5mm' from qiskit_metal.qlibrary.tlines.meandered import RouteMeander options = Dict( total_length = '8mm', pin_inputs = Dict( start_pin = Dict( component = 'Q1', pin = 'a'), end_pin = Dict( component = 'Q2', pin = 'b')), ) cpw = RouteMeander(design, options=options) gui.rebuild() gui.autoscale() cpw.options.fillet = '90um' cpw.options.lead.start_straight = '90um' gui.rebuild() gui.autoscale() design.net_info design.delete_component('Q2') cpw.delete() design.net_info # from qiskit_metal.qlibrary.user_components.my429_qcomponents import MyQComponent1 import sys sys.path.append('../../resources') from my429_qcomponents import MyQComponent1 myQC = MyQComponent1(design, 'myQC') gui.rebuild() # this is need to actually make() the component gui.autoscale() options = Dict( total_length = '4mm', pin_inputs = Dict( start_pin = Dict( component = 'Q1', pin = 'a'), end_pin = Dict( component = myQC.name, pin = 'in')), fillet = '90um', lead = Dict( start_straight = '90um') ) cpw = RouteMeander(design, options=options) gui.rebuild() gui.autoscale() cpw.delete() myQC.delete() # from qiskit_metal.qlibrary.user_components.my429_qcomponents import MyQComponent2 from my429_qcomponents import MyQComponent2 opt_myqc = Dict(width='1mm', height='0.01mm', pos_x='0.1mm') myQC = MyQComponent2(design, 'myQC', options=opt_myqc) cpw = RouteMeander(design, options=options) gui.rebuild() # this is need to actually make() the component gui.autoscale() myQC.options cpw.delete() myQC.delete() opt_myqc.gap = '8um' opt_myqc.height = '20um' # from qiskit_metal.qlibrary.user_components.my429_qcomponents import MyQComponent4 from my429_qcomponents import MyQComponent4 myQC = MyQComponent4(design, options=opt_myqc) #opt_myqc defined earlier options = Dict( total_length = '4mm', pin_inputs = Dict( start_pin = Dict( component = 'Q1', pin = 'a'), end_pin = Dict( component = myQC.name, #updating this pin = 'in')), fillet = '90um', lead = Dict( start_straight = '90um') ) cpw = RouteMeander(design, options=options) gui.rebuild() # this is need to actually make() the component gui.autoscale() myQC.options
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit import math from qiskit.quantum_info import Statevector qc = QuantumCircuit(3) qc.rx(math.pi/2, 0) qc.ry(math.pi/2, 1) qc.rz(math.pi/2, 2) qc.draw("mpl") state = Statevector.from_instruction(qc) state.draw('bloch')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram import random circ = QuantumCircuit(40, 40) # Initialize with a Hadamard layer circ.h(range(40)) # Apply some random CNOT and T gates qubit_indices = [i for i in range(40)] for i in range(10): control, target, t = random.sample(qubit_indices, 3) circ.cx(control, target) circ.t(t) circ.measure(range(40), range(40)) # Create statevector method simulator statevector_simulator = AerSimulator(method='statevector') # Transpile circuit for backend tcirc = transpile(circ, statevector_simulator) # Try and run circuit statevector_result = statevector_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(statevector_result.success)) print('Why not? {}'.format(statevector_result.status)) # Create extended stabilizer method simulator extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer') # Transpile circuit for backend tcirc = transpile(circ, extended_stabilizer_simulator) extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(extended_stabilizer_result.success)) small_circ = QuantumCircuit(2, 2) small_circ.h(0) small_circ.cx(0, 1) small_circ.t(0) small_circ.measure([0, 1], [0, 1]) # This circuit should give 00 or 11 with equal probability... expected_results ={'00': 50, '11': 50} tsmall_circ = transpile(small_circ, extended_stabilizer_simulator) result = extended_stabilizer_simulator.run( tsmall_circ, shots=100).result() counts = result.get_counts(0) print('100 shots in {}s'.format(result.time_taken)) plot_histogram([expected_results, counts], legend=['Expected', 'Extended Stabilizer']) # Add runtime options for extended stabilizer simulator opts = {'extended_stabilizer_approximation_error': 0.03} reduced_error = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() reduced_error_counts = reduced_error.get_counts(0) print('100 shots in {}s'.format(reduced_error.time_taken)) plot_histogram([expected_results, reduced_error_counts], legend=['Expected', 'Extended Stabilizer']) print("The circuit above, with 100 shots at precision 0.03 " "and default mixing time, needed {}s".format(int(reduced_error.time_taken))) opts = { 'extended_stabilizer_approximation_error': 0.03, 'extended_stabilizer_mixing_time': 100 } optimized = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken)) # We set these options here only to make the example run more quickly. opts = {'extended_stabilizer_mixing_time': 100} multishot = extended_stabilizer_simulator.run( tcirc, shots=100, **opts).result() print("100 shots took {} s".format(multishot.time_taken)) opts = { 'extended_stabilizer_measure_sampling': True, 'extended_stabilizer_mixing_time': 100 } measure_sampling = extended_stabilizer_simulator.run( circ, shots=100, **opts).result() print("With the optimization, 100 shots took {} s".format(result.time_taken)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from IPython.core.display import display print("Ch 4: Upside down quantum coin toss") print("-----------------------------------") qc = QuantumCircuit(1, 1) initial_vector = [0.+0.j, 1.+0.j] qc.initialize(initial_vector,0) #qc.x(0) qc.h(0) qc.measure(0, 0) print(qc) #display(qc.draw()) backend = Aer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1).result().get_counts(qc) display(plot_histogram(counts))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting # the qubits in a GHZ state. circ.cx(0, 2) circ.draw('mpl') from qiskit.quantum_info import Statevector # Set the intial state of the simulator to the ground state using from_int state = Statevector.from_int(0, 2**3) # Evolve the state by the quantum circuit state = state.evolve(circ) #draw using latex state.draw('latex') from qiskit.visualization import array_to_latex #Alternative way of representing in latex array_to_latex(state) state.draw('qsphere') state.draw('hinton') from qiskit.quantum_info import Operator U = Operator(circ) # Show the results U.data # Create a Quantum Circuit meas = QuantumCircuit(3, 3) meas.barrier(range(3)) # map the quantum measurement to the classical bits meas.measure(range(3), range(3)) # The Qiskit circuit object supports composition. # Here the meas has to be first and front=True (putting it before) # as compose must put a smaller circuit into a larger one. qc = meas.compose(circ, range(3), front=True) #drawing the circuit qc.draw('mpl') # Adding the transpiler to reduce the circuit to QASM instructions # supported by the backend from qiskit import transpile # Use AerSimulator from qiskit_aer import AerSimulator backend = AerSimulator() # First we have to transpile the quantum circuit # to the low-level QASM instructions used by the # backend qc_compiled = transpile(qc, backend) # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = backend.run(qc_compiled, shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc_compiled) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jwalaQ/my-qiskit-textbook-solutions
jwalaQ
from qiskit_textbook.widgets import plot_bloch_vector_spherical from math import pi,sqrt coords = [0,0,1] plot_bloch_vector_spherical(coords) coords = [pi,0,1] plot_bloch_vector_spherical(coords) coords = [pi/2,0,1] plot_bloch_vector_spherical(coords) coords = [pi/2,-pi/2,1] plot_bloch_vector_spherical(coords) coords = [pi/2,-pi/2,1] plot_bloch_vector_spherical(coords) import qiskit qiskit.__qiskit_version__
https://github.com/xtophe388/QISKIT
xtophe388
import sys, time, getpass try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) except: APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.') from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError from qiskit import available_backends, execute, register, get_backend, compile from qiskit.tools.visualization import plot_histogram from pprint import pprint available_backends() available_backends(compact=False) register(qx_config['APItoken'], qx_config['url']) available_backends() available_backends({'local': False}) available_backends({'local': True}) available_backends({'simulator': True}) available_backends({'simulator': False}) available_backends({'local': False, 'simulator': True}) available_backends({'operational': True, 'simulator': False}) available_backends(lambda x: x.configuration['n_qubits'] > 10 and not x.configuration['simulator']) from qiskit import least_busy least_busy(available_backends({'simulator': False})) backends = [] for backend in available_backends(): backends.append(get_backend(backend)) backends for backend in backends: pprint(backend.status) for backend in backends: pprint(backend.configuration) for backend in backends: pprint(backend.parameters) for backend in backends: pprint(backend.calibration) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.x(qr[1]) circuit.ccx(qr[0], qr[1], qr[2]) circuit.cx(qr[0], qr[1]) circuit.measure(qr, cr) my_backend = get_backend('local_qasm_simulator') qobj = compile(circuit, backend=my_backend, shots=1024) job = my_backend.run(qobj) job.status job.done result = job.result() counts = result.get_counts() print(counts) device_name = least_busy(available_backends({'simulator': False})) my_backend = get_backend(device_name) qobj = compile(circuit, backend=my_backend, shots=1024) job = my_backend.run(qobj) lapse = 0 interval = 10 while not job.done: print('Status @ {} seconds'.format(interval * lapse)) print(job.status) time.sleep(interval) lapse += 1 print(job.status) job.id result = job.result() counts = result.get_counts() print(counts) plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 42 from qiskit.circuit import Parameter from qiskit import QuantumCircuit params1 = [Parameter("input1"), Parameter("weight1")] qc1 = QuantumCircuit(1) qc1.h(0) qc1.ry(params1[0], 0) qc1.rx(params1[1], 0) qc1.draw("mpl") from qiskit.quantum_info import SparsePauliOp observable1 = SparsePauliOp.from_list([("Y" * qc1.num_qubits, 1)]) from qiskit_machine_learning.neural_networks import EstimatorQNN estimator_qnn = EstimatorQNN( circuit=qc1, observables=observable1, input_params=[params1[0]], weight_params=[params1[1]] ) estimator_qnn from qiskit.circuit import ParameterVector inputs2 = ParameterVector("input", 2) weights2 = ParameterVector("weight", 4) print(f"input parameters: {[str(item) for item in inputs2.params]}") print(f"weight parameters: {[str(item) for item in weights2.params]}") qc2 = QuantumCircuit(2) qc2.ry(inputs2[0], 0) qc2.ry(inputs2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[0], 0) qc2.ry(weights2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[2], 0) qc2.ry(weights2[3], 1) qc2.draw(output="mpl") from qiskit_machine_learning.neural_networks import SamplerQNN sampler_qnn = SamplerQNN(circuit=qc2, input_params=inputs2, weight_params=weights2) sampler_qnn estimator_qnn_input = algorithm_globals.random.random(estimator_qnn.num_inputs) estimator_qnn_weights = algorithm_globals.random.random(estimator_qnn.num_weights) print( f"Number of input features for EstimatorQNN: {estimator_qnn.num_inputs} \nInput: {estimator_qnn_input}" ) print( f"Number of trainable weights for EstimatorQNN: {estimator_qnn.num_weights} \nWeights: {estimator_qnn_weights}" ) sampler_qnn_input = algorithm_globals.random.random(sampler_qnn.num_inputs) sampler_qnn_weights = algorithm_globals.random.random(sampler_qnn.num_weights) print( f"Number of input features for SamplerQNN: {sampler_qnn.num_inputs} \nInput: {sampler_qnn_input}" ) print( f"Number of trainable weights for SamplerQNN: {sampler_qnn.num_weights} \nWeights: {sampler_qnn_weights}" ) estimator_qnn_forward = estimator_qnn.forward(estimator_qnn_input, estimator_qnn_weights) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward}. \nShape: {estimator_qnn_forward.shape}" ) sampler_qnn_forward = sampler_qnn.forward(sampler_qnn_input, sampler_qnn_weights) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward}. \nShape: {sampler_qnn_forward.shape}" ) estimator_qnn_forward_batched = estimator_qnn.forward( [estimator_qnn_input, estimator_qnn_input], estimator_qnn_weights ) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward_batched}. \nShape: {estimator_qnn_forward_batched.shape}" ) sampler_qnn_forward_batched = sampler_qnn.forward( [sampler_qnn_input, sampler_qnn_input], sampler_qnn_weights ) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward_batched}. \nShape: {sampler_qnn_forward_batched.shape}" ) estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) estimator_qnn.input_gradients = True sampler_qnn.input_gradients = True estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad.shape}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad.shape}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) observable2 = SparsePauliOp.from_list([("Z" * qc1.num_qubits, 1)]) estimator_qnn2 = EstimatorQNN( circuit=qc1, observables=[observable1, observable2], input_params=[params1[0]], weight_params=[params1[1]], ) estimator_qnn_forward2 = estimator_qnn2.forward(estimator_qnn_input, estimator_qnn_weights) estimator_qnn_input_grad2, estimator_qnn_weight_grad2 = estimator_qnn2.backward( estimator_qnn_input, estimator_qnn_weights ) print(f"Forward output for EstimatorQNN1: {estimator_qnn_forward.shape}") print(f"Forward output for EstimatorQNN2: {estimator_qnn_forward2.shape}") print(f"Backward output for EstimatorQNN1: {estimator_qnn_weight_grad.shape}") print(f"Backward output for EstimatorQNN2: {estimator_qnn_weight_grad2.shape}") parity = lambda x: "{:b}".format(x).count("1") % 2 output_shape = 2 # parity = 0, 1 sampler_qnn2 = SamplerQNN( circuit=qc2, input_params=inputs2, weight_params=weights2, interpret=parity, output_shape=output_shape, ) sampler_qnn_forward2 = sampler_qnn2.forward(sampler_qnn_input, sampler_qnn_weights) sampler_qnn_input_grad2, sampler_qnn_weight_grad2 = sampler_qnn2.backward( sampler_qnn_input, sampler_qnn_weights ) print(f"Forward output for SamplerQNN1: {sampler_qnn_forward.shape}") print(f"Forward output for SamplerQNN2: {sampler_qnn_forward2.shape}") print(f"Backward output for SamplerQNN1: {sampler_qnn_weight_grad.shape}") print(f"Backward output for SamplerQNN2: {sampler_qnn_weight_grad2.shape}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/AsishMandoi/VRP-explorations
AsishMandoi
import numpy as np import pandas as pd class Initializer: def __init__(self, n, a, b): self.n = n self.a = a self.b = b def generate_nodes_and_weight_matrix(self): n = self.n a = self.a b = self.b np.random.seed(100*a + b) x = (np.random.rand(n) - 0.5) * 50 y = (np.random.rand(n) - 0.5) * 50 weight_matrix = np.zeros([n, n]) for i in range(n): for j in range(i+1, n): weight_matrix[i, j] = (x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2 weight_matrix[j, i] = weight_matrix[i, j] return x, y, weight_matrix for i in range(2,16): ### Here, (2,16) could be replaced with the some other range of no. of locations you want. for j in range(10): ### Here, (10) could be replaced with some other number of instcnces you want to generate for a particular no. of locations. initializer = Initializer(i, i, j) x,y,weight_matrix = initializer.generate_nodes_and_weight_matrix() df_x = pd.DataFrame(x) df_y = pd.DataFrame(y) df_wm = pd.DataFrame(weight_matrix) with open ("dataset.csv", 'a') as f: df = pd.concat([df_x, df_y, df_wm], keys = ["x_" + str(i) + '_' + str(j), "y_" + str(i) + '_' + str(j), "wm_" + str(i) + '_' + str(j)]) df.to_csv(f)
https://github.com/biswaroopmukherjee/Quantum-Waddle
biswaroopmukherjee
# Practical Implementation of a Quantum String Matching Algorithm # S. Faro, F.P. Marino, and A. Scardace # QUASAR 2024 %%capture !pip install ibm-cloud-sdk-core==3.18.2 !pip install qiskit==0.45.1 !pip install qiskit-aer==0.13.1 !pip install pylatexenc==2.10 from numpy import log2, sqrt from numpy import pi from qiskit.tools.visualization import plot_histogram from qiskit.circuit.gate import Gate from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit import transpile def run(circuit: QuantumCircuit, shots: int) -> dict: simulator = Aer.get_backend('aer_simulator') compiled_circuit = transpile(circuit, simulator) job = simulator.run(compiled_circuit, shots=shots) result = job.result() return result.get_counts(compiled_circuit) def init_register(bin_str: str) -> QuantumCircuit: data_qr = QuantumRegister(len(bin_str), 'data') qc = QuantumCircuit(data_qr) for i, bit in enumerate(bin_str): if bit == '1': qc.x(data_qr[i]) return qc classical_value = '1001' init_register(classical_value).draw(fold=255) def rot(n: int, s: int) -> QuantumCircuit: y_qr = QuantumRegister(n, 'y') qc = QuantumCircuit(y_qr, name='ROT_' + str(s)) for i in range(1, (int(log2(n)) - int(log2(s)) + 2)): for j in range(int(n / (s * (2**i)))): for q in range(j * s * (2**i), s * (j*2 ** i+1)): qc.swap(n - 1 - (q+s), n - 1 - (q+2 ** (i-1) * s + s)) return qc num_qubits = 8 shift_value = 2 rot(num_qubits, shift_value).draw(fold=255) def rot_gate(n: int, s: int) -> Gate: rot_circuit = rot(n, s) return rot_circuit.to_gate(label='ROT_' + str(s)) def parameterized_rot(n: int) -> QuantumCircuit: j_qr = QuantumRegister(int(log2(n)), 'j') y_qr = QuantumRegister(n, 'y') qc = QuantumCircuit(j_qr, y_qr) for i in range(int(log2(n))): crot = rot_gate(n, 2**i).control(1) qc = qc.compose(crot, [j_qr[i]] + y_qr[:]) return qc num_qubits = 8 parameterized_rot(num_qubits).draw(fold=255) text = '10110001' text_length = len(text) shift_qr = QuantumRegister(int(log2(text_length)), 'shift') text_qr = QuantumRegister(text_length, 'text') output_cr = ClassicalRegister(text_length, 'output_classic') circ = QuantumCircuit(shift_qr, text_qr, output_cr) circ.h(shift_qr) circ.append(init_register(text), text_qr[:]) circ.append(parameterized_rot(text_length), shift_qr[:] + text_qr[:]) circ.measure(text_qr, output_cr) counts = run(circ, 100) plot_histogram(counts, title='Rotate ' + text + ' Leftward in Superposition') def match(m: int) -> QuantumCircuit: x_qr = QuantumRegister(m, 'x') y_qr = QuantumRegister(m, 'y') out_qr = QuantumRegister(1, 'out') qc = QuantumCircuit(x_qr, y_qr, out_qr) for i in range(m): qc.cx(x_qr[i], y_qr[i]) qc.x(y_qr[i]) qc.mcx(y_qr[:], out_qr) for i in reversed(range(m)): qc.x(y_qr[i]) qc.cx(x_qr[i], y_qr[i]) return qc pattern_length = 4 match(pattern_length).draw(fold=255) text = '1011' text_length = len(text) pattern_qr = QuantumRegister(text_length, 'pattern') text_qr = QuantumRegister(text_length, 'text') output_qr = QuantumRegister(1, 'output') output_cr = ClassicalRegister(text_length + 1, 'output_classic') circ = QuantumCircuit(pattern_qr, text_qr, output_qr, output_cr) circ.h(pattern_qr) circ.append(init_register(text), text_qr[:]) circ.append(match(text_length), pattern_qr[:] + text_qr[:] + output_qr[:]) circ.measure(pattern_qr, output_cr[:-1]) circ.measure(output_qr, output_cr[-1]) counts = run(circ, 100) plot_histogram(counts, title='Matching ' + text) def match_gate(m: int) -> Gate: match_circuit = match(m) return match_circuit.to_gate(label='MATCH') def esm(m: int, n: int) -> QuantumCircuit: j_qr = QuantumRegister(int(log2(n)), 'j') x_qr = QuantumRegister(m, 'x') y_qr = QuantumRegister(n, 'y') out = QuantumRegister(1, 'out') qc = QuantumCircuit( j_qr, x_qr, y_qr, out ) qc = qc.compose(parameterized_rot(n), j_qr[:] + y_qr[:]) qc = qc.compose(match_gate(m), x_qr[:] + y_qr[:m] + out[:]) qc = qc.compose(parameterized_rot(n).inverse(), j_qr[:] + y_qr[:]) return qc pattern_length = 2 text_length = 4 esm(pattern_length, text_length).draw(fold=255) def esm_oracle(m: int, n: int): esm_circuit = esm(m, n) return esm_circuit.to_gate(label='ESMO') def diffuser(n: int) -> Gate: qc = QuantumCircuit(n) qc.h(range(n)) qc.x(range(n)) qc.h(n-1) qc.mcx(list(range(n-1)), n-1) qc.h(n-1) qc.x(range(n)) qc.h(range(n)) return qc.to_gate(label='DIFF') def grover(esmo: Gate, t: int, x: str, y: str) -> QuantumCircuit: n = len(y) m = len(x) logn = int(log2(n)) num_iterations = int(pi/4 * sqrt(n/t)) j_qr = QuantumRegister(logn, 'j') x_qr = QuantumRegister(m, 'x') y_qr = QuantumRegister(n, 'y') out_qr = QuantumRegister(2, 'out') out_cr = ClassicalRegister(logn+1, 'c') qc = QuantumCircuit(j_qr, x_qr, y_qr, out_qr, out_cr) qc.h(j_qr) qc.x(out_qr[0]) qc.h(out_qr[0]) qc = qc.compose(init_register(x), x_qr[:]) qc = qc.compose(init_register(y), y_qr[:]) for _ in range(num_iterations): qc = qc.compose(esmo) qc = qc.compose(diffuser(logn)) qc.measure(j_qr, out_cr[:-1]) qc = qc.compose(esmo, j_qr[:] + x_qr[:] + y_qr[:] + [out_qr[1]]) qc.measure(out_qr[1], out_cr[-1]) return qc x = '11' y = '10101100' esmo = esm_oracle(len(x), len(y)) grover(esmo, 1, x, y).draw(fold=255) x = '00' y = '01010101' esmo = esm_oracle(len(x), len(y)) counts = run(grover(esmo, 1, x, y), 100) plot_histogram(counts, title=f'Search for {x} in {y} - 0 occurrence(s)') x = '00' y = '11010011' esmo = esm_oracle(len(x), len(y)) counts = run(grover(esmo, 1, x, y), 100) plot_histogram(counts, title=f'Search for {x} in {y} - 1 occurrence(s)') x = '00' y = '00111001' esmo = esm_oracle(len(x), len(y)) counts = run(grover(esmo, 2, x, y), 100) plot_histogram(counts, title=f'Search for {x} in {y} - 2 occurrence(s)') def search(x: str, y: str) -> int: m = len(x) n = len(y) esmo = esm_oracle(m, n) for t in range(1, int(n/2) + 1): print('Trying with t =', t) results = run(grover(esmo, t, x, y), 1) results = list(results.keys())[0] outcome = int(results[0]) position = int(results[1:], 2) if outcome: return position else: print('Pattern not found in position', position) return -1 x = input('Enter the value of x: ') y = input('Enter the value of y: ') if len(x) > len(y): raise Exception('The length of x must be shorter than the length of y.') if x.count('0') + x.count('1') < len(x): raise Exception('The pattern must be a binary string.') if y.count('0') + y.count('1') < len(y): raise Exception('The text must be a binary string.') print('') position = search(x, y) if position >= 0: print('Pattern occurrence found in position', str(position)) else: print('Pattern occurrence not found.')
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# import the drawing methods from matplotlib.pyplot import plot, figure # draw a figure figure(figsize=(6,6), dpi=60) # draw the origin plot(0,0,'ro') # a point in red color # draw the quantum states as points (in blue color) plot(1,0,'bo') plot(0,1,'bo') plot(-1,0,'bo') plot(0,-1,'bo') # import the drawing methods from matplotlib.pyplot import plot, figure # draw a figure figure(figsize=(6,6), dpi=80) # include our predefined functions %run qlatvia.py # draw the axes draw_axes() # draw the origin plot(0,0,'ro') # a point in red color # draw these quantum states as points (in blue color) plot(1,0,'bo') plot(0,1,'bo') plot(-1,0,'bo') plot(0,-1,'bo') # import the drawing methods from matplotlib.pyplot import figure, arrow # draw a figure figure(figsize=(6,6), dpi=80) # include our predefined functions %run qlatvia.py # draw the axes draw_axes() # draw the quantum states as vectors (in blue color) arrow(0,0,0.92,0,head_width=0.04, head_length=0.08, color="blue") arrow(0,0,0,0.92,head_width=0.04, head_length=0.08, color="blue") arrow(0,0,-0.92,0,head_width=0.04, head_length=0.08, color="blue") arrow(0,0,0,-0.92,head_width=0.04, head_length=0.08, color="blue") # import the drawing methods from matplotlib.pyplot import plot, figure # draw a figure figure(figsize=(6,6), dpi=60) # draw the origin plot(0,0,'ro') # draw the axes draw_axes() # # your solution is here # # include our predefined functions %run qlatvia.py for i in range(100): quantum_state = random_quantum_state() x = quantum_state[0]; y = quantum_state[1]; plot(x,y,'bo') # import the drawing methods from matplotlib.pyplot import plot, figure, arrow # draw a figure figure(figsize=(6,6), dpi=60) # include our predefined functions %run qlatvia.py # draw the axes draw_axes() # draw the origin plot(0,0,'ro') # # your solution is here # for i in range(100): quantum_state = random_quantum_state() x = quantum_state[0]; y = quantum_state[1]; arrow(0,0,x,y,head_width=0.04,head_length=0.08,color="red") # import the drawing methods from matplotlib.pyplot import figure figure(figsize=(6,6), dpi=80) # size of the figure # include our predefined functions %run qlatvia.py # draw axes draw_axes() # draw the unit circle draw_unit_circle() # import the drawing methods from matplotlib.pyplot import figure, text figure(figsize=(6,6), dpi=80) # size of the figure # include our predefined functions %run qlatvia.py # draw axes draw_axes() # randomly determine the points from random import randrange for i in range(5): x = randrange(-100,101)/100 y = randrange(-100,101)/100 string = str(i+1)+". point at ("+str(x)+","+str(y)+")" print(string) text(x,y,string) # %%writefile FILENAME.py # import the drawing methods from matplotlib.pyplot import figure, arrow, text def display_quantum_state(x,y,name): # draw axes draw_axes() # draw the unit circle draw_unit_circle() # get the random quantum state quantum_state = random_quantum_state() x = quantum_state[0]; y = quantum_state[1]; arrow(0,0,x * 0.90,y * 0.90,head_width=0.04,head_length=0.1,color="red") # display the name out of unit circle text(x + 0.1,y + 0.1,name,fontsize=15) # # test your function # # import the drawing methods from matplotlib.pyplot import figure figure(figsize=(6,6), dpi=80) # size of the figure # include our predefined functions %run qlatvia.py # draw axes draw_axes() # draw the unit circle draw_unit_circle() for i in range(6): s = random_quantum_state() display_quantum_state(s[0],s[1],"v"+str(i))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) plot_circuit_layout(new_circ_lv0, backend)
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
bayesian-randomized-benchmarking
#Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt from IPython import display #Import Qiskit classes import qiskit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error #Import the RB Functions import qiskit.ignis.verification.randomized_benchmarking as rb import copy # import the bayesian packages import pymc3 as pm import arviz as az # initialize the Bayesian extension %config InlineBackend.figure_format = 'retina' # Initialize random number generator RANDOM_SEED = 8927 np.random.seed(RANDOM_SEED) az.style.use("arviz-darkgrid") def obtain_priors_and_data_from_fitter(printout = True): m_gates = copy.deepcopy(nCliffs) # We choose the count matrix corresponding to 2 Qubit RB Y = (np.array(rbfit._raw_data[0])*shots).astype(int) # alpha prior and bounds alpha_ref = rbfit._fit[0]['params'][1] alpha_lower = alpha_ref - 5*rbfit._fit[0]['params_err'][1] alpha_upper = alpha_ref + 5*rbfit._fit[0]['params_err'][1] # priors for A anbd B mu_AB = np.delete(rbfit._fit[0]['params'],1) cov_AB=np.delete(rbfit._fit[0]['params_err'],1)**2 # prior for sigmatheta: sigma_theta = 0.004 if printout: print("priors:\nalpha_ref",alpha_ref) print("alpha_lower", alpha_lower, "alpha_upper", alpha_upper) print("A,B", mu_AB, "\ncov A,B", cov_AB) print("sigma_theta", sigma_theta) return m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta def get_bayesian_model(model_type): # Bayesian model # from https://iopscience.iop.org/article/10.1088/1367-2630/17/1/013042/pdf # see https://docs.pymc.io/api/model.html RB_model = pm.Model() with RB_model: #Priors for unknown model parameters alpha = pm.Uniform("alpha",lower=alpha_lower, upper=alpha_upper, testval = alpha_ref) BoundedMvNormal = pm.Bound(pm.MvNormal, lower=0.0) AB = BoundedMvNormal("AB", mu=mu_AB,testval = mu_AB, cov= np.diag(cov_AB), shape = (2)) # Expected value of outcome GSP = AB[0]*alpha**m_gates + AB[1] if model_type == "pooled": total_shots = np.full(Y.shape, shots) theta = GSP elif model_type == "hierarchical": total_shots = np.full(Y.shape, shots) theta = pm.Beta("GSP", mu=GSP, sigma = sigma_theta, shape = Y.shape[1]) # Likelihood (sampling distribution) of observations p = pm.Binomial("Counts", p=theta, observed=Y, n = total_shots) return RB_model def get_trace(RB_model): # Gradient-based sampling methods # see also: https://docs.pymc.io/notebooks/sampler-stats.html # and https://docs.pymc.io/notebooks/api_quickstart.html with RB_model: trace= pm.sample(draws = 2000, tune= 10000, target_accept=0.9, return_inferencedata=True) with RB_model: az.plot_trace(trace); return trace def get_summary(RB_model, trace, hdi_prob=.94, kind='all'): with RB_model: # (hdi_prob=.94 is default) az_summary = az.summary(trace, round_to=4, hdi_prob=hdi_prob, kind=kind ) return az_summary # obtain EPC from alpha (used by plot_posterior) def alpha_to_EPC(alpha): return 3*(1-alpha)/4 def get_EPC_and_legends(azs): EPC_Bayes = alpha_to_EPC(azs['mean']['alpha']) EPC_Bayes_err = EPC_Bayes - alpha_to_EPC(azs['mean']['alpha']+azs['sd']['alpha']) Bayes_legend ="EPC Bayes {0:.5f} ({1:.5f})".format(EPC_Bayes, EPC_Bayes_err) Fitter_legend ="EPC Fitter {0:.5f} ({1:.5f})".format(rbfit.fit[0]['epc']\ ,rbfit._fit[0]['epc_err']) pred_epc_legend = "EPC predicted {0:.5f}".format(pred_epc) return EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend def EPC_compare_fitter_to_bayes(RB_model, azs, trace): EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend, pred_epc_legend = get_EPC_and_legends(azs) with RB_model: az.plot_posterior(trace, var_names=['alpha'], round_to=4, transform = alpha_to_EPC, point_estimate=None) plt.title("Error per Clifford") plt.axvline(x=alpha_to_EPC(alpha_ref),color='red') plt.axvline(x=pred_epc,color='green') plt.legend((Bayes_legend, "Higher density interval",Fitter_legend, pred_epc_legend), fontsize=10 ) plt.show() def GSP_compare_fitter_to_bayes(RB_model, azs): EPC_Bayes, EPC_Bayes_err, Bayes_legend,Fitter_legend,_ = get_EPC_and_legends(azs) # plot ground state population ~ Clifford length fig, axes = plt.subplots(1, 1, sharex=True, figsize=(10, 6)) axes.set_ylabel("Ground State Population") axes.set_xlabel("Clifford Length") axes.plot(m_gates, np.mean(Y/shots,axis=0), 'r.') axes.plot(m_gates,azs['mean']['AB[0]']*azs['mean']['alpha']**m_gates+azs['mean']['AB[1]'],'--') axes.plot(m_gates,mu_AB[0]*np.power(alpha_ref,m_gates)+mu_AB[1],':') for i_seed in range(nseeds): plt.scatter(m_gates, Y[i_seed,:]/shots, label = "data", marker="x") axes.legend(["Mean Observed Frequencies", "Bayesian Model\n"+Bayes_legend, "Fitter Model\n"+Fitter_legend],fontsize=12) #axes.set_title('2 Qubit RB with T1/T2 Noise', fontsize=18) def get_predicted_EPC(error_source): #Count the number of single and 2Q gates in the 2Q Cliffords gates_per_cliff = rb.rb_utils.gates_per_clifford(transpile_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0]) for basis_gate in basis_gates: print("Number of %s gates per Clifford: %f "%(basis_gate , np.mean([gates_per_cliff[rb_pattern[0][0]][basis_gate], gates_per_cliff[rb_pattern[0][1]][basis_gate]]))) # Calculate the predicted epc # from the known depolarizing errors on the simulation if error_source == "depolarization": # Error per gate from noise model epgs_1q = {'u1': 0, 'u2': p1Q/2, 'u3': 2*p1Q/2} epg_2q = p2Q*3/4 pred_epc = rb.rb_utils.calculate_2q_epc( gate_per_cliff=gates_per_cliff, epg_2q=epg_2q, qubit_pair=[0, 2], list_epgs_1q=[epgs_1q, epgs_1q]) # using the predicted primitive gate errors from the coherence limit if error_source == "from_T1_T2": # Predicted primitive gate errors from the coherence limit u2_error = rb.rb_utils.coherence_limit(1,[t1],[t2],gate1Q) u3_error = rb.rb_utils.coherence_limit(1,[t1],[t2],2*gate1Q) epg_2q = rb.rb_utils.coherence_limit(2,[t1,t1],[t2,t2],gate2Q) epgs_1q = {'u1': 0, 'u2': u2_error, 'u3': u3_error} pred_epc = rb.rb_utils.calculate_2q_epc( gate_per_cliff=gates_per_cliff, epg_2q=epg_2q, qubit_pair=[0, 1], list_epgs_1q=[epgs_1q, epgs_1q]) return pred_epc #Number of qubits nQ = 3 #There are 3 qubits: Q0,Q1,Q2. #Number of seeds (random sequences) nseeds = 8 #Number of Cliffords in the sequence (start, stop, steps) nCliffs = np.arange(1,200,20) #2Q RB on Q0,Q2 and 1Q RB on Q1 rb_pattern = [[0,2],[1]] #Do three times as many 1Q Cliffords length_multiplier = [1,3] rb_pattern[0][1] rb_opts = {} rb_opts['length_vector'] = nCliffs rb_opts['nseeds'] = nseeds rb_opts['rb_pattern'] = rb_pattern rb_opts['length_multiplier'] = length_multiplier rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts) print(rb_circs[0][0]) noise_model = NoiseModel() p1Q = 0.004 # this was doubled with respect to the original example p2Q = 0.02 # this was doubled with respect to the original example noise_model.add_all_qubit_quantum_error(depolarizing_error(p1Q, 1), 'u2') noise_model.add_all_qubit_quantum_error(depolarizing_error(2*p1Q, 1), 'u3') noise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx') backend = qiskit.Aer.get_backend('qasm_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now shots = 1024 result_list = [] transpile_list = [] import time for rb_seed,rb_circ_seed in enumerate(rb_circs): print('Compiling seed %d'%rb_seed) rb_circ_transpile = qiskit.transpile(rb_circ_seed, basis_gates=basis_gates) print('Simulating seed %d'%rb_seed) job = qiskit.execute(rb_circ_transpile, noise_model=noise_model, shots=shots, backend=backend, max_parallel_experiments=0) result_list.append(job.result()) transpile_list.append(rb_circ_transpile) print("Finished Simulating") #Create an RBFitter object rbfit = rb.fitters.RBFitter(result_list, xdata, rb_opts['rb_pattern']) m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta =\ obtain_priors_and_data_from_fitter(printout = True) pooled = get_bayesian_model("pooled") pm.model_to_graphviz(pooled) trace_p = get_trace(pooled) azp_summary = get_summary(pooled, trace_p) azp_summary hierarchical = get_bayesian_model("hierarchical") pm.model_to_graphviz(hierarchical) trace_h = get_trace(hierarchical) azh_summary = get_summary(hierarchical, trace_h) azh_summary # Leave-one-out Cross-validation (LOO) comparison df_comp_loo = az.compare({"hierarchical": trace_h, "pooled": trace_p}) df_comp_loo az.plot_compare(df_comp_loo, insample_dev=False); # predict EPC from the noisy model pred_epc = get_predicted_EPC(error_source = 'depolarization') print("Predicted 2Q Error per Clifford: %e"%pred_epc) EPC_compare_fitter_to_bayes(pooled, azp_summary, trace_p) EPC_compare_fitter_to_bayes(hierarchical, azh_summary, trace_h) GSP_compare_fitter_to_bayes(pooled, azp_summary) GSP_compare_fitter_to_bayes(hierarchical, azh_summary) #Number of qubits nQ = 2 #There are 2 qubits: Q0,Q1. #Number of seeds (random sequences) nseeds = 10 # more data for the Rev. Mr. Bayes #Number of Cliffords in the sequence (start, stop, steps) nCliffs = np.arange(1,200,20) #2Q RB Q0,Q1 rb_pattern = [[0,1]] length_multiplier = 1 rb_opts = {} rb_opts ['length_vector'] = nCliffs rb_opts ['nseeds'] = nseeds rb_opts ['rb_pattern'] = rb_pattern rb_opts ['length_multiplier'] = length_multiplier rb_circs , xdata = rb.randomized_benchmarking_seq(**rb_opts ) noise_model = NoiseModel() #Add T1/T2 noise to the simulation t1 = 100. t2 = 80. gate1Q = 0.2 # this was doubled with respect to the original example gate2Q = 1.0 # this was doubled with respect to the original example noise_model.add_all_qubit_quantum_error(thermal_relaxation_error(t1,t2,gate1Q), 'u2') noise_model.add_all_qubit_quantum_error(thermal_relaxation_error(t1,t2,2*gate1Q), 'u3') noise_model.add_all_qubit_quantum_error( thermal_relaxation_error(t1,t2,gate2Q).tensor(thermal_relaxation_error(t1,t2,gate2Q)), 'cx') backend = qiskit.Aer.get_backend('qasm_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now shots = 1024 # a typical experimental value result_list = [] transpile_list = [] for rb_seed,rb_circ_seed in enumerate(rb_circs): print('Compiling seed %d'%rb_seed) rb_circ_transpile = qiskit.transpile(rb_circ_seed, basis_gates=basis_gates) print('Simulating seed %d'%rb_seed) job = qiskit.execute(rb_circ_transpile, noise_model=noise_model, shots=shots, backend=backend, max_parallel_experiments=0) result_list.append(job.result()) transpile_list.append(rb_circ_transpile) print("Finished Simulating") print(rb_circs[0][0]) #Create an RBFitter object rbfit = rb.RBFitter(result_list, xdata, rb_opts['rb_pattern']) m_gates, Y, alpha_ref, alpha_lower, alpha_upper, mu_AB, cov_AB, sigma_theta =\ obtain_priors_and_data_from_fitter(printout = True) pooled = get_bayesian_model("pooled") pm.model_to_graphviz(pooled) trace_p = get_trace(pooled) azp_summary = get_summary(pooled, trace_p) azp_summary hierarchical = get_bayesian_model("hierarchical") pm.model_to_graphviz(hierarchical) trace_h = get_trace(hierarchical) azh_summary = get_summary(hierarchical, trace_h) azh_summary # Leave-one-out Cross-validation (LOO) comparison df_comp_loo = az.compare({"hierarchical": trace_h, "pooled": trace_p}) df_comp_loo az.plot_compare(df_comp_loo, insample_dev=False); # predict EPC from the noisy model pred_epc = get_predicted_EPC(error_source = 'from_T1_T2') print("Predicted 2Q Error per Clifford: %e"%pred_epc) EPC_compare_fitter_to_bayes(pooled, azp_summary, trace_p) EPC_compare_fitter_to_bayes(hierarchical, azh_summary, trace_h) GSP_compare_fitter_to_bayes(pooled, azp_summary) GSP_compare_fitter_to_bayes(hierarchical, azh_summary) %load_ext watermark %watermark -n -u -v -iv -w
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Tests for generator of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import generators, types, stylesheet from qiskit.circuit import library, Delay class TestGates(QiskitTestCase): """Tests for generator.gates.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] self.u1 = types.ScheduledGate( t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0 ) self.u3 = types.ScheduledGate( t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0 ) self.delay = types.ScheduledGate( t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0 ) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_sched_gate_with_finite_duration(self): """Test test_gen_sched_gate generator with finite duration gate.""" drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 120]) self.assertListEqual( list(drawing_obj.yvals), [-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_meta = { "name": "u3", "label": "n/a", "bits": str(self.qubit.register.name), "t0": 100, "duration": 20, "unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]", "parameters": "0, 0, 0", } self.assertDictEqual(ref_meta, drawing_obj.meta) ref_styles = { "zorder": self.formatter["layer.gate"], "facecolor": self.formatter["color.gates"]["u3"], "alpha": self.formatter["alpha.gate"], "linewidth": self.formatter["line_width.gate"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_zero_duration(self): """Test test_gen_sched_gate generator with zero duration gate.""" drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"]) self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"]) ref_styles = { "zorder": self.formatter["layer.frame_change"], "color": self.formatter["color.gates"]["u1"], "size": self.formatter["text_size.frame_change"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_delay(self): """Test test_gen_sched_gate generator with delay.""" drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value)) def test_gen_full_gate_name_with_finite_duration(self): """Test gen_full_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]") ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format( name=self.formatter["latex_symbol.gates"]["u3"] ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_zero_duration(self): """Test gen_full_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1(0.00)") ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_delay(self): """Test gen_full_gate_name generator with delay.""" drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) def test_gen_short_gate_name_with_finite_duration(self): """Test gen_short_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_zero_duration(self): """Test gen_short_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_delay(self): """Test gen_short_gate_name generator with delay.""" drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) class TestTimeslot(QiskitTestCase): """Tests for generator.bits.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_timeslot(self): """Test gen_timeslot generator.""" drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value)) self.assertListEqual( list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ) self.assertListEqual( list(drawing_obj.yvals), [ -0.5 * self.formatter["box_height.timeslot"], 0.5 * self.formatter["box_height.timeslot"], ], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_styles = { "zorder": self.formatter["layer.timeslot"], "alpha": self.formatter["alpha.timeslot"], "linewidth": self.formatter["line_width.timeslot"], "facecolor": self.formatter["color.timeslot"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_bit_name(self): """Test gen_bit_name generator.""" drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, str(self.qubit.register.name)) ref_latex = r"{{\rm {register}}}_{{{index}}}".format( register=self.qubit.register.prefix, index=self.qubit.index ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.bit_name"], "color": self.formatter["color.bit_name"], "size": self.formatter["text_size.bit_name"], "va": "center", "ha": "right", } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestBarrier(QiskitTestCase): """Tests for generator.barriers.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(3)) self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_barrier(self): """Test gen_barrier generator.""" drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 100]) self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5]) self.assertListEqual(drawing_obj.bits, [self.qubits[1]]) ref_styles = { "alpha": self.formatter["alpha.barrier"], "zorder": self.formatter["layer.barrier"], "linewidth": self.formatter["line_width.barrier"], "linestyle": self.formatter["line_style.barrier"], "color": self.formatter["color.barrier"], } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestGateLink(QiskitTestCase): """Tests for generator.gate_links.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(2)) self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def gen_bit_link(self): """Test gen_bit_link generator.""" drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, self.qubits) ref_styles = { "alpha": self.formatter["alpha.bit_link"], "zorder": self.formatter["layer.bit_link"], "linewidth": self.formatter["line_width.bit_link"], "linestyle": self.formatter["line_style.bit_link"], "color": self.formatter["color.gates"]["cx"], } self.assertDictEqual(ref_styles, drawing_obj.styles)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit import ParameterVector from qiskit.circuit.library import ZFeatureMap from qiskit.quantum_info import SparsePauliOp from qiskit.utils import algorithm_globals from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import EstimatorQNN from sklearn.model_selection import train_test_split algorithm_globals.random_seed = 12345 # We now define a two qubit unitary as defined in [3] def conv_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) target.cx(1, 0) target.rz(np.pi / 2, 0) return target # Let's draw this circuit and see what it looks like params = ParameterVector("θ", length=3) circuit = conv_circuit(params) circuit.draw("mpl") def conv_layer(num_qubits, param_prefix): qc = QuantumCircuit(num_qubits, name="Convolutional Layer") qubits = list(range(num_qubits)) param_index = 0 params = ParameterVector(param_prefix, length=num_qubits * 3) for q1, q2 in zip(qubits[0::2], qubits[1::2]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 for q1, q2 in zip(qubits[1::2], qubits[2::2] + [0]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, qubits) return qc circuit = conv_layer(4, "θ") circuit.decompose().draw("mpl") def pool_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) return target params = ParameterVector("θ", length=3) circuit = pool_circuit(params) circuit.draw("mpl") def pool_layer(sources, sinks, param_prefix): num_qubits = len(sources) + len(sinks) qc = QuantumCircuit(num_qubits, name="Pooling Layer") param_index = 0 params = ParameterVector(param_prefix, length=num_qubits // 2 * 3) for source, sink in zip(sources, sinks): qc = qc.compose(pool_circuit(params[param_index : (param_index + 3)]), [source, sink]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, range(num_qubits)) return qc sources = [0, 1] sinks = [2, 3] circuit = pool_layer(sources, sinks, "θ") circuit.decompose().draw("mpl") def generate_dataset(num_images): images = [] labels = [] hor_array = np.zeros((6, 8)) ver_array = np.zeros((4, 8)) j = 0 for i in range(0, 7): if i != 3: hor_array[j][i] = np.pi / 2 hor_array[j][i + 1] = np.pi / 2 j += 1 j = 0 for i in range(0, 4): ver_array[j][i] = np.pi / 2 ver_array[j][i + 4] = np.pi / 2 j += 1 for n in range(num_images): rng = algorithm_globals.random.integers(0, 2) if rng == 0: labels.append(-1) random_image = algorithm_globals.random.integers(0, 6) images.append(np.array(hor_array[random_image])) elif rng == 1: labels.append(1) random_image = algorithm_globals.random.integers(0, 4) images.append(np.array(ver_array[random_image])) # Create noise for i in range(8): if images[-1][i] == 0: images[-1][i] = algorithm_globals.random.uniform(0, np.pi / 4) return images, labels images, labels = generate_dataset(50) train_images, test_images, train_labels, test_labels = train_test_split( images, labels, test_size=0.3 ) fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(4): ax[i // 2, i % 2].imshow( train_images[i].reshape(2, 4), # Change back to 2 by 4 aspect="equal", ) plt.subplots_adjust(wspace=0.1, hspace=0.025) feature_map = ZFeatureMap(8) feature_map.decompose().draw("mpl") feature_map = ZFeatureMap(8) ansatz = QuantumCircuit(8, name="Ansatz") # First Convolutional Layer ansatz.compose(conv_layer(8, "с1"), list(range(8)), inplace=True) # First Pooling Layer ansatz.compose(pool_layer([0, 1, 2, 3], [4, 5, 6, 7], "p1"), list(range(8)), inplace=True) # Second Convolutional Layer ansatz.compose(conv_layer(4, "c2"), list(range(4, 8)), inplace=True) # Second Pooling Layer ansatz.compose(pool_layer([0, 1], [2, 3], "p2"), list(range(4, 8)), inplace=True) # Third Convolutional Layer ansatz.compose(conv_layer(2, "c3"), list(range(6, 8)), inplace=True) # Third Pooling Layer ansatz.compose(pool_layer([0], [1], "p3"), list(range(6, 8)), inplace=True) # Combining the feature map and ansatz circuit = QuantumCircuit(8) circuit.compose(feature_map, range(8), inplace=True) circuit.compose(ansatz, range(8), inplace=True) observable = SparsePauliOp.from_list([("Z" + "I" * 7, 1)]) # we decompose the circuit for the QNN to avoid additional data copying qnn = EstimatorQNN( circuit=circuit.decompose(), observables=observable, input_params=feature_map.parameters, weight_params=ansatz.parameters, ) circuit.draw("mpl") def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() with open("11_qcnn_initial_point.json", "r") as f: initial_point = json.load(f) classifier = NeuralNetworkClassifier( qnn, optimizer=COBYLA(maxiter=200), # Set max iterations here callback=callback_graph, initial_point=initial_point, ) x = np.asarray(train_images) y = np.asarray(train_labels) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) classifier.fit(x, y) # score classifier print(f"Accuracy from the train data : {np.round(100 * classifier.score(x, y), 2)}%") y_predict = classifier.predict(test_images) x = np.asarray(test_images) y = np.asarray(test_labels) print(f"Accuracy from the test data : {np.round(100 * classifier.score(x, y), 2)}%") # Let's see some examples in our dataset fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(0, 4): ax[i // 2, i % 2].imshow(test_images[i].reshape(2, 4), aspect="equal") if y_predict[i] == -1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Horizontal Line") if y_predict[i] == +1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Vertical Line") plt.subplots_adjust(wspace=0.1, hspace=0.5) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/tushdon2/Qiskit_Hackathon_IITR_2021
tushdon2
from qiskit import execute, QuantumCircuit from qiskit.providers.aer import QasmSimulator # Import from Qiskit Aer noise module from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import pauli_error import warnings warnings.filterwarnings('ignore') def get_noise(): # Error probabilities pb_reset = 0.03 pb_meas = 0.1 pb_gate1 = 0.05 # QuantumError objects er_reset = pauli_error([('X', pb_reset), ('I', 1 - pb_reset)]) er_meas = pauli_error([('X',pb_meas), ('I', 1 - pb_meas)]) er_gate1 = pauli_error([('X',pb_gate1), ('I', 1 - pb_gate1)]) er_gate2 = er_gate1.tensor(er_gate1) # Add errors to noise model noise = NoiseModel() noise.add_all_qubit_quantum_error(er_reset, "reset") noise.add_all_qubit_quantum_error(er_meas, "measure") noise.add_all_qubit_quantum_error(er_gate1, ["u1", "u2", "u3"]) noise.add_all_qubit_quantum_error(er_gate2, ["cx"]) return noise def random_number(): circ = QuantumCircuit(3) simulator = QasmSimulator() #NQRNS Circuit for i in range(200): circ.u3(0,0,0,0) circ.u3(0,0,0,1) circ.u3(0,0,0,2) circ.cx(0,1) circ.cx(1,2) circ.cx(0,2) circ.barrier() circ.measure_all() noise = get_noise() #get output job = execute(circ, simulator, basis_gates=noise.basis_gates, noise_model=noise, shots= 1) result = job.result() counts = result.get_counts(0) num=list(counts.keys())[0] num = int(num, 2) if num>=5 : num =random_number() return num if __name__ == "__main__": arr =[0,0,0,0,0] for i in range (0,100) : number = random_number() arr[number] +=1 print(arr)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import os import sys cwd = os.getcwd() qiskit_dir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(cwd)))) sys.path.append(qiskit_dir) from qiskit import IBMQ from qiskit.tools.jupyter import * IBMQ.load_account() %qiskit_backend_overview
https://github.com/abbarreto/qiskit3
abbarreto
import sympy from sympy import * import numpy as np from numpy import random import math import scipy init_printing(use_unicode=True) from matplotlib import pyplot as plt %matplotlib inline from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum import TensorProduct as tp from mpmath import factorial as fact import io import base64 #from IPython.core.display import display, HTML, clear_output from IPython import * from ipywidgets import interactive, interact, fixed, interact_manual, widgets import csv import importlib import scipy.interpolate from mpl_toolkits.mplot3d import Axes3D, proj3d from itertools import product, combinations from matplotlib.patches import FancyArrowPatch from matplotlib import cm, colors from sympy.functions.special.tensor_functions import KroneckerDelta from scipy.linalg import polar, lapack import mpmath # constantes físicas e = 1.60217662*10**-19 # C (carga elementar) k = 8.9875517923*10**9 # Nm^2/C^2 (constante de Coulomb) eps0 = 8.8541878128*10**-12 #F/m (permissividade do vácuo) mu0 = 1.25663706212*10**-6 # N/A^2 (permeabilidade do vácuo) h = 6.626069*10**-34 # Js (constante de Planck) heV = h/e # em eV hb = h/(2*math.pi) # hbar hbeV = hb/e # em eV c = 2.99792458*10**8 # m/s (velocidade da luz no vácuo) G = 6.6742*10**-11 # Nm^2/kg^2 (constante gravitacional) kB = 1.38065*10**-23 # J/K (constante de Boltzmann) me = 9.109382*10**-31 # kg (massa do elétron) mp = 1.6726219*10**-27 # kg (massa do próton) mn = 1.67492749804*10**-27 # kg (massa do nêutron) mT = 5.9722*10**24 # kg (massa da Terra) mS = 1.98847*10**30 # kg (massa do Sol) u = 1.660538921*10**-27 # kg (unidade de massa atômica) dTS = 1.496*10**11 # m (distância Terra-Sol) rT = 6.3781*10**6 # m (raio da Terra) sSB = 5.670374419*10**-8 # W⋅m−2⋅K−4 (constante de Stefan-Boltzmann) Ri = 10973734.848575922 # m^-1 (constante de Rydberg) al = (k*e**2)/(hb*c) # ~1/137.035999084 (constante de estrutura fina) a0=(hb**2)/(me*k*e**2) # ~ 0.52917710^-10 m (raio de Bohr) ge = 2 # (fator giromagnetico do eletron) gp = 5.58 # (fator giromagnetico do proton) def id(n): '''retorna a matriz identidade nxn''' id = zeros(n,n) for j in range(0,n): id[j,j] = 1 return id #id(2) def pauli(j): '''retorna as matrizes de Pauli''' if j == 1: return Matrix([[0,1],[1,0]]) elif j == 2: return Matrix([[0,-1j],[1j,0]]) elif j == 3: return Matrix([[1,0],[0,-1]]) #pauli(1), pauli(2), pauli(3) def tr(A): '''retorna o traço de uma matriz''' d = A.shape[0] tr = 0 for j in range(0,d): tr += A[j,j] return tr #tr(pauli(1)) def comm(A,B): '''retorna a função comutador''' return A*B-B*A #comm(pauli(1),pauli(2)) def acomm(A,B): '''retorna a função anti-comutador''' return A*B+B*A #acomm(pauli(1),pauli(2)) def cb(n,j): '''retorna um vetor da base padrão de C^n''' vec = zeros(n,1) vec[j] = 1 return vec #cb(2,0) def proj(psi): '''retorna o projeto no vetor psi''' d = psi.shape[0] P = zeros(d,d) for j in range(0,d): for k in range(0,d): P[j,k] = psi[j]*conjugate(psi[k]) return P #proj(cb(2,0)) def bell(j,k): if j == 0 and k == 0: return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))+tp(cb(2,1),cb(2,1))) elif j == 0 and k == 1: return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))+tp(cb(2,1),cb(2,0))) elif j == 1 and k == 0: return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))-tp(cb(2,1),cb(2,0))) elif j == 1 and k == 1: return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))-tp(cb(2,1),cb(2,1))) #bell(0,0), bell(0,1), bell(1,0), bell(1,1) def inner_product(v,w): d = len(v); ip = 0 for j in range(0,d): ip += conjugate(v[j])*w[j] return ip #a,b,c,d = symbols("a b c d"); v = [b,a]; w = [c,d]; inner_product(v,w) def norm(v): d = len(v) return sqrt(inner_product(v,v)) #v = [2,2]; norm(v) def tp(x,y): return tensorproduct(x,y) A = tp(pauli(3),pauli(1)); A
https://github.com/WhenTheyCry96/qiskitHackathon2022
WhenTheyCry96
%load_ext autoreload %autoreload 2 import os import warnings import numpy as np import pyEPR as epr import qiskit_metal as metal from collections import OrderedDict import scqubits as scq from scipy.constants import c, h, pi, hbar, e from qiskit_metal import designs, draw, MetalGUI, Dict, Headings from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from qiskit_metal.analyses.quantization import LOManalysis, EPRanalysis from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry ws_path = os.getcwd() warnings.filterwarnings("ignore") design = designs.DesignPlanar() design.overwrite_enabled = True #constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) design.chips.main.size_x = '12mm' design.chips.main.size_y = '10mm' gui = MetalGUI(design) design.delete_all_components() design_span_x = 5 design_span_y = 3 half_chip_width = design_span_x / 2 half_chip_height = design_span_y / 2 connection_pads_options = dict( a = dict(loc_W=1, loc_H=-1), b = dict(loc_W=1, loc_H=1), c = dict(loc_W=-1, loc_H=-1) ) connection23_pads_options = dict( a = dict(loc_W=1, loc_H=-1), c = dict(loc_W=-1, loc_H=-1) ) transmons = [] transmons.append(TransmonPocketCL(design, 'Q1', options=dict(pos_x=f'-{half_chip_width}mm', pos_y=f'{-half_chip_height}mm', connection_pads=dict(**connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q2', options=dict(pos_x=f'0mm', pos_y=f'{half_chip_height}mm', orientation=-90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q3', options=dict(pos_x=f'0mm', pos_y=f'{-half_chip_height}mm', orientation=90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q4', options=dict(pos_x=f'{half_chip_width}mm', pos_y=f'{half_chip_height}mm', orientation=180, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() fillet='99.99um' options = Dict( meander=Dict( lead_start='0.1mm', lead_end='0.1mm', asymmetry='0 um') ) def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str, length: str, asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False): """Connect two pins with a CPW.""" myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component=component1, pin=pin1), end_pin=Dict( component=component2, pin=pin2)), lead=Dict( start_straight=start_strght, end_straight=end_strght ), total_length=length, fillet = '99.9um') myoptions.update(options) myoptions.meander.asymmetry = asymmetry myoptions.meander.lead_direction_inverted = 'true' if flip else 'false' return RouteMeander(design, component_name, myoptions) asym_h = 100 asym_v = 100 cpw = [] cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) gui.rebuild() gui.autoscale() readouts_lwc = [] control_lwc = [] offset_x = 0 offset_y = 1 #Readouts readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1', options = dict( pos_x = '-5mm', pos_y = f'-{half_chip_height+offset_y}mm', lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2', options = dict( pos_x = '-1mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3', options = dict( pos_x = '1mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4', options = dict( pos_x = '5mm', pos_y = f'{half_chip_height+offset_y}mm', orientation = 180, lead_length = '30um'))) #Controls control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1', options = dict( pos_x = '-5mm', pos_y = '2mm', lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2', options = dict( pos_x = '4mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3', options = dict( pos_x = '-4mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4', options = dict( pos_x = '5mm', pos_y = '-2mm', orientation = 180, lead_length = '30um'))) gui.rebuild() gui.autoscale() readout_lines = [] asym_14 = 700 asym_23 = 700 options = Dict( lead=Dict( start_straight='330um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um')) options = Dict( lead=Dict( start_straight='430um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um')) gui.rebuild() gui.autoscale() control_lines = [] def connectRouteAnchor(name: str, component1: str, pin1: str, component2: str, pin2: str, anchor_points: OrderedDict) -> RouteAnchors: options_line_cl = dict( pin_inputs = dict(start_pin = dict(component = component1, pin = pin1), end_pin = dict(component = component2, pin = pin2)), anchors = anchor_points, lead = dict(start_straight = '200um', end_straight = '225um'), fillet = fillet ) return RouteAnchors(design, name, options_line_cl) anchors1c = OrderedDict() anchors1c[0] = np.array([-4, -1.42]) anchors1c[1] = np.array([-4, 2]) control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c)) anchors2c = OrderedDict() anchors2c[0] = np.array([0.08, 3.25]) anchors2c[1] = np.array([4, 3.25]) control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c)) anchors3c = OrderedDict() anchors3c[0] = np.array([-0.08, -3.25]) anchors3c[1] = np.array([-4, -3.25]) control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c)) anchors4c = OrderedDict() anchors4c[0] = np.array([4, 1.42]) anchors4c[1] = np.array([4, -2]) control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c)) gui.rebuild() gui.autoscale() gui.screenshot(name="full_design.png") # constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) # CPW busline length is determined to be 7 mm cpw[0].options.total_length = '7.0mm' cpw[1].options.total_length = '7.0mm' cpw[2].options.total_length = '7.0mm' cpw[3].options.total_length = '7.0mm' gui.rebuild() gui.autoscale() # qubit 1 design target f: 5.25 GHz # readout resonator target f: 7.05 GHz # qubit 2 design target f: 5.42 GHz # readout resonator target f: 7.22 GHz # qubit 3 design target f: 5.58 GHz # readout resonator target f: 7.38 GHz # qubit 4 design target f: 5.75 GHz # readout resonator target f: 7.55 GHz # tuning parameters C_JJ4f = 2 L_JJ4f = 11.7 C_JJ4 = str(C_JJ4f)+' fF' L_JJ4 = str(L_JJ4f)+' nH' transmons[3].options.pad_gap = '35um' transmons[3].options.pad_width = '500um' transmons[3].options.pad_height = '125um' transmons[3].options.connection_pads.c.pad_gap = '40um' transmons[3].options.connection_pads.a.pad_gap = '60um' # cpw5 transmons[3].options.connection_pads.a.pad_width = '40um' # cpw5 transmons[3].options.connection_pads.b.pad_gap = '60um' # cpw3 transmons[3].options.connection_pads.b.pad_width = '30um' # cpw3 readout_lines[3].options.total_length = '7.5mm' gui.rebuild() gui.autoscale() # EPR analysis eig_q4 = EPRanalysis(design, "hfss") hfss4 = eig_q4.sim.renderer hfss4.start() hfss4.activate_ansys_design("TransmonQ4", 'eigenmode') hfss4.render_design(['Q4', 'ol4', 'cpw3', 'cpw5'], [('cpw3', 'end'), ('cpw5', 'start'), ('ol4', 'end')]) # Analysis properties setup4 = hfss4.pinfo.setup setup4.n_modes = 6 setup4.passes = 10 setup4.min_freq_ghz = 4 print(f""" Number of eigenmodes to find = {setup4.n_modes} Number of simulation passes = {setup4.passes} Convergence freq max delta percent diff = {setup4.delta_f} """) pinfo4 = hfss4.pinfo pinfo4.design.set_variable('Lj4', L_JJ4) pinfo4.design.set_variable('Cj4', C_JJ4) setup4.analyze() eig_q4.sim.convergence_t, eig_q4.sim.convergence_f, _ = hfss4.get_convergences() eig_q4.sim.plot_convergences() pinfo4.junctions['jj'] = {'Lj_variable': 'Lj4', 'rect': 'JJ_rect_Lj_Q4_rect_jj', 'line': 'JJ_Lj_Q4_rect_jj_', 'Cj_variable': 'Cj4'} pinfo4.validate_junction_info() pinfo4.dissipative['dielectrics_bulk'] = ['main'] hfss4.set_mode(1, "Setup") hfss4.modeler._modeler.ShowWindow() hfss4.plot_fields('main') eprd4 = epr.DistributedAnalysis(pinfo4) ℰ_elec = eprd4.calc_energy_electric() ℰ_elec_substrate = eprd4.calc_energy_electric(None, 'main') ℰ_mag = eprd4.calc_energy_magnetic() print(f""" ℰ_elec_all = {ℰ_elec} ℰ_elec_substrate = {ℰ_elec_substrate} EPR of substrate = {ℰ_elec_substrate / ℰ_elec * 100 :.1f}% ℰ_mag_all = {ℰ_mag} ℰ_mag % of ℰ_elec_all = {ℰ_mag / ℰ_elec * 100 :.1f}% """) eprd4.do_EPR_analysis() #epra4 = epr.QuantumAnalysis(eprd4.data_filename) #epra4.analyze_all_variations(cos_trunc = 8, fock_trunc = 7) c4 = LOManalysis(design, "q3d") q3d4 = c4.sim.renderer q3d4.start() q3d4.activate_ansys_design("TransmonQ4_q3d", 'capacitive') q3d4.render_design(['Q4'], [('Q4', 'a'),('Q4', 'b'),('Q4', 'c')]) q3d4.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5, percent_error=0.1) q3d4.analyze_setup("Setup") c4.sim.capacitance_matrix, c4.sim.units = q3d4.get_capacitance_matrix() c4.sim.capacitance_all_passes, _ = q3d4.get_capacitance_all_passes() c4.sim.capacitance_matrix c4.setup.junctions = Dict({'Lj':L_JJ4f, 'Cj':C_JJ4f}) c4.setup.freq_readout = 7.45 c4.setup.freq_bus = [8.25, 8.25, 15] c4.run_lom() c4.lumped_oscillator_all QuantumSystemRegistry.registry() # Q4 path4= ws_path+"/Project71_TransmonQ4_q3d.txt" t4_mat, _, _, _ = load_q3d_capacitance_matrix(path4) # Cell 4 Transmon-4 opt4 = dict( node_rename = {'a_connector_pad_Q4': 'cpw5', 'b_connector_pad_Q4': 'cpw3', 'c_connector_pad_Q4': 'readout4'}, cap_mat = t4_mat, ind_dict = {('pad_top_Q4', 'pad_bot_Q4'): 11.7}, # junction inductance in nH jj_dict = {('pad_top_Q4', 'pad_bot_Q4'): 'j4'}, cj_dict = {('pad_top_Q4', 'pad_bot_Q4'): 2} # junction capacitance in fF ) cell_4 = Cell(opt4) # subsystem 1: Transmon-4 transmon4 = Subsystem(name='transmon4', sys_type='TRANSMON', nodes=['j4']) # Resonator Subsystems q_opts = dict( Z0 = 50, # characteristic impedance in Ohm vp = 0.404314 * 3e8 # phase velocity ) # subsystem 3: Q2 readout resonator ro4 = Subsystem(name='readout4', sys_type='TL_RESONATOR', nodes=['readout4'], q_opts=dict(f_res = 7.57, **q_opts)) # subsystem 4: bus3 resonator cpw3 = Subsystem(name='cpw3', sys_type='TL_RESONATOR', nodes=['cpw3'], q_opts=dict(f_res = 8.2, **q_opts)) # subsystem 15: bus5 resonator cpw5 = Subsystem(name='cpw5', sys_type='TL_RESONATOR', nodes=['cpw5'], q_opts=dict(f_res = 8.29, **q_opts)) composite_sys = CompositeSystem( subsystems=[transmon4, ro4, cpw3, cpw5], cells=[cell_4], grd_node='ground_main_plane', nodes_force_keep=['readout4', 'cpw3', 'cpw5'] ) cg = composite_sys.circuitGraph() print(cg) hilbertspace = composite_sys.create_hilbertspace() print(hilbertspace) # Convert the hilbert space into # "Interaction Picture" hilbertspace = composite_sys.add_interaction() hilbertspace.hamiltonian() hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30) composite_sys.compute_gs()
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
OccumRazor
from qiskit import * from qiskit.circuit.library.standard_gates import SwapGate,CU1Gate,XGate,U1Gate from math import pi,sqrt from qiskit.quantum_info.operators import Operator import numpy as np def ini(circ,qr,ipt): # Input binary form, and append [0] ahead for qr1 block. for i in range(len(ipt)): if ipt[len(ipt)-i-1]: circ.x(qr[i]) return 0 def diffusion(n): # Matrix representation of the diffusion transformation. N=2**n# for Grover search. return [N*[2/N] for i in range(N)]-np.identity(N) def phaseFlip(reg,theta): # reg is a one qubit register (input a qubit is also OK). if reg.__len__()!=1: raise TypeError('The input quantum register contains more than one qubit.') phaseCirc=QuantumCircuit(reg,name='p\nh\na\ns\ne\n') phaseCirc.append(U1Gate(theta),reg) phaseCirc.append(XGate(),reg) phaseCirc.append(U1Gate(theta),reg) phaseCirc.append(XGate(),reg) return phaseCirc.to_instruction() def CPhaseFlip(qReg,reg,theta):# If all ancilla qubits equal one, flip the phase of querry REG. # In this place, reg is a one qubit quantum register, and qReg is a n qubits quantum register. phaseCirc=QuantumCircuit(qReg,reg,name='p\nh\na\ns\ne\n') num=qReg.__len__() IN=[qReg[i] for i in range(num)]+[reg[0]] CU1Gate=U1Gate(theta).control(num) CXGate=XGate().control(num) phaseCirc.append(CU1Gate,IN) phaseCirc.append(CXGate,IN) phaseCirc.append(CU1Gate,IN) phaseCirc.append(CXGate,IN) return phaseCirc.to_instruction() def amulitpdeAmplification(query,criteria,ancilla,n):# for Grover search. AACirc=QuantumCircuit(query,criteria,ancilla,name='A\nA\n') AACirc.h(query) from qiskit_code.Grover import check CHECK=check(query,criteria,ancilla,n) lst=range(n)# This looks rather awkward, I may (but not likely) try to change this later. AC=[ancilla[i] for i in lst] QUERY=[query[i] for i in lst] CHECKIN=QUERY+[criteria[i] for i in lst]+AC nCP=CPhaseFlip(ancilla,QuantumRegister(1),pi) nCX=XGate().control(n)# Generate a controlled-X gate with n controls. D=Operator(diffusion(n)) for i in range(int(pi*sqrt(2**n)/8+1)):#[1] Iteration times. AACirc.append(CHECK,CHECKIN) AACirc.append(nCP,AC+[query[0]]) AACirc.append(CHECK,CHECKIN) AACirc.append(D,query) # [1]M. Boyer, G. Brassard, P. Hoyer & A. Tapp, Tight bounds on quantum searching, #Proceedings, PhysComp 1996 return AACirc.to_instruction() def bigCSwap(c,t0,t1,l):# Controlled Swap of two qubit blocks. BCSC=QuantumCircuit(c,t0,t1,name='b\ni\ng\nC\nS\nw\na\np\n') for i in range(l): BCSC.cswap(c,t0[i],t1[i]) return BCSC.to_instruction() def bigSwap(t0,t1,l):# Swap of two qubit blocks. BSC=QuantumCircuit(t0,t1,name='b\ni\ng\nS\nw\na\np\n') for i in range(l): BSC.swap(t0[i],t1[i]) return BSC.to_instruction() def c_cx(c0,c1,target,n):# CCX where the second control and the target are two blocks c_cxC=QuantumCircuit(c0,c1,target,name='C\no\nn\nt\nr\no\nl\nl\ne\nd\n-\nC\nX\n') for i in range(n): c_cxC.ccx(c0,c1[i],target[i]) return c_cxC.to_instruction() def bigCCSwap(c0,c1,reg1,reg2,l):# Controlled-Controlled Swap of two qubit blocks. bigCCSwapC=QuantumCircuit(c0,c1,reg1,reg2,name='C\nC\nS\nw\na\np\n') ccswap=SwapGate().control(2) for i in range(l): bigCCSwapC.append(ccswap,[c0[0],c1[0],reg1[i],reg2[i]]) return bigCCSwapC.to_instruction() carry_q=QuantumRegister(4) carryC=QuantumCircuit(carry_q,name='c\na\nr\nr\ny\n') carryC.ccx(carry_q[1],carry_q[2],carry_q[3]) carryC.cx(carry_q[1],carry_q[2]) carryC.ccx(carry_q[0],carry_q[2],carry_q[3]) CARRY=carryC.to_instruction() sum_q=QuantumRegister(3) sumC=QuantumCircuit(sum_q,name='s\nu\nm') sumC.cx(sum_q[1],sum_q[2]) sumC.cx(sum_q[0],sum_q[2]) SUM=sumC.to_instruction() def add(q0,q1,q2,l): # A quantum plain adder, as the main part of the oracle. # Vedral, V., Barenco, A. and Ekert, A., 1996. # Quantum networks for elementary arithmetic operations. Physical Review A, 54(1), p.147. add_circ=QuantumCircuit(q0,q1,q2,name='a\nd\nd') for i in range(l-1): add_circ.append(CARRY,[q2[i],q0[i],q1[i],q2[i+1]]) add_circ.append(CARRY,[q2[l-1],q0[l-1],q1[l-1],q1[l]]) add_circ.cx(q0[l-1],q1[l-1]) add_circ.append(SUM,[q2[l-1],q0[l-1],q1[l-1]]) RCARRY=CARRY.reverse_ops()#inverse() for i in range(l-2,-1,-1): add_circ.append(RCARRY,[q2[i],q0[i],q1[i],q2[i+1]]) add_circ.append(SUM,[q2[i],q0[i],q1[i]]) return add_circ.to_instruction() def sub(q0,q1,q2,l): RCARRY=CARRY.reverse_ops() sub_circ=QuantumCircuit(q0,q1,q2,name='s\nu\nb') for i in range(l): sub_circ.append(SUM,[q2[i],q1[i],q0[i]]) if i==l-1: sub_circ.cx(q0[i],q1[i]) sub_circ.append(CARRY,[q2[i],q1[i],q0[i],q2[i+1]]) for i in range(l-2,-1,-1): sub_circ.append(RCARRY,[q2[i],q1[i],q0[i],q2[i+1]]) sub_circ.x(q2[l]) sub_circ.swap(q0,q1) return sub_circ.to_instruction() def adderMod(qr0,qr1,ac,Nr,swap_ac,t,l,ADD,SUB): # 0<=a,b<N AMC=QuantumCircuit(qr0,qr1,ac,Nr,swap_ac,t,name='a\nd\nd\ne\nr\nM\no\nd\n') BigCSwap=bigCSwap(t,qr0,swap_ac,l) BigSwap=bigSwap(qr0,Nr,l) lst=range(l) ADDIN=[qr0[i] for i in lst]+[qr1[i] for i in lst]+[ac[i] for i in lst] BigSwapIN=[qr0[i] for i in lst]+[Nr[i] for i in lst] BigCSwapIN=[t[0]]+[qr0[i] for i in lst]+[swap_ac[i] for i in lst] AMC.append(ADD,ADDIN) AMC.append(BigSwap,BigSwapIN) AMC.append(SUB,ADDIN) AMC.x(qr1[l-1]) AMC.cx(qr1[l-1],t) AMC.x(qr1[l-1]) AMC.append(BigCSwap,BigCSwapIN) AMC.append(ADD,ADDIN) AMC.append(BigCSwap,BigCSwapIN) AMC.append(BigSwap,BigSwapIN) AMC.append(SUB,ADDIN) AMC.cx(qr1[l-1],t) AMC.append(ADD,ADDIN) return AMC.to_instruction() def c_mtpMOD(circ,qr0,qr1,qr2,ac,Nr,swap_ac,t,cReg,xReg,l,n): ADD=add(qr0,qr1,ac,l) SUB=sub(qr0,qr1,ac,l) AddMOD=adderMod(qr0,qr1,ac,Nr,swap_ac,t,l,ADD,SUB) iAddMOD=AddMOD.reverse_ops() BigCCSwap=bigCCSwap(cReg,t,qr0,swap_ac,l) CCX=c_cx(cReg,xReg,qr1,n) lst=range(l) AddMODIN=[qr0[i] for i in lst]+[qr1[i] for i in lst]+[ac[i] for i in lst] AddMODIN+=[Nr[i] for i in lst]+[swap_ac[i] for i in lst]+[t[0]] for i in range(n): BigCCSwapIN=[cReg,xReg[i]]+[qr0[i] for i in lst]+[qr2[i] for i in lst] circ.append(BigCCSwap,BigCCSwapIN) circ.append(AddMOD,AddMODIN) circ.append(BigCCSwap,BigCCSwapIN) circ.x(cReg) CCXIN=[cReg[0]]+[xReg[i] for i in range(n)]+[qr1[i] for i in range(l)] circ.append(CCX,CCXIN) circ.x(cReg) return 0 def expMod(qr0,qr1,ac,circ,N,l): BigSwap=bigSwap(xReg,qr1,l) lst=range(l) BigSwapIN=[xReg[i] for i in lst]+[qr1[i] for i in lst] C_MtpMOD=c_mtpMOD(qr0,qr1,qr2,ac,Nr,swap_ac,t,cReg,xReg,l,n) iC_MtpMOD=C_MtpMOD.reverse_ops() for i in range(m): MtpMODIN circ.append(C_MtpMOD,MtpMODIN) circ.append(BigSwap,BigSwapIN) circ.append(C_MtpMOD,MtpMODIN) return None def qft(qReg): # Michael Nielsen and Isaac Chuang (2000). Quantum Computation and Quantum # Information. Cambridge: Cambridge University Press. ISBN 0-521-63503-9. # OCLC 174527496. P219, section 5.1 The quantum Fourier transform # https://qiskit.org/documentation/stubs/qiskit.circuit.library.QFT.html qft_circ=QuantumCircuit(qReg,name='Q\nF\nT\n') num=qReg.__len__() for i in range(num-1,-1,-1): qft_circ.h(qReg[i]) for j in range(i): qft_circ.append(CU1Gate(pi/2**(i-j)),[qReg[i],qReg[j]]) # Reverse the qubit order for i in range(int(num/2)):# int(0.5)=0, so odd/even does not matters qft_circ.swap(qReg[i],qReg[num-1-i]) return qft_circ.to_instruction()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A module for monitoring various qiskit functionality""" import sys import time def _text_checker( job, interval, _interval_set=False, quiet=False, output=sys.stdout, line_discipline="\r" ): """A text-based job status checker Args: job (BaseJob): The job to check. interval (int): The interval at which to check. _interval_set (bool): Was interval time set by user? quiet (bool): If True, do not print status messages. output (file): The file like object to write status messages to. By default this is sys.stdout. line_discipline (string): character emitted at start of a line of job monitor output, This defaults to \\r. """ status = job.status() msg = status.value prev_msg = msg msg_len = len(msg) if not quiet: print("{}{}: {}".format(line_discipline, "Job Status", msg), end="", file=output) while status.name not in ["DONE", "CANCELLED", "ERROR"]: time.sleep(interval) status = job.status() msg = status.value if status.name == "QUEUED": msg += " (%s)" % job.queue_position() if job.queue_position() is None: interval = 2 elif not _interval_set: interval = max(job.queue_position(), 2) else: if not _interval_set: interval = 2 # Adjust length of message so there are no artifacts if len(msg) < msg_len: msg += " " * (msg_len - len(msg)) elif len(msg) > msg_len: msg_len = len(msg) if msg != prev_msg and not quiet: print("{}{}: {}".format(line_discipline, "Job Status", msg), end="", file=output) prev_msg = msg if not quiet: print("", file=output) def job_monitor(job, interval=None, quiet=False, output=sys.stdout, line_discipline="\r"): """Monitor the status of a IBMQJob instance. Args: job (BaseJob): Job to monitor. interval (int): Time interval between status queries. quiet (bool): If True, do not print status messages. output (file): The file like object to write status messages to. By default this is sys.stdout. line_discipline (string): character emitted at start of a line of job monitor output, This defaults to \\r. Examples: .. code-block:: python from qiskit import BasicAer, transpile from qiskit.circuit import QuantumCircuit from qiskit.tools.monitor import job_monitor sim_backend = BasicAer.get_backend("qasm_simulator") qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure_all() tqc = transpile(qc, sim_backend) job_sim = sim_backend.run(tqc) job_monitor(job_sim) """ if interval is None: _interval_set = False interval = 5 else: _interval_set = True _text_checker( job, interval, _interval_set, quiet=quiet, output=output, line_discipline=line_discipline )
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
# TODO, show how different aggression configurations impact results from qiskit.transpiler import CouplingMap from mirror_gates.pass_managers import Mirage, QiskitLevel3 from transpile_benchy.metrics.abc_metrics import MetricInterface from transpile_benchy.metrics.gate_counts import DepthMetric from mirror_gates.utilities import DoNothing from mirror_gates.logging import transpile_benchy_logger from transpile_benchy.library import CircuitLibrary library = CircuitLibrary.from_txt("../../circuits/select.txt") coupling_map = CouplingMap.from_heavy_hex(5) total_work = 80 transpilers = [ QiskitLevel3(coupling_map), Mirage(coupling_map, name="Mirage"), # Mirage( # coupling_map, # name="Mirage-b2", # layout_trials=3, # fb_iters=total_work // 3, # anneal_routing=True, # ), Mirage( coupling_map, name="Mirage-b3", layout_trials=4, fb_iters=total_work // 4, anneal_routing=True, ), ] metrics = [DepthMetric(consolidate=False)] from transpile_benchy.benchmark import Benchmark # only interested in TimeMetric, is there by default benchmark = Benchmark( transpilers=transpilers, circuit_library=library, metrics=metrics, num_runs=1, logger=transpile_benchy_logger, ) benchmark.run() print(benchmark.summary_statistics(transpilers[0], transpilers[1])["monodromy_depth"]) print(benchmark.summary_statistics(transpilers[0], transpilers[2])["monodromy_depth"]) # print(benchmark.summary_statistics(transpilers[0], transpilers[3])["monodromy_depth"]) from transpile_benchy.render import plot_benchmark plot_benchmark(benchmark, save=0, legend_show=1, filename="annealing")
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
DRA-chaos
!pip install qiskit import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list import numpy as np import torch from torch.autograd import Function import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute from qiskit.circuit import Parameter from qiskit import Aer from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): t_qc = transpile(self._circuit, self.backend) qobj = assemble(t_qc, shots=self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) job = self.backend.run(qobj) result = job.result().get_counts() counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) simulator = qiskit.Aer.get_backend('qasm_simulator') circuit = QuantumCircuit(1, simulator, 100) print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0])) circuit._circuit.draw() class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, input, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = ctx.quantum_circuit.run(input[0].tolist()) result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) labels = cifar_trainset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_trainset.targets = labels[idx] cifar_trainset.data = cifar_trainset.data[idx] train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) import numpy as np import matplotlib.pyplot as plt n_samples_show = 8 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2)) while n_samples_show > 0: images, targets = data_iter.__next__() images=images.squeeze() #axes[n_samples_show - 1].imshow( tf.shape( tf.squeeze(images[0]) ),cmap='gray' ) #plt.imshow((tf.squeeze(images[0]))) #plt.imshow( tf.shape( tf.squeeze(x_train) ) ) #axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray') axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform) labels = cifar_testset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_testset.targets = labels[idx] cifar_testset.data = cifar_testset.data[idx] test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(500, 500) self.fc2 = nn.Linear(500, 1) self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(1, -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) return torch.cat((x, 1 - x), -1) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Now plotting the training graph plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 10 loss_list1 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list1.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list1[-1])) #Alongside, let's also plot the data plt.plot(loss_list1) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 15 loss_list2 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list2.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list2[-1])) #Alongside, let's also plot the data plt.plot(loss_list2) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 20 loss_list3 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list3.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list3[-1])) #Alongside, let's also plot the data plt.plot(loss_list3) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 30 loss_list4 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list4.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list4[-1])) #Alongside, let's also plot the data plt.plot(loss_list4) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) )
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Abstract CircuitFactory to build a circuit, along with inverse, controlled and power combinations of the circuit. """ from abc import ABC, abstractmethod from qiskit import QuantumCircuit from qiskit.aqua.utils.controlled_circuit import get_controlled_circuit class CircuitFactory(ABC): """ Base class for CircuitFactories """ def __init__(self, num_target_qubits): self._num_target_qubits = num_target_qubits pass @property def num_target_qubits(self): """ Returns the number of target qubits """ return self._num_target_qubits def required_ancillas(self): return 0 def required_ancillas_controlled(self): return self.required_ancillas() def get_num_qubits(self): return self._num_target_qubits + self.required_ancillas() def get_num_qubits_controlled(self): return self._num_target_qubits + self.required_ancillas_controlled() @abstractmethod def build(self, qc, q, q_ancillas=None): """ Adds corresponding sub-circuit to given circuit Args: qc : quantum circuit q : list of qubits (has to be same length as self._num_qubits) q_ancillas : list of ancilla qubits (or None if none needed) params : parameters for circuit """ raise NotImplementedError() def build_inverse(self, qc, q, q_ancillas=None): """ Adds inverse of corresponding sub-circuit to given circuit Args: qc : quantum circuit q : list of qubits (has to be same length as self._num_qubits) q_ancillas : list of ancilla qubits (or None if none needed) params : parameters for circuit """ qc_ = QuantumCircuit(*qc.qregs) self.build(qc_, q, q_ancillas) qc.extend(qc_.inverse()) def build_controlled(self, qc, q, q_control, q_ancillas=None, use_basis_gates=True): """ Adds corresponding controlled sub-circuit to given circuit Args: qc : quantum circuit q : list of qubits (has to be same length as self._num_qubits) q_control : control qubit q_ancillas : list of ancilla qubits (or None if none needed) use_basis_gates: use basis gates for expansion of controlled circuit """ uncontrolled_circuit = QuantumCircuit(*qc.qregs) self.build(uncontrolled_circuit, q, q_ancillas) controlled_circuit = get_controlled_circuit(uncontrolled_circuit, q_control, use_basis_gates=use_basis_gates) qc.extend(controlled_circuit) def build_controlled_inverse(self, qc, q, q_control, q_ancillas=None, use_basis_gates=True): """ Adds controlled inverse of corresponding sub-circuit to given circuit Args: qc : quantum circuit q : list of qubits (has to be same length as self._num_qubits) q_control : control qubit q_ancillas : list of ancilla qubits (or None if none needed) use_basis_gates: use basis gates for expansion of controlled circuit """ qc_ = QuantumCircuit(*qc.qregs) self.build_controlled(qc_, q, q_control, q_ancillas, use_basis_gates) qc.extend(qc_.inverse()) def build_power(self, qc, q, power, q_ancillas=None): """ Adds power of corresponding circuit. May be overridden if a more efficient implementation is possible """ for _ in range(power): self.build(qc, q, q_ancillas) def build_inverse_power(self, qc, q, power, q_ancillas=None): """ Adds inverse power of corresponding circuit. May be overridden if a more efficient implementation is possible """ for _ in range(power): self.build_inverse(qc, q, q_ancillas) def build_controlled_power(self, qc, q, q_control, power, q_ancillas=None, use_basis_gates=True): """ Adds controlled power of corresponding circuit. May be overridden if a more efficient implementation is possible """ for _ in range(power): self.build_controlled(qc, q, q_control, q_ancillas, use_basis_gates) def build_controlled_inverse_power(self, qc, q, q_control, power, q_ancillas=None, use_basis_gates=True): """ Adds controlled, inverse, power of corresponding circuit. May be overridden if a more efficient implementation is possible """ for _ in range(power): self.build_controlled_inverse(qc, q, q_control, q_ancillas, use_basis_gates)
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
AlphaMiyaL
%matplotlib inline #Imports from qiskit import QuantumCircuit, execute, Aer, IBMQ, ClassicalRegister, QuantumRegister from qiskit.compiler import transpile, assemble import numpy as np from qiskit.tools.jupyter import * from qiskit.visualization import * import json from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller from qiskit.tools.monitor import job_monitor def block_idx(x, y): if x<2 and y<2: return 0 if x<2: return 1 if y<2: return 2 return 3 def apply_cands(matrix): cands = [] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] != 0: continue temp = [] for k in range(4): f = True for row in range(4): if matrix[row][j] == k + 1: f = False for col in range(4): if matrix[i][col] == k + 1: f = False for x in range(4): for y in range(4): if block_idx(i, j) != block_idx(x, y): continue if matrix[x][y] == k + 1: f = False if f: temp.append(k+1) cands.append(temp) return cands def one_cand_op(qc, q0, q1, cands): #print(q0, q1) if cands[0] == 1: pass elif cands[0] == 2: qc.x(q1) elif cands[0] == 3: qc.x(q0) else: qc.x(q0) qc.x(q1) def one_cand_op_inverse(qc, q0, q1, cands): if cands[0] == 1: pass elif cands[0] == 2: qc.x(q1) elif cands[0] == 3: qc.x(q0) else: qc.x(q1) qc.x(q0) def two_cand_op(qc, q0, q1, cands): #print(q0, q1, cands[0], cands[1]) product = cands[0]*cands[1] #1 + 2 if product == 2: qc.h(q1) #1 + 3 elif product == 3: qc.h(q0) #1 + 4 elif product == 4: qc.h(q0) qc.cx(q0, q1) #2 + 3 elif product == 6: qc.x(q1) qc.h(q0) qc.cx(q0, q1) #2 + 4 elif product == 8: qc.x(q1) qc.h(q0) #3 + 4 else: qc.h(q1) qc.x(q0) def two_cand_op_inverse(qc, q0, q1, cands): product = cands[0]*cands[1] #1 + 2 if product == 2: qc.h(q1) #1 + 3 elif product == 3: qc.h(q0) #1 + 4 elif product == 4: qc.cx(q0, q1) qc.h(q0) #2 + 3 elif product == 6: qc.cx(q0, q1) qc.h(q0) qc.x(q1) #2 + 4 elif product == 8: qc.h(q0) qc.x(q1) #3 + 4 else: qc.h(q1) qc.x(q0) def init_blanks(qc, qr, matrix): cands = apply_cands(matrix) # print(cands) for i in range(len(cands)): if len(cands[i]) == 1: one_cand_op(qc, qr[2*i], qr[2*i+1], cands[i]) else: two_cand_op(qc, qr[2*i], qr[2*i+1], cands[i]) def init_blanks_inverse(qc, qr, matrix): cands = apply_cands(matrix) for i in range(len(cands)-1, -1, -1): if len(cands[i]) == 1: one_cand_op_inverse(qc, qr[2*i], qr[2*i+1], cands[i]) else: two_cand_op_inverse(qc, qr[2*i], qr[2*i+1], cands[i]) # if v1 != v2 (number) then target = 1 else target = 0 def compare_vertex(qc, qr, v1, v2, target): qc.x(qr[2*v2]) qc.x(qr[2*v2+1]) qc.ccx(qr[2*v1], qr[2*v1+1], target) qc.ccx(qr[2*v1+1], qr[2*v2], target) qc.ccx(qr[2*v2], qr[2*v2+1], target) qc.ccx(qr[2*v1], qr[2*v2+1], target) qc.x(qr[2*v2+1]) qc.x(qr[2*v2]) qc.x(qr[target]) def compare_vertex_inverse(qc, qr, v1, v2, target): qc.x(qr[target]) qc.x(qr[2*v2]) qc.x(qr[2*v2+1]) qc.ccx(qr[2*v1], qr[2*v2+1], target) qc.ccx(qr[2*v2], qr[2*v2+1], target) qc.ccx(qr[2*v1+1], qr[2*v2], target) qc.ccx(qr[2*v1], qr[2*v1+1], target) qc.x(qr[2*v2+1]) qc.x(qr[2*v2]) # Edge constraint oracle def oracle(qc, qr): # vs = [0, 1, 2, 3, 4, 5, 6, 7] list1 = [[0, 1], [2, 3], [4, 5], [6, 7], [2, 6], [0, 4]] list2 = [[1, 5], [3, 7], [0, 2], [1, 3], [4, 6], [5, 7]] target = 16 temp1 = 30 temp2 = 31 for elm in list1: assert(len(elm)==2) compare_vertex(qc, qr, elm[0], elm[1], target) target+=1 qc.mct(qr[16:target], qr[temp1], qr[22:29], mode='basic') for elm in (reversed(list1)): target-=1 compare_vertex_inverse(qc, qr, elm[0], elm[1], target) for elm in list2: assert(len(elm)==2) compare_vertex(qc, qr, elm[0], elm[1], target) target+=1 qc.mct(qr[16:target], qr[temp2], qr[22:29], mode='basic') for elm in (reversed(list2)): target-=1 compare_vertex_inverse(qc, qr, elm[0], elm[1], target) dest = 29 qc.ccx(qr[temp1], qr[temp2], qr[dest]) for elm in list2: assert(len(elm)==2) compare_vertex(qc, qr, elm[0], elm[1], target) target+=1 qc.mct(qr[16:target], qr[temp2], qr[22:29], mode='basic') for elm in (reversed(list2)): target-=1 compare_vertex_inverse(qc, qr, elm[0], elm[1], target) for elm in list1: assert(len(elm)==2) compare_vertex(qc, qr, elm[0], elm[1], target) target+=1 qc.mct(qr[16:target], qr[temp1], qr[22:29], mode='basic') for elm in (reversed(list1)): target-=1 compare_vertex_inverse(qc, qr, elm[0], elm[1], target) """ diffusion (inversion about the mean) circuit. """ def diffusion(circuit, qr, matrix): # circuit.h(qr) init_blanks_inverse(circuit, qr[:16], matrix) # inverse of unitary op of initial state preparation circuit.x(qr[:16]) # apply multi-control CZ circuit.h(qr[15]) # circuit.mct(qr[:-1], qr[-1], anc, mode='basic') circuit.mct(qr[:15], qr[15], qr[16:29], mode='basic') circuit.h(qr[15]) circuit.x(qr[:16]) # circuit.h(qr) init_blanks(circuit, qr[:16], matrix) qr = QuantumRegister(32) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) matrix = np.array([4, 0, 2, 0, 0, 1, 0, 4, 1, 0, 4, 0, 0, 4, 0, 2]).reshape(4, 4) print(matrix) print(apply_cands(matrix)) def grover(iter): init_blanks(qc, qr, matrix) for _ in range(iter): oracle(qc, qr) print("oracle done") diffusion(qc, qr, matrix) print("diffusion done") qc.measure(qr[0:16], cr[0:16]) print("measure done") #print("drawing start") #qc.draw() grover(3) # Unroll the circuit pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) # obtain gates gates=new_circuit.count_ops() print(gates) cost=gates['u3'] + 10*gates['cx'] print(cost) # shots = 8000 shots = 1024 print("shots:", shots) ## Run on Aer Simulator backend = Aer.get_backend('qasm_simulator') ## Run on Quantum Hardware(does not techically work however since we need 32 qbits but free only give 7) ## Can run the 2x2 to show that the Sudoku solving does work on a Quantum Computer however #provider = IBMQ.load_account() #backend = provider.get_backend('ibm_oslo') print("execute start") job = execute(qc, backend=backend, shots=shots, seed_simulator=12345, backend_options={"fusion_enable":True}) print("job id:", job.job_id()) job_monitor(job) result = job.result() count = result.get_counts() print(count) print(len(count)) score_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True) final_score = score_sorted[0:15] final_score count_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True) # collect answers with Top 7 probability ans_list = count_sorted[:12] # reverse ans_list ans_reversed = [] for i in ans_list: ans_temp=[i[0][::-1],i[1]] ans_reversed.append(ans_temp) # convert each 2 bits into corresponding color. Add node0(0),node3(1),node8(2) and node11(3) ans_shaped = [] for j in ans_reversed: ans_temp=j[0] node0 = int(ans_temp[0] + ans_temp[1], 2) node1 = int(ans_temp[2] + ans_temp[3], 2) node2 = int(ans_temp[4] + ans_temp[5], 2) node3 = int(ans_temp[6] + ans_temp[7], 2) node4 = int(ans_temp[8] + ans_temp[9], 2) node5 = int(ans_temp[10] + ans_temp[11], 2) node6 = int(ans_temp[12] + ans_temp[13], 2) node7 = int(ans_temp[14] + ans_temp[15], 2) nodes_color = str(node0) + str(node1) + str(node2) + str(node3) + str(node4) + str(node5) + str(node6) + str(node7) ans_shaped.append([nodes_color,j[1]]) sorted(ans_shaped) # Converting to decimal, 1-4 (since this is a 4x4 matrix) def convert_to_decimal(str_bin): str_bin = ''.join(list(reversed(str_bin))) # cbitに格納されるときに順番逆になっていることに注意 list_dec = [str(int(str_bin[2*i:2*i+2], 2)+1) for i in range(len(str_bin)//2)] str_dec = ''.join(list_dec) return str_dec # histogram plot (decimal representation) count_decimal = {} for key, value in count.items(): count_decimal[convert_to_decimal(key)] = value print(count_decimal) plot_histogram(count_decimal) def replace_matrix_vals(matrix): new_matrix = [] replace_idx = 0 #first sol from above replacements = [int(x) for x in str(convert_to_decimal(next(iter(count.items()))[0]))] for list in matrix: for num in list: if num == 0: new_matrix.append(replacements[replace_idx]) replace_idx+=1 else: new_matrix.append(num) return np.array(new_matrix).reshape(4,4) filled_sudoku = replace_matrix_vals(matrix) print(filled_sudoku)
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
Alice-Bob-SW
''' qiskitpool/job.py Contains the QJob class ''' from functools import partial from qiskit import execute class QJob(): ''' QJob Job manager for asynch qiskit backends ''' def __init__(self, *args, qjob_id=None, **kwargs): ''' QJob.__init__ Initialiser for a qiksit job :: *args :: Args for qiskit execute :: **kwargs :: Kwargs for qiskit execute ''' self.job_fn = partial(execute, *args, **kwargs) self.job = None self.done = False self.test_count = 10 self.qjob_id = qjob_id def __call__(self): ''' QJob.__call__ Wrapper for QJob.run ''' return self.run() def run(self): ''' QJob.run Send async job to qiskit backend ''' self.job = self.job_fn() return self def poll(self): ''' QJob.poll Poll qiskit backend for job completion status ''' if self.job is not None: return self.job.done() return False def cancel(self): ''' QJob.cancel Cancel job on backend ''' if self.job is None: return None return self.job.cancel() def position(self): pos = self.job.queue_position() if pos is None: return 0 return pos def status(self): if self.job is None: return 'LOCAL QUEUE' else: status = self.job.status().value if 'running' in status: return 'RUNNING' if 'run' in status: return 'COMPLETE' if 'validated' in status: return 'VALIDATING' if 'queued' in status: pos = self.position() return f'QISKIT QUEUE: {self.position()}' def status_short(self): if self.job is None: return ' ' else: status = self.job.status().value if 'running' in status: return 'R' if 'run' in status: return 'C' if 'validated' in status: return 'V' if 'queued' in status: return str(self.position()) def result(self): ''' QJob.result Get result from backend Non blocking - returns False if a job is not yet ready ''' if self.poll(): return self.job.result() return False
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Variational Quantum Real Time Evolution algorithm.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Type, Callable import numpy as np from scipy.integrate import OdeSolver from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import BaseEstimator from .solvers.ode.forward_euler_solver import ForwardEulerSolver from .variational_principles import RealVariationalPrinciple, RealMcLachlanPrinciple from .var_qte import VarQTE from ..real_time_evolver import RealTimeEvolver class VarQRTE(VarQTE, RealTimeEvolver): """Variational Quantum Real Time Evolution algorithm. .. code-block::python import numpy as np from qiskit_algorithms import TimeEvolutionProblem, VarQRTE from qiskit.circuit.library import EfficientSU2 from qiskit_algorithms.time_evolvers.variational import RealMcLachlanPrinciple from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info import SparsePauliOp, Pauli from qiskit.primitives import Estimator observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) ansatz = EfficientSU2(observable.num_qubits, reps=1) init_param_values = np.ones(len(ansatz.parameters)) * np.pi/2 var_principle = RealMcLachlanPrinciple() time = 1 # without evaluating auxiliary operators evolution_problem = TimeEvolutionProblem(observable, time) var_qrte = VarQRTE(ansatz, init_param_values, var_principle) evolution_result = var_qrte.evolve(evolution_problem) # evaluating auxiliary operators aux_ops = [Pauli("XX"), Pauli("YZ")] evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) var_qrte = VarQRTE(ansatz, init_param_values, var_principle, Estimator()) evolution_result = var_qrte.evolve(evolution_problem) """ def __init__( self, ansatz: QuantumCircuit, initial_parameters: Mapping[Parameter, float] | Sequence[float], variational_principle: RealVariationalPrinciple | None = None, estimator: BaseEstimator | None = None, ode_solver: Type[OdeSolver] | str = ForwardEulerSolver, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, num_timesteps: int | None = None, imag_part_tol: float = 1e-7, num_instability_tol: float = 1e-7, ) -> None: r""" Args: ansatz: Ansatz to be used for variational time evolution. initial_parameters: Initial parameter values for an ansatz. variational_principle: Variational Principle to be used. Defaults to ``RealMcLachlanPrinciple``. estimator: An estimator primitive used for calculating expectation values of TimeEvolutionProblem.aux_operators. ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. num_timesteps: The number of timesteps to take. If ``None``, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol: The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. """ if variational_principle is None: variational_principle = RealMcLachlanPrinciple() super().__init__( ansatz, initial_parameters, variational_principle, estimator, ode_solver, lse_solver=lse_solver, num_timesteps=num_timesteps, imag_part_tol=imag_part_tol, num_instability_tol=num_instability_tol, )
https://github.com/UST-QuAntiL/nisq-analyzer-content
UST-QuAntiL
from typing import List from qiskit import QuantumCircuit, transpile, QuantumRegister, ClassicalRegister from qiskit import BasicAer,Aer,execute, IBMQ from qiskit.providers.aer import QasmSimulator from qiskit.circuit.library.arithmetic import DraperQFTAdder, RGQFTMultiplier from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, AmplitudeEstimation from qiskit.algorithms import EstimationProblem from qiskit.utils import QuantumInstance from qiskit.providers.fake_provider import FakeMontreal def encode_input(x: List[int]) -> "Gate": num_qubits = len(x) qc = QuantumCircuit(num_qubits, name="encoding") for i in range(num_qubits): if x[i] == 1: qc.x(num_qubits - i - 1) return qc def encode_hadamard_copy(num_qubits: int) -> "Gate": qc = QuantumCircuit(num_qubits * 2, name="extension") for i in range(num_qubits): qc.cx(i, i + num_qubits) return qc def encode_hadamard(num_qubits: int) -> "Gate": qc = QuantumCircuit(num_qubits, name="encoding") for i in range(num_qubits): qc.h(i) return qc def classical(x: List[int], y: List[int]) -> int: num1 = 0 for i in range(len(x)): num1 += x[i] * 0.5 ** (i + 1) num2 = 0 for i in range(len(y)): num2 += x[i] * 0.5 ** (i + 1) result = num1 ** 2 + num2 ** 2 if result < 1: return 1 return 0 def operator(bits_per_input, x1, x2, useQAE): num_bits_after_mult = 2 * bits_per_input num_bits_comparer = num_bits_after_mult + 1 nQubits = 4 * bits_per_input + 2 * num_bits_after_mult + 1 + num_bits_comparer nClassical = 1 input_register_1 = QuantumRegister(size=bits_per_input) input_register_1_copy = QuantumRegister(size=bits_per_input) input_register_2 = QuantumRegister(size=bits_per_input) input_register_2_copy = QuantumRegister(size=bits_per_input) if len(x1) == 0 and len(x2) == 0: input_circuit_1 = encode_hadamard(bits_per_input) input_circuit_1_copy = encode_hadamard_copy(bits_per_input) input_circuit_2 = encode_hadamard(bits_per_input) input_circuit_2_copy = encode_hadamard_copy(bits_per_input) else: input_circuit_1 = encode_input(x1) input_circuit_1_copy = encode_input(x1) input_circuit_2 = encode_input(x2) input_circuit_2_copy = encode_input(x2) carry_qubits_mult_1 = QuantumRegister(size=num_bits_after_mult) carry_qubits_mult_2 = QuantumRegister(size=num_bits_after_mult) carry_qubits_comparer = QuantumRegister(size=num_bits_comparer) carry_qubit_addition = QuantumRegister(size=1) # 1 additional qubit for addition if useQAE == False: output_register = ClassicalRegister(size=nClassical) circuit = QuantumCircuit( input_register_1, input_register_1_copy, input_register_2, input_register_2_copy, carry_qubits_mult_1, carry_qubits_mult_2, carry_qubit_addition, carry_qubits_comparer, output_register ) else: circuit = QuantumCircuit( input_register_1, input_register_1_copy, input_register_2, input_register_2_copy, carry_qubits_mult_1, carry_qubits_mult_2, carry_qubit_addition, carry_qubits_comparer ) # encoding circuit.append(input_circuit_1, input_register_1[:]) if len(x1) == 0 and len(x2) == 0: circuit.append(input_circuit_1_copy, input_register_1[:] + input_register_1_copy[:]) else: circuit.append(input_circuit_1_copy, input_register_1_copy[:]) circuit.append(input_circuit_2, input_register_2[:]) if len(x1) == 0 and len(x2) == 0: circuit.append(input_circuit_2_copy, input_register_2[:] + input_register_2_copy[:]) else: circuit.append(input_circuit_2_copy, input_register_2_copy[:]) # multiplication multiplicator = RGQFTMultiplier(num_state_qubits=bits_per_input) circuit.append(multiplicator, input_register_1[:] + input_register_1_copy[:] + carry_qubits_mult_1[:]) circuit.append(multiplicator, input_register_2[:] + input_register_2_copy[:] + carry_qubits_mult_2[:]) # addition adder = DraperQFTAdder(num_bits_after_mult, kind="half") circuit.append(adder, carry_qubits_mult_1[:] + carry_qubits_mult_2[:] + carry_qubit_addition[:]) # inequality check if in circle s = 2 ** (bits_per_input) - 1 comparer = IntegerComparator(num_bits_after_mult + 1, s * s + 1, False) circuit.append(comparer, carry_qubits_mult_2[:] + carry_qubit_addition[:] + carry_qubits_comparer[:]) # readout if useQAE == False: circuit.measure(nQubits - num_bits_comparer, 0) return circuit def get_circuit(**kwargs): bits_per_input =1 # num qubits per number useQAE =True circuit =operator(bits_per_input,[],[],useQAE) #circuit.draw('mpl') #backend = FakeMontreal() #circuit_transpiled = transpile(circuit,backend) #circuit_transpiled.draw('mpl') #circuit_transpiled.depth() backend =Aer.get_backend('qasm_simulator') circuit_to_return = None if useQAE == True: quantum_instance = Aer.get_backend('qasm_simulator') num_bits_after_mult = 2 * bits_per_input num_bits_comparer =num_bits_after_mult+1 nQubits=4*bits_per_input + 2*num_bits_after_mult+1 +num_bits_comparer problem = EstimationProblem( state_preparation=circuit.decompose(), # A operator objective_qubits=[nQubits-num_bits_comparer], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) print(f"Depth: ", circuit.depth()) print(f"Width: ", circuit.num_qubits) ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy quantum_instance=quantum_instance, ) iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval quantum_instance=quantum_instance, ) circuit_to_return = ae.construct_circuit(problem, measurement=True).decompose() print(circuit_to_return) result =ae.estimate(problem) print(result) else: shots =1000 job= execute(circuit,backend=backend,shots=shots) counts =job.result().get_counts() print(counts) #print(4 * counts['1'] /shots ) return circuit_to_return
https://github.com/JohnBurke4/qaoa_testing_framework
JohnBurke4
from Image_Reader import ImageReader from DCT_Classic import DCT import Quantum_Subroutines import os import Image_Compression import cv2 import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, transpile from CustomStatePrep import StatePreparation from qiskit_aer.backends.aerbackend import AerBackend from qiskit.providers.fake_provider import FakeSydneyV2 from qiskit_aer import AerSimulator from qiskit.circuit.library import Isometry import csv import CustomUnitaryDecomp import scipy max = 256 np.set_printoptions(precision=3, suppress=True) path = "StateCompression/images/camera.png" image = ImageReader.getImage(path) image = cv2.resize(image, (max, max)).astype(int) basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] basis_gates = ['u3', 'cx', 'id'] # image = image / np.linalg.norm(image) maxCompression = 8 for comp in range(maxCompression, -1, -1): [U, D, V] = np.linalg.svd(image) compression = comp n = max // 2**compression D = D[:n] dNorm = np.linalg.norm(D) D = D / dNorm D = D.transpose() def prepareDState(D, totalQubits): qubits = int(np.log2(len(D))) qc = QuantumCircuit(totalQubits) qc.initialize(D, range(0, qubits)) for i in range(0, qubits): qc.cx(i, totalQubits//2) return qc # qubits = int(2 * np.log2(max)) # qc = QuantumCircuit(qubits) # if (n != 1): # statePrep = prepareDState(D, qubits) # statePrep.name = "S" # qc.append(statePrep, range(0, qubits)) # print(U.shape) # print(V.shape) V = V.transpose() U = U[:, :n] V = V[:, :n] # print(U) # uIsometry = Isometry(U, num_ancillas_dirty=0, num_ancillas_zero=0) # uIsometry.name = "U" # vIsometry = Isometry(V, num_ancillas_dirty=0, num_ancillas_zero=0) # vIsometry.name = "V" # qc.append(vIsometry, range(0, qubits//2)) # qc.append(uIsometry, range(qubits//2, qubits)) # # print(qc) # sim = Aer.get_backend('aer_simulator') # circ = transpile(qc, sim, basis_gates=basis_gates) # depth = circ.depth() # gates = sum(dict(circ.count_ops()).values()) # # print(depth, gates) # # circ.save_statevector() # # result = sim.run(circ, nshots=1).result() # # out_vector = result.get_statevector().data # # imageData = out_vector.real.reshape((max, max)) # # # imageData = imageData V = V.transpose() for i in range(0, len(D)): V[i, :] *= D[i] classicalCompressed = np.matmul(U, V) * dNorm # inner = np.inner(classicalCompressed.flatten(), image.flatten() / np.linalg.norm(image)) # print(V) # print(D) # for i in range(0, len(D)): # V[i, :] *= D[i] # print(V) # print(np.matmul(U, V)) # print(imageData) # quantumImage = (imageData * dNorm) # psnr = cv2.PSNR(image.astype(int), classicalCompressed.astype(int)) # print(comp, gates, depth, psnr) # print(comp, inner**2) plt.imsave("svd_cameraX" + str(comp) + ".png", classicalCompressed, cmap='gray') # plt.show()
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from sympy import Matrix X = Matrix([[0,1],[1,0]]); X Y = Matrix([[0,-1j],[1j,0]]); Y Z = Matrix([[1,0],[0,-1]]); Z X.eigenvals() X.eigenvects() Y.eigenvects() Z.eigenvects() from sympy import Matrix X = Matrix([[0,1],[1,0]]) ket0 = Matrix([[1],[0]]); ket1 = Matrix([[0],[1]]); ket0, ket1 X*ket0, X*ket1 Y*ket0, Y*ket1, Z*ket0, Z*ket1 from sympy.physics.quantum import TensorProduct as tp ket00 = tp(ket0,ket0); ket01 = tp(ket0,ket1); ket10 = tp(ket1,ket0); ket11 = tp(ket1,ket1); ket00, ket01, ket10, ket11 tp(eye(2),X), tp(eye(2),eye(2))*ket00, tp(eye(2),X)*ket00, tp(X,eye(2))*ket00, tp(X,X)*ket00 from qiskit import QuantumCircuit import qiskit from qiskit.quantum_info import Statevector qc = QuantumCircuit(2) # prepara o estado |00> qc.draw('mpl') state = Statevector(qc) state qc = QuantumCircuit(2) qc.x(1) # estado |01> qc.draw('mpl') state = Statevector(qc); state from sympy.physics.quantum.dagger import Dagger P0 = ket0*Dagger(ket0); P1 = ket1*Dagger(ket1); P0,P1 CNOTab = tp(P0,eye(2)) + tp(P1,X); CNOTba = tp(eye(2),P0) + tp(X,P1); CNOTab,CNOTba H = Matrix([[1,1],[1,-1]])/sqrt(2); H Phip = CNOTab*tp(H,eye(2))*ket00; Phim = CNOTab*tp(H,eye(2))*ket10; Phip,Phim from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # |Phi+> from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.x([0,1]) qc.h(0) qc.cx(0,1) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # |Psi-> from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0); qc.cx(0,1) # prepara |Phi+> qc.barrier() qc.cx(0,1) qc.h(0) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # estado |00> from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi-> qc.barrier() qc.cx(0,1) qc.h(0) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # estado |11> from sympy import Matrix X = Matrix([[0,1],[1,0]]); X init_printing(use_unicode=True) # pra visualização ficar melhor X.eigenvects() from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.h(0) from qiskit.quantum_info import Statevector state = Statevector(qc) state qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 # 8192 job = execute(qc, backend=simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.h(0) qc.barrier() qc.h(0) qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 # 8192 job = execute(qc, backend=simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.sdg(0) qc.h(0) qc.measure(0,0) qc.draw('mpl') from qiskit import execute, Aer simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) from sympy import symbols th, ph, lb = symbols('theta phi lambda'); th, ph, lb sn = Matrix([[cos(th),exp(-1j*ph)*sin(th)],[exp(1j*ph)*sin(th),-cos(th)]]); sn sn.eigenvects() import math math.cos(math.pi/8)**2 from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) import math th = -math.pi/4 ph = 0 lb = math.pi - ph qc.u(th,ph,lb, 0) # porta parametrizada qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend = simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) # Cria o circuito quântico, sem usar medidas from qiskit import QuantumCircuit qc = QuantumCircuit(1) qc.h(0) qc.s(0) qc.draw(output='mpl') # estado |o+>=(|0>+i|1>)/sqrt(2) 2**13 from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 import qiskit; from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter qstc = state_tomography_circuits(qc, [0]); job = execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') qiskit.visualization.plot_state_city(rho) rho from sympy import Matrix, symbols, init_printing, eye init_printing(use_unicode=True) X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]) x,y,z = symbols('x y z') rho = (1/2)*(eye(2) + x*X + y*Y + z*Z); rho rho.eigenvals() from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(4) # não faz nada no 1º qubit qc.x(1) qc.h(2) qc.h(3); qc.s(3) state = Statevector(qc) plot_bloch_multivector(state)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Sampler.""" import unittest import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes from qiskit.exceptions import QiskitError from qiskit.extensions.unitary import UnitaryGate from qiskit.primitives import Sampler, SamplerResult from qiskit.providers import JobStatus, JobV1 from qiskit.test import QiskitTestCase class TestSampler(QiskitTestCase): """Test Sampler""" def setUp(self): super().setUp() hadamard = QuantumCircuit(1, 1, name="Hadamard") hadamard.h(0) hadamard.measure(0, 0) bell = QuantumCircuit(2, name="Bell") bell.h(0) bell.cx(0, 1) bell.measure_all() self._circuit = [hadamard, bell] self._target = [ {0: 0.5, 1: 0.5}, {0: 0.5, 3: 0.5, 1: 0, 2: 0}, ] self._pqc = RealAmplitudes(num_qubits=2, reps=2) self._pqc.measure_all() self._pqc2 = RealAmplitudes(num_qubits=2, reps=3) self._pqc2.measure_all() self._pqc_params = [[0.0] * 6, [1.0] * 6] self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}] self._theta = [ [0, 1, 1, 2, 3, 5], [1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], ] def _generate_circuits_target(self, indices): if isinstance(indices, list): circuits = [self._circuit[j] for j in indices] target = [self._target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return circuits, target def _generate_params_target(self, indices): if isinstance(indices, int): params = self._pqc_params[indices] target = self._pqc_target[indices] elif isinstance(indices, list): params = [self._pqc_params[j] for j in indices] target = [self._pqc_target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return params, target def _compare_probs(self, prob, target): if not isinstance(prob, list): prob = [prob] if not isinstance(target, list): target = [target] self.assertEqual(len(prob), len(target)) for p, targ in zip(prob, target): for key, t_val in targ.items(): if key in p: self.assertAlmostEqual(p[key], t_val, places=1) else: self.assertAlmostEqual(t_val, 0, places=1) def test_sampler_run(self): """Test Sampler.run().""" bell = self._circuit[1] sampler = Sampler() job = sampler.run(circuits=[bell]) self.assertIsInstance(job, JobV1) result = job.result() self.assertIsInstance(result, SamplerResult) # print([q.binary_probabilities() for q in result.quasi_dists]) self._compare_probs(result.quasi_dists, self._target[1]) def test_sample_run_multiple_circuits(self): """Test Sampler.run() with multiple circuits.""" # executes three Bell circuits # Argument `parameters` is optional. bell = self._circuit[1] sampler = Sampler() result = sampler.run([bell, bell, bell]).result() # print([q.binary_probabilities() for q in result.quasi_dists]) self._compare_probs(result.quasi_dists[0], self._target[1]) self._compare_probs(result.quasi_dists[1], self._target[1]) self._compare_probs(result.quasi_dists[2], self._target[1]) def test_sampler_run_with_parameterized_circuits(self): """Test Sampler.run() with parameterized circuits.""" # parameterized circuit pqc = self._pqc pqc2 = self._pqc2 theta1, theta2, theta3 = self._theta sampler = Sampler() result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() # result of pqc(theta1) prob1 = { "00": 0.1309248462975777, "01": 0.3608720796028448, "10": 0.09324865232050054, "11": 0.41495442177907715, } self.assertDictAlmostEqual(result.quasi_dists[0].binary_probabilities(), prob1) # result of pqc(theta2) prob2 = { "00": 0.06282290651933871, "01": 0.02877144385576705, "10": 0.606654494132085, "11": 0.3017511554928094, } self.assertDictAlmostEqual(result.quasi_dists[1].binary_probabilities(), prob2) # result of pqc2(theta3) prob3 = { "00": 0.1880263994380416, "01": 0.6881971261189544, "10": 0.09326232720582443, "11": 0.030514147237179892, } self.assertDictAlmostEqual(result.quasi_dists[2].binary_probabilities(), prob3) def test_run_1qubit(self): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = Sampler() result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) for i in range(2): keys, values = zip(*sorted(result.quasi_dists[i].items())) self.assertTupleEqual(keys, (i,)) np.testing.assert_allclose(values, [1]) def test_run_2qubit(self): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.x(0) qc1.measure_all() qc2 = QuantumCircuit(2) qc2.x(1) qc2.measure_all() qc3 = QuantumCircuit(2) qc3.x([0, 1]) qc3.measure_all() sampler = Sampler() result = sampler.run([qc0, qc1, qc2, qc3]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) for i in range(4): keys, values = zip(*sorted(result.quasi_dists[i].items())) self.assertTupleEqual(keys, (i,)) np.testing.assert_allclose(values, [1]) def test_run_single_circuit(self): """Test for single circuit case.""" sampler = Sampler() with self.subTest("No parameter"): circuit = self._circuit[1] target = self._target[1] param_vals = [None, [], [[]], np.array([]), np.array([[]])] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) with self.subTest("One parameter"): circuit = QuantumCircuit(1, 1, name="X gate") param = Parameter("x") circuit.ry(param, 0) circuit.measure(0, 0) target = [{1: 1}] param_vals = [ [np.pi], [[np.pi]], np.array([np.pi]), np.array([[np.pi]]), [np.array([np.pi])], ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) with self.subTest("More than one parameter"): circuit = self._pqc target = [self._pqc_target[0]] param_vals = [ self._pqc_params[0], [self._pqc_params[0]], np.array(self._pqc_params[0]), np.array([self._pqc_params[0]]), [np.array(self._pqc_params[0])], ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) def test_run_reverse_meas_order(self): """test for sampler with reverse measurement order""" x = Parameter("x") y = Parameter("y") qc = QuantumCircuit(3, 3) qc.rx(x, 0) qc.rx(y, 1) qc.x(2) qc.measure(0, 2) qc.measure(1, 1) qc.measure(2, 0) sampler = Sampler() result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) # qc({x: 0, y: 0}) keys, values = zip(*sorted(result.quasi_dists[0].items())) self.assertTupleEqual(keys, (1,)) np.testing.assert_allclose(values, [1]) # qc({x: pi/2, y: 0}) keys, values = zip(*sorted(result.quasi_dists[1].items())) self.assertTupleEqual(keys, (1, 5)) np.testing.assert_allclose(values, [0.5, 0.5]) def test_run_errors(self): """Test for errors with run method""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() qc3 = QuantumCircuit(1) qc4 = QuantumCircuit(1, 1) sampler = Sampler() with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc1], [[1e2]]) with self.subTest("missing all parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[]]) with self.subTest("missing some parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[1e2]]) with self.subTest("too many parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[1e2]] * 100) with self.subTest("no classical bits"): with self.assertRaises(ValueError): _ = sampler.run([qc3], [[]]) with self.subTest("no measurement"): with self.assertRaises(QiskitError): # The following raises QiskitError because this check is located in # `Sampler._preprocess_circuit` _ = sampler.run([qc4], [[]]) def test_run_empty_parameter(self): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) sampler = Sampler() with self.subTest("one circuit"): result = sampler.run([qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 1) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictEqual(quasi_dist, {0: 1.0}) self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictEqual(quasi_dist, {0: 1.0}) self.assertEqual(len(result.metadata), 2) def test_run_numpy_params(self): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() k = 5 params_array = np.random.rand(k, qc.num_parameters) params_list = params_array.tolist() params_list_array = list(params_array) sampler = Sampler() target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) with self.subTest("list of ndarray"): result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) def test_run_with_shots_option(self): """test with shots option.""" params, target = self._generate_params_target([1]) sampler = Sampler() result = sampler.run( circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 ).result() self._compare_probs(result.quasi_dists, target) def test_run_with_shots_option_none(self): """test with shots=None option. Seed is ignored then.""" sampler = Sampler() result_42 = sampler.run( [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=42 ).result() result_15 = sampler.run( [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=15 ).result() self.assertDictAlmostEqual(result_42.quasi_dists, result_15.quasi_dists) def test_run_shots_result_size(self): """test with shots option to validate the result size""" n = 10 shots = 100 qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() sampler = Sampler() result = sampler.run(qc, [], shots=shots, seed=42).result() self.assertEqual(len(result.quasi_dists), 1) self.assertLessEqual(len(result.quasi_dists[0]), shots) self.assertAlmostEqual(sum(result.quasi_dists[0].values()), 1.0) def test_primitive_job_status_done(self): """test primitive job's status""" bell = self._circuit[1] sampler = Sampler() job = sampler.run(circuits=[bell]) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_options(self): """Test for options""" with self.subTest("init"): sampler = Sampler(options={"shots": 3000}) self.assertEqual(sampler.options.get("shots"), 3000) with self.subTest("set_options"): sampler.set_options(shots=1024, seed=15) self.assertEqual(sampler.options.get("shots"), 1024) self.assertEqual(sampler.options.get("seed"), 15) with self.subTest("run"): params, target = self._generate_params_target([1]) result = sampler.run([self._pqc], parameter_values=params).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(result.quasi_dists[0].shots, 1024) def test_circuit_with_unitary(self): """Test for circuit with unitary gate.""" gate = UnitaryGate(np.eye(2)) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = Sampler() sampler_result = sampler.run([circuit]).result() self.assertDictAlmostEqual(sampler_result.quasi_dists[0], {0: 1, 1: 0}) if __name__ == "__main__": unittest.main()
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb from qiskit import * nshots = 8192 IBMQ.load_account() provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') simulator = Aer.get_backend('qasm_simulator') device = provider.get_backend('ibm_nairobi') from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor qr = QuantumRegister(4); cr = ClassicalRegister(4); qc = QuantumCircuit(qr,cr) qc.h([0,1]) qc.barrier() qc.cx(0,2); qc.cx(0,3); qc.cx(1,2); qc.cx(1,3) # oraculo qc.barrier() qc.measure([2,3],[2,3]) qc.barrier() qc.h([0,1]); qc.measure([0,1],[0,1]) qc.draw(output='mpl') jobS = execute(qc, backend = simulator, shots = nshots) jobE = execute(qc, backend = device, shots = nshots) job_monitor(jobE) plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)], bar_labels = False, legend = ['sim', 'exp'])
https://github.com/martian17/qiskit-graph-coloring-hamiltonian
martian17
import math from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, BasicAer from qiskit.visualization import plot_histogram # 4,0 -> 00 # 4,1 -> 01 # 4,2 -> 10 # 4,3 -> 11 # 4, 3 -> 11 # 2,3 -> 1,1 # 1,1 -> exit def genvec(veclen, n): vec = [] veclen = int(veclen/2) while veclen > 0: if veclen <= n: n = n - veclen vec.append(1) else: vec.append(0) veclen = int(veclen/2) vec.reverse() return vec def convertToState(v): # converts from [0,0,1,0] to [1,0] # initializing the returning vector lenv = len(v) for i in range(lenv): if v[i] != 0: return genvec(lenv,i) return False def mcts(circuit, controls, target, ancilla, activq):# multi cubit toffoli select for i in range(len(controls)): if activq[i] == 0: circuit.x(controls[i]) circuit.mct(controls, target, ancilla, 'basic') for i in range(len(controls)): if activq[i] == 0: circuit.x(controls[i]) def all0(v): for e in v: if e != 0: return False return True def fnon0(v): for e in v: if e != 0: return e return False def vdeg(v): for i in range(len(v)): e = v[i] if e != 0: return i return False def vecinfo(v): for i in range(len(v)): e = v[i] if e != 0: return [e,i] return False def make_circuit(hamil): matlen = len(hamil) N = int(math.log(matlen,2)) q1 = QuantumRegister(N) q2 = QuantumRegister(N) q3 = QuantumRegister(1) q4 = QuantumRegister(N) ancils = QuantumRegister(N) cr = ClassicalRegister(N) circuit = QuantumCircuit(q1,q2,q3,q4,ancils,cr) print(q1) # w for i in range(matlen): if all0(hamil[i]): continue # if there is no correcponding state else: # find the target val = fnon0(hamil[i]) targetLocation = genvec(matlen,val) # weight print(hamil[i],i,targetLocation) for j in range(N):# for each controlled output if targetLocation[j] == 1: print(matlen,j,i) mcts(circuit, q1, q4[j], ancils, genvec(matlen,i)) circuit.barrier() print("b") # m for i in range(matlen): if all0(hamil[i]): continue # if there is no correcponding state else: # find the target val = fnon0(hamil[i]) targetLocation = convertToState(hamil[i]) # multiplication result print(hamil[i],i,targetLocation) for j in range(N):# for each controlled output if targetLocation[j] == 1: print(matlen,j,i) mcts(circuit, q1, q2[j], ancils, genvec(matlen,i)) # f # -a # -m return circuit make_circuit( [ [0,2,0,0], [2,0,0,0], [0,0,0,1], [0,0,1,0] ] ).draw(output = "mpl")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """UnitaryGate tests""" import json import numpy from numpy.testing import assert_allclose import qiskit from qiskit.extensions.unitary import UnitaryGate from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.operators import Operator from qiskit.transpiler.passes import CXCancellation class TestUnitaryGate(QiskitTestCase): """Tests for the Unitary class.""" def test_set_matrix(self): """Test instantiation""" try: UnitaryGate([[0, 1], [1, 0]]) # pylint: disable=broad-except except Exception as err: self.fail(f"unexpected exception in init of Unitary: {err}") def test_set_matrix_raises(self): """test non-unitary""" try: UnitaryGate([[1, 1], [1, 0]]) # pylint: disable=broad-except except Exception: pass else: self.fail("setting Unitary with non-unitary did not raise") def test_set_init_with_unitary(self): """test instantiation of new unitary with another one (copy)""" uni1 = UnitaryGate([[0, 1], [1, 0]]) uni2 = UnitaryGate(uni1) self.assertEqual(uni1, uni2) self.assertFalse(uni1 is uni2) def test_conjugate(self): """test conjugate""" ymat = numpy.array([[0, -1j], [1j, 0]]) uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.conjugate().to_matrix(), ymat)) def test_adjoint(self): """test adjoint operation""" uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.adjoint().to_matrix(), uni.to_matrix())) class TestUnitaryCircuit(QiskitTestCase): """Matrix gate circuit tests.""" def test_1q_unitary(self): """test 1 qubit unitary matrix""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) qc.x(qr[0]) qc.append(UnitaryGate(matrix), [qr[0]]) # test of qasm output self.log.info(qc.qasm()) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("unitary") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0],)) assert_allclose(dnode.op.to_matrix(), matrix) def test_2q_unitary(self): """test 2 qubit unitary matrix""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) qc.x(qr[0]) uni2q = UnitaryGate(matrix) qc.append(uni2q, [qr[0], qr[1]]) passman = PassManager() passman.append(CXCancellation()) qc2 = passman.run(qc) # test of qasm output self.log.info(qc2.qasm()) # test of text drawer self.log.info(qc2) dag = circuit_to_dag(qc) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) assert_allclose(dnode.op.to_matrix(), matrix) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_unitary(self): """test 3 qubit unitary matrix on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.x(qr[0]) uni3q = UnitaryGate(matrix) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) assert_allclose(dnode.op.to_matrix(), matrix) def test_1q_unitary_int_qargs(self): """test single qubit unitary matrix with 'int' and 'list of ints' qubits argument""" sigmax = numpy.array([[0, 1], [1, 0]]) sigmaz = numpy.array([[1, 0], [0, -1]]) # new syntax qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.unitary(sigmax, 0) qc.unitary(sigmax, qr[1]) qc.unitary(sigmaz, [0, 1]) # expected circuit qc_target = QuantumCircuit(qr) qc_target.append(UnitaryGate(sigmax), [0]) qc_target.append(UnitaryGate(sigmax), [qr[1]]) qc_target.append(UnitaryGate(sigmaz), [[0, 1]]) self.assertEqual(qc, qc_target) def test_qobj_with_unitary_matrix(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.rx(numpy.pi / 4, qr[0]) uni = UnitaryGate(matrix) qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "unitary") assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix) # check conversion to dict qobj_dict = qobj.to_dict() class NumpyEncoder(json.JSONEncoder): """Class for encoding json str with complex and numpy arrays.""" def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) # check json serialization self.assertTrue(isinstance(json.dumps(qobj_dict, cls=NumpyEncoder), str)) def test_labeled_unitary(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) uni = UnitaryGate(matrix, label="xy") qc.append(uni, [qr[0], qr[1]]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[0] self.assertEqual(instr.name, "unitary") self.assertEqual(instr.label, "xy") def test_qasm_unitary_only_one_def(self): """test that a custom unitary can be converted to qasm and the definition is only written once""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_twice(self): """test that a custom unitary can be converted to qasm and that if the qasm is called twice it is the same every time""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_2q_unitary(self): """test that a 2 qubit custom unitary can be converted to qasm""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.asarray([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0], qr[1]]) qc.append(unitary_gate, [qr[1], qr[0]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1 { u(pi,-pi/2,pi/2) q0; u(pi,pi/2,-pi/2) q1; }\n" "qreg q0[2];\n" "creg c0[1];\n" "x q0[0];\n" "unitary q0[0],q0[1];\n" "unitary q0[1],q0[0];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_noop(self): """Test that an identity unitary can be converted to OpenQASM 2""" qc = QuantumCircuit(QuantumRegister(3, "q0")) qc.unitary(numpy.eye(8), qc.qubits) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1,q2 { }\n" "qreg q0[3];\n" "unitary q0[0],q0[1],q0[2];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_unitary_decomposition(self): """Test decomposition for unitary gates over 2 qubits.""" qc = QuantumCircuit(3) qc.unitary(random_unitary(8, seed=42), [0, 1, 2]) self.assertTrue(Operator(qc).equiv(Operator(qc.decompose()))) def test_unitary_decomposition_via_definition(self): """Test decomposition for 1Q unitary via definition.""" mat = numpy.array([[0, 1], [1, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_decomposition_via_definition_2q(self): """Test decomposition for 2Q unitary via definition.""" mat = numpy.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_control(self): """Test parameters of controlled - unitary.""" mat = numpy.array([[0, 1], [1, 0]]) gate = UnitaryGate(mat).control() self.assertTrue(numpy.allclose(gate.params, mat)) self.assertTrue(numpy.allclose(gate.base_gate.params, mat))
https://github.com/Qiskit/feedback
Qiskit
# imports from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import PermutationGate from qiskit.transpiler.passes.synthesis.high_level_synthesis import ( HighLevelSynthesis, HighLevelSynthesisPluginManager, HighLevelSynthesisPlugin, HLSConfig, ) from qiskit.compiler import transpile from qiskit.transpiler import CouplingMap qc = QuantumCircuit(6) perm = PermutationGate([1, 2, 3, 4, 0]) qc.append(perm, [1, 2, 3, 4, 5]) qc.draw(output='mpl') qct = transpile(qc) qct.draw(output='mpl') qct = HighLevelSynthesis()(qc) qct.draw(output='mpl') print(HighLevelSynthesisPluginManager().method_names("permutation")) config = HLSConfig(permutation=["acg"]) qct = HighLevelSynthesis(hls_config=config)(qc) qct.draw(output='mpl') config = HLSConfig(permutation=["kms"]) qct = HighLevelSynthesis(hls_config=config)(qc) qct.draw(output='mpl') config = HLSConfig(permutation=["kms"]) qct = transpile(qc, hls_config=config) qct.draw(output='mpl') config = HLSConfig(permutation=["token_swapper"]) qct = HighLevelSynthesis(hls_config=config)(qc) qct.draw(output='mpl') config = HLSConfig(permutation=["token_swapper"]) coupling_map = CouplingMap([[1, 2], [1, 3], [1, 4], [1, 5]]) qct = HighLevelSynthesis(hls_config=config, coupling_map=coupling_map, use_qubit_indices=True)(qc) qct.draw(output='mpl') config = HLSConfig(permutation=["token_swapper"]) coupling_map = CouplingMap([[1, 2], [2, 3], [2, 4], [2, 5]]) qct = HighLevelSynthesis(hls_config=config, coupling_map=coupling_map, use_qubit_indices=True)(qc) qct.draw(output='mpl') config = HLSConfig(permutation=["token_swapper"]) coupling_map = CouplingMap.from_ring(6) qct = HighLevelSynthesis(hls_config=config, coupling_map=coupling_map, use_qubit_indices=True)(qc) qct.draw(output='mpl') coupling_map = CouplingMap([[0, 1], [1, 2], [3, 4], [4, 5]]) config = HLSConfig(permutation=["token_swapper"]) qc = QuantumCircuit(6) qc.append(PermutationGate([1, 0, 3, 2]), [1, 2, 3, 4]) config = HLSConfig(permutation=[("token_swapper", {"trials": 10})]) qct = HighLevelSynthesis(hls_config=config, coupling_map=coupling_map, use_qubit_indices=True)(qc) qct.draw(output='mpl') coupling_map = CouplingMap([[0, 1], [1, 2], [3, 4], [4, 5]]) config = HLSConfig(permutation=["token_swapper"]) qc = QuantumCircuit(6) qc.append(PermutationGate([1, 0, 3, 2]), [1, 4, 2, 3]) config = HLSConfig(permutation=[("token_swapper", {"trials": 10})]) qct = HighLevelSynthesis(hls_config=config, coupling_map=coupling_map, use_qubit_indices=True)(qc) qct.draw(output='mpl')
https://github.com/Pitt-JonesLab/clonk_transpilation
Pitt-JonesLab
import numpy as np from scipy.linalg import expm from qiskit.circuit.library import * S = expm( -1j * np.pi * (XGate().to_matrix() + YGate().to_matrix() + ZGate().to_matrix()) / np.sqrt(33) ) from qiskit.extensions.unitary import UnitaryGate from qiskit import QuantumCircuit S_gate = UnitaryGate(S) qc = QuantumCircuit(1) qc.append(S_gate, [0]) qc.draw(output="mpl") from qiskit.transpiler.passes import ( BasisTranslator, UnrollCustomDefinitions, Optimize1qGates, ) from qiskit.transpiler import PassManager from qiskit.circuit.equivalence_library import StandardEquivalenceLibrary as _sel pass_ = [UnrollCustomDefinitions(_sel, ["u3"]), BasisTranslator(_sel, ["rz", "sx"])] pm = PassManager(pass_) new_circ = pm.run(qc) new_circ.draw(output="mpl") # verify correctness from qiskit.quantum_info.operators import Operator Operator(new_circ).equiv(qc) from qiskit.quantum_info.synthesis.one_qubit_decompose import OneQubitEulerDecomposer decomposer = OneQubitEulerDecomposer("ZSXX") euler_circ = decomposer(S) euler_circ.draw(output="mpl") # verify correctness Operator(new_circ).equiv(qc) from qiskit.quantum_info.synthesis.one_qubit_decompose import OneQubitEulerDecomposer decomposer = OneQubitEulerDecomposer("ZXZ") euler_decomp = decomposer(S) euler_decomp.draw(output="mpl") alpha, gamma, delta = [gate[0].params[0] for gate in euler_decomp] new_circ2 = QuantumCircuit(1) new_circ2.rz(alpha - np.pi / 2, 0) new_circ2.sx(0) new_circ2.rz(np.pi - gamma, 0) new_circ2.sx(0) new_circ2.rz(delta - np.pi / 2, 0) new_circ2.draw(output="mpl") # verify correctness Operator(new_circ).equiv(qc)
https://github.com/KMU-quantum-classroom/qiskit-classroom-converter
KMU-quantum-classroom
""" converter service """ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import typing from enum import Enum import numpy as np from qiskit import QuantumCircuit from qiskit_class_converter.converters.matrix_to_quantum_circuit \ import MatrixToQuantumCircuitConverter from qiskit_class_converter.converters.quantum_circuit_to_braket_notation \ import QuantumCircuitToBraketNotationConverter from qiskit_class_converter.converters.quantum_circuit_to_matrix \ import QuantumCircuitToMatrixConverter from qiskit_class_converter.converters.string_to_braket_notation \ import StringToBraketNotationConverter class ConversionType(Enum): """ Conversion Type """ QC_TO_BRA_KET = QuantumCircuitToBraketNotationConverter """```python from qiskit import QuantumCircuit from qiskit_class_converter import ConversionService quantum_circuit = QuantumCircuit(2, 2) quantum_circuit.x(0) quantum_circuit.cx(0, 1) sample_converter = ConversionService(conversion_type="QC_TO_BRA_KET") result = sample_converter.convert(input_value=quantum_circuit) ```""" QC_TO_MATRIX = QuantumCircuitToMatrixConverter """```python from qiskit import QuantumCircuit from qiskit_class_converter import ConversionService quantum_circuit = QuantumCircuit(2, 2) quantum_circuit.x(0) quantum_circuit.cx(0, 1) sample_converter = ConversionService(conversion_type="QC_TO_MATRIX") result = sample_converter.convert(input_value=quantum_circuit) ```""" MATRIX_TO_QC = MatrixToQuantumCircuitConverter """```python from qiskit import QuantumCircuit from qiskit_class_converter import ConversionService input_value = [ [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0] ] sample_converter = ConversionService(conversion_type="MATRIX_TO_QC") result = sample_converter.convert(input_value=input_value) # using user's QuantumCircuit object quantum_circuit = QuantumCircuit(2, 2) quantum_circuit.append(result, [0, 1]) ```""" STR_TO_BRA_KET = StringToBraketNotationConverter """```python from qiskit import QuantumCircuit from qiskit_class_converter import ConversionService sample_converter = ConversionService(conversion_type="STR_TO_BRA_KET") sample_converter.convert(input_value="|01>") ```""" class ConversionService: # pylint: disable=too-few-public-methods """ Conversion Service class ```python from qiskit_class_converter import ConversionService ConversionService(conversion_type="QC_TO_BRA_KET", option={"expression": "simplify"}) ``` """ def __init__(self, conversion_type: typing.Union[str, ConversionType], option=None): """ init function :param conversion_type: QC_TO_BRA_KET, QC_TO_MATRIX, MATRIX_TO_QC, STR_TO_BRA_KET :param option: See the Options table in this article. """ if option is None: self.option = {} self.option = option if isinstance(conversion_type, str): self.__conversion_object = ConversionType[conversion_type.upper()].value elif isinstance(conversion_type, ConversionType): self.__conversion_object = conversion_type.value def convert(self, input_value: typing.Union[list, np.ndarray, QuantumCircuit, str]): """ convert functions result = sample_converter.convert(input_value=quantum_circuit) logger.info(result) :param input_value: QuantumCircuit or MATRIX or BRA_KET String :return: Converted result """ convert = self.__conversion_object(self.option).convert(input_value) return convert
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the BasicSwap pass""" import unittest from qiskit.transpiler.passes import BasicSwap from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.layout import Layout from qiskit.transpiler import CouplingMap, Target from qiskit.circuit.library import CXGate from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestBasicSwap(QiskitTestCase): """Tests the BasicSwap pass.""" def test_trivial_case(self): """No need to have any swap, the CX are distance 1 to each other q0:--(+)-[U]-(+)- | | q1:---.-------|-- | q2:-----------.-- CouplingMap map: [1]--[0]--[2] """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_trivial_in_same_layer(self): """No need to have any swap, two CXs distance 1 to each other, in the same layer q0:--(+)-- | q1:---.--- q2:--(+)-- | q3:---.--- CouplingMap map: [0]--[1]--[2]--[3] """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[2], qr[3]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_a_single_swap(self): """Adding a swap q0:------- q1:--(+)-- | q2:---.--- CouplingMap map: [1]--[0]--[2] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_a_single_swap_with_target(self): """Adding a swap q0:------- q1:--(+)-- | q2:---.--- CouplingMap map: [1]--[0]--[2] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ target = Target() target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None}) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(target) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_a_single_swap_bigger_cm(self): """Swapper in a bigger coupling map q0:------- q1:---.--- | q2:--(+)-- CouplingMap map: [1]--[0]--[2]--[3] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ coupling = CouplingMap([[0, 1], [0, 2], [2, 3]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_keep_layout(self): """After a swap, the following gates also change the wires. qr0:---.---[H]-- | qr1:---|-------- | qr2:--(+)------- CouplingMap map: [0]--[1]--[2] qr0:--X----------- | qr1:--X---.--[H]-- | qr2:-----(+)------ """ coupling = CouplingMap([[1, 0], [1, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.h(qr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.cx(qr[1], qr[2]) expected.h(qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap(self): """A far swap that affects coming CXs. qr0:--(+)---.-- | | qr1:---|----|-- | | qr2:---|----|-- | | qr3:---.---(+)- CouplingMap map: [0]--[1]--[2]--[3] qr0:--X-------------- | qr1:--X--X----------- | qr2:-----X--(+)---.-- | | qr3:---------.---(+)- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.swap(qr[1], qr[2]) expected.cx(qr[2], qr[3]) expected.cx(qr[3], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_front(self): """A far swap with a gate in the front. q0:------(+)-- | q1:-------|--- | q2:-------|--- | q3:--[H]--.--- CouplingMap map: [0]--[1]--[2]--[3] q0:-----------(+)-- | q1:---------X--.--- | q2:------X--X------ | q3:-[H]--X--------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.h(qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(qr[3]) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_back(self): """A far swap with a gate in the back. q0:--(+)------ | q1:---|------- | q2:---|------- | q3:---.--[H]-- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)------ | q1:-----X--.--[H]-- | q2:--X--X---------- | q3:--X------------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) expected.h(qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_middle(self): """A far swap with a gate in the middle. q0:--(+)-------.-- | | q1:---|--------|-- | q2:---|--------|-- | | q3:---.--[H]--(+)- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)-------.--- | | q1:-----X--.--[H]--(+)-- | q2:--X--X--------------- | q3:--X------------------ """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) circuit.cx(qr[0], qr[3]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) expected.h(qr[1]) expected.cx(qr[0], qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_fake_run(self): """A fake run, doesn't change dag q0:--(+)-------.-- | | q1:---|--------|-- | q2:---|--------|-- | | q3:---.--[H]--(+)- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)-------.--- | | q1:-----X--.--[H]--(+)-- | q2:--X--X--------------- | q3:--X------------------ """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) circuit.cx(qr[0], qr[3]) fake_pm = PassManager([BasicSwap(coupling, fake_run=True)]) real_pm = PassManager([BasicSwap(coupling, fake_run=False)]) self.assertEqual(circuit, fake_pm.run(circuit)) self.assertNotEqual(circuit, real_pm.run(circuit)) self.assertIsInstance(fake_pm.property_set["final_layout"], Layout) self.assertEqual(fake_pm.property_set["final_layout"], real_pm.property_set["final_layout"]) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for layouts of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import layouts class TestBitArrange(QiskitTestCase): """Tests for layout.bit_arrange.""" def setUp(self) -> None: """Setup.""" super().setUp() qregs = qiskit.QuantumRegister(3) cregs = qiskit.ClassicalRegister(3) self.regs = list(qregs) + list(cregs) def test_qreg_creg_ascending(self): """Test qreg_creg_ascending layout function.""" sorted_regs = layouts.qreg_creg_ascending(self.regs) ref_regs = [ self.regs[0], self.regs[1], self.regs[2], self.regs[3], self.regs[4], self.regs[5], ] self.assertListEqual(sorted_regs, ref_regs) def test_qreg_creg_descending(self): """Test qreg_creg_descending layout function.""" sorted_regs = layouts.qreg_creg_descending(self.regs) ref_regs = [ self.regs[2], self.regs[1], self.regs[0], self.regs[5], self.regs[4], self.regs[3], ] self.assertListEqual(sorted_regs, ref_regs) class TestAxisMap(QiskitTestCase): """Tests for layout.time_axis_map.""" def test_time_map_in_dt(self): """Test time_map_in_dt layout function.""" axis_config = layouts.time_map_in_dt(time_window=(-100, 500)) self.assertEqual(axis_config.window, (-100, 500)) self.assertEqual(axis_config.label, "System cycle time (dt)") ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"} self.assertDictEqual(axis_config.axis_map, ref_map)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/sebasmos/QuantumVE
sebasmos
import qiskit as q from qiskit import IBMQ %matplotlib inline IBMQ.save_account("5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3") # Details in: https://qiskit.org/documentation/install.html # https://quantumcomputing.stackexchange.com/questions/7098/loading-qiskit-account-in-the-jupyter-notebook-gives-requestsapierror-error ''' IBMQ.delete_account() IBMQ.active_account() ''' API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3" IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() circuit = q.QuantumCircuit(2,2) # 2 qubits, 2 classical bits # Currently: 0,0 circuit.x(0) # Creates quantum bit of 0,1 or any combination of both #1,0 circuit.cx(0,1) #cnot, controlled not, Flibs 2nd qubit value if first quibit is 1 #1,1 circuit.measure([0,1],[0,1]) # Observer performs measurements between the qubit and classical bit circuit.draw() # pip install pylatexenc circuit.draw(output = "mpl") provider = IBMQ.get_provider("ibm-q") for backend in provider.backends(): try: qubit_count = len(backend.properties().quibits) except: qubit_count = "simulated" print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits") from qiskit.tools.monitor import job_monitor backend = provider.get_backend("ibmq_bogota") job = q.execute(circuit, backend, shots = 500) job_monitor(job) from qiskit.visualization import plot_histogram from matplotlib import style style.use("dark_background") result = job.result() counts = result.get_counts(circuit) plot_histogram([counts]) # Currently: 0,0 circuit.h(0) # Creates quantum bit of 0,1 or any combination of both #1,0 circuit.cx(0,1) #cnot, controlled not, Flibs 2nd qubit value if first quibit is 1 #1,1 circuit.measure([0,1],[0,1]) # Observer performs measurements between the qubit and classical bit circuit.draw() job = q.execute(circuit, backend, shots = 500) job_monitor(job) result = job.result() counts = result.get_counts(circuit) plot_histogram([counts])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.algorithms import AmplificationProblem # the state we desire to find is '11' good_state = ['11'] # specify the oracle that marks the state '11' as a good solution oracle = QuantumCircuit(2) oracle.cz(0, 1) # define Grover's algorithm problem = AmplificationProblem(oracle, is_good_state=good_state) # now we can have a look at the Grover operator that is used in running the algorithm # (Algorithm circuits are wrapped in a gate to appear in composition as a block # so we have to decompose() the op to see it expanded into its component gates.) problem.grover_operator.decompose().draw(output='mpl') from qiskit.algorithms import Grover from qiskit.primitives import Sampler grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) from qiskit.quantum_info import Statevector oracle = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) problem.grover_operator.oracle.decompose().draw(output='mpl') from qiskit.circuit.library.phase_oracle import PhaseOracle from qiskit.exceptions import MissingOptionalLibraryError # `Oracle` (`PhaseOracle`) as the `oracle` argument expression = '(a & b)' try: oracle = PhaseOracle(expression) problem = AmplificationProblem(oracle) display(problem.grover_operator.oracle.decompose().draw(output='mpl')) except MissingOptionalLibraryError as ex: print(ex) import numpy as np # Specifying `state_preparation` # to prepare a superposition of |01>, |10>, and |11> oracle = QuantumCircuit(3) oracle.ccz(0, 1, 2) theta = 2 * np.arccos(1 / np.sqrt(3)) state_preparation = QuantumCircuit(3) state_preparation.ry(theta, 0) state_preparation.ch(0,1) state_preparation.x(1) state_preparation.h(2) # we only care about the first two bits being in state 1, thus add both possibilities for the last qubit problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111']) # state_preparation print('state preparation circuit:') problem.grover_operator.state_preparation.draw(output='mpl') grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) oracle = QuantumCircuit(5) oracle.ccz(0, 1, 2) oracle.draw(output='mpl') from qiskit.circuit.library import GroverOperator grover_op = GroverOperator(oracle, insert_barriers=True) grover_op.decompose().draw(output='mpl') grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True) grover_op.decompose().draw(output='mpl') # a list of binary strings good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = ['11', '00'] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # a list of integer good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = [0, 1] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) from qiskit.quantum_info import Statevector # `Statevector` good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # Callable good state def callable_good_state(bitstr): if bitstr == "11": return True return False oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # integer iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=1) # list iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3]) # using sample_from_iterations oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True) iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8) iterations def to_DIAMACS_CNF_format(bit_rep): return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)] oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format) problem.post_processing([1, 0, 1]) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/carstenblank/dc-qiskit-algorithms
carstenblank
# Copyright 2018 Carsten Blank # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from typing import List, Union import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import Gate, Instruction, Qubit from qiskit.extensions import RYGate, RZGate from scipy import sparse from scipy.sparse.linalg import norm from .UniformRotation import UniformRotationGate def get_alpha_z(omega, n, k): # type: (sparse.dok_matrix, int, int) -> sparse.dok_matrix """ Computes the rotation angles alpha for the z-rotations :param omega: the input phase :param n: total number of qubits :param k: current qubit :return: a sparse vector """ alpha_z_k = sparse.dok_matrix((2 ** (n - k), 1), dtype=np.float64) for (i, _), om in omega.items(): i += 1 j = int(np.ceil(i * 2 ** (-k))) s_condition = 2 ** (k - 1) * (2 * j - 1) s_i = 1.0 if i > s_condition else -1.0 alpha_z_k[j - 1, 0] = alpha_z_k[j - 1, 0] + s_i * om / 2 ** (k - 1) return alpha_z_k def get_alpha_y(a, n, k): # type: (sparse.dok_matrix, int, int) -> sparse.dok_matrix """ Computes the rotation angles alpha for the y-rotations :param a: the input absolute values :param n: total number of qubits :param k: current qubit :return: a sparse vector """ alpha = sparse.dok_matrix((2**(n - k), 1), dtype=np.float64) numerator = sparse.dok_matrix((2 ** (n - k), 1), dtype=np.float64) denominator = sparse.dok_matrix((2 ** (n - k), 1), dtype=np.float64) for (i, _), e in a.items(): j = int(math.ceil((i + 1) / 2**k)) l = (i + 1) - (2*j - 1)*2**(k-1) is_part_numerator = 1 <= l <= 2**(k-1) if is_part_numerator: numerator[j - 1, 0] += e*e denominator[j - 1, 0] += e*e for (j, _), e in numerator.items(): numerator[j, 0] = np.sqrt(e) for (j, _), e in denominator.items(): denominator[j, 0] = 1/np.sqrt(e) pre_alpha = numerator.multiply(denominator) # type: sparse.csr_matrix for (j, _), e in pre_alpha.todok().items(): alpha[j, 0] = 2*np.arcsin(e) return alpha class RZGateNegatedAngle(RZGate): def __init__(self, phi): super().__init__(-phi) class RYGateNegatedAngle(RYGate): def __init__(self, phi): super().__init__(-phi) # noinspection NonAsciiCharacters class MottonenStatePreparationGate(Gate): """Uniform rotation Y gate (Möttönen).""" def __init__(self, vector, neglect_absolute_value=False): # type: (Union[sparse.dok_matrix, List[complex], List[float]], bool) -> None """ Create the composite gate for the Möttönen state preparation scheme with an input vector, which registers/qubits to apply it to, and the circuit (if any) :param vector: the input complex sparse vector :param neglect_absolute_value: When given a vector, the absolute value is neglected which means that only the phase/angle is applied (RZ rotations) """ if isinstance(vector, list): vector = sparse.dok_matrix([vector]).transpose() self.neglect_absolute_value = neglect_absolute_value num_qubits = int(math.log2(vector.shape[0])) vector_str = ",".join([f'{v:.2f}' for v in vector.toarray()[:, 0]]) label = f'state({vector_str})' if len(vector) <= 16 else None super().__init__("state_prep_möttönen", num_qubits=num_qubits, params=[], label=label) self.vector = vector # type: sparse.dok_matrix def _define(self): a = sparse.dok_matrix(self.vector.get_shape()) # type: sparse.dok_matrix omega = sparse.dok_matrix(self.vector.get_shape()) # type: sparse.dok_matrix for (i, j), v in self.vector.items(): a[i, j] = np.absolute(v) omega[i, j] = np.angle(v) # As the subspace phase correction is a very expensive module, we only want to do it if the # z rotation matrix is non-zero! no_z_rotations = abs(norm(omega)) < 1e-3 q = QuantumRegister(self.num_qubits, "qubits") qc: QuantumCircuit = QuantumCircuit(q, name=self.name) if not no_z_rotations: qc_rot_z = self.apply_rot_z(omega, q) qc = qc.compose(qc_rot_z) if not self.neglect_absolute_value: qc_rot_y = self.apply_rot_y(a, q) qc = qc.compose(qc_rot_y) self._definition = qc.inverse() @staticmethod def apply_rot_y(a, qreg): # type: (sparse.dok_matrix, QuantumRegister) -> QuantumCircuit """ Applies the cascade of y-uniform rotations to the qubits :param a: the sparse absolute value vector :param qreg: quantum register to which the scheme are applied :return: None """ qc = QuantumCircuit(qreg, name='apply_rot_y') # type: QuantumCircuit num_qubits = int(math.log2(a.shape[0])) for k in range(1, num_qubits + 1): alpha_y_k = get_alpha_y(a, num_qubits, k) # type: sparse.dok_matrix control = qreg[k:] target = qreg[k - 1] qc.append(UniformRotationGate(gate=RYGateNegatedAngle, alpha=alpha_y_k), control + [target], []) return qc @staticmethod def apply_rot_z(omega, qreg): # type: (sparse.dok_matrix, QuantumRegister) -> QuantumCircuit """ Applies the cascade of z-uniform rotations to the qubits :param omega: the sparse phase vector :param qreg: quantum register to which the scheme are applied :return: None """ qc = QuantumCircuit(qreg, name='apply_rot_z') # type: QuantumCircuit num_qubits = int(math.log2(omega.shape[0])) for k in range(1, num_qubits + 1): alpha_z_k = get_alpha_z(omega, num_qubits, k) control = qreg[k:] target = qreg[k - 1] # if len(alpha_z_k) != 0: qc.append(UniformRotationGate(gate=RZGateNegatedAngle, alpha=alpha_z_k), control + [target], []) return qc # noinspection NonAsciiCharacters def state_prep_möttönen(self, a, qubits): # type: (QuantumCircuit, Union[List[float], sparse.dok_matrix], Union[List[Qubit], QuantumRegister]) -> Instruction """ Convenience function to encapsulate the composite gate of the state preparation :param self: Quantum circuit to apply this to :param a: the input vector :param qubits: the qubits to be transformed :return: gate just added """ if isinstance(qubits, QuantumRegister): qubits = list(qubits) if isinstance(a, sparse.dok_matrix): return self.append(MottonenStatePreparationGate(a), qubits, []) else: return self.append(MottonenStatePreparationGate(sparse.dok_matrix([a]).transpose()), qubits) # noinspection NonAsciiCharacters def state_prep_möttönen_dg(self, a, qubits): # type: (QuantumCircuit, Union[List[float], sparse.dok_matrix], Union[List[Qubit], QuantumRegister]) -> Instruction """ Convenience function to encapsulate the composite gate of the dagger of the state preparation :param self: Composite Gate or Quantum circuit to apply this to :param a: the input vector :param qubits: the qubits to be transformed :return: gate or instruction set """ return state_prep_möttönen(self, a, qubits).inverse() # noinspection NonAsciiCharacters QuantumCircuit.state_prep_möttönen = state_prep_möttönen # noinspection NonAsciiCharacters QuantumCircuit.state_prep_möttönen_dg = state_prep_möttönen_dg
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
#Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt #Import Qiskit classes classes import qiskit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error #Import the qv function. import qiskit.ignis.verification.quantum_volume as qv # qubit_lists: list of list of qubit subsets to generate QV circuits qubit_lists = [[0,1,3],[0,1,3,5],[0,1,3,5,7],[0,1,3,5,7,10]] # ntrials: Number of random circuits to create for each subset ntrials = 50 qv_circs, qv_circs_nomeas = qv.qv_circuits(qubit_lists, ntrials) #pass the first trial of the nomeas through the transpiler to illustrate the circuit qv_circs_nomeas[0] = qiskit.compiler.transpile(qv_circs_nomeas[0], basis_gates=['u1','u2','u3','cx']) print(qv_circs_nomeas[0][0]) #The Unitary is an identity (with a global phase) backend = qiskit.Aer.get_backend('statevector_simulator') ideal_results = [] for trial in range(ntrials): print('Simulating trial %d'%trial) ideal_results.append(qiskit.execute(qv_circs_nomeas[trial], backend=backend).result()) qv_fitter = qv.QVFitter(qubit_lists=qubit_lists) qv_fitter.add_statevectors(ideal_results) for qubit_list in qubit_lists: l = len(qubit_list) print ('qv_depth_'+str(l)+'_trial_0:', qv_fitter._heavy_outputs['qv_depth_'+str(l)+'_trial_0']) for qubit_list in qubit_lists: l = len(qubit_list) print ('qv_depth_'+str(l)+'_trial_0:', qv_fitter._heavy_output_prob_ideal['qv_depth_'+str(l)+'_trial_0']) noise_model = NoiseModel() p1Q = 0.002 p2Q = 0.02 noise_model.add_all_qubit_quantum_error(depolarizing_error(p1Q, 1), 'u2') noise_model.add_all_qubit_quantum_error(depolarizing_error(2*p1Q, 1), 'u3') noise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx') #noise_model = None backend = qiskit.Aer.get_backend('qasm_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now shots = 1024 exp_results = [] for trial in range(ntrials): print('Running trial %d'%trial) exp_results.append(qiskit.execute(qv_circs[trial], basis_gates=basis_gates, backend=backend, noise_model=noise_model, backend_options={'max_parallel_experiments': 0}).result()) qv_fitter.add_data(exp_results) for qubit_list in qubit_lists: l = len(qubit_list) #print (qv_fitter._heavy_output_counts) print ('qv_depth_'+str(l)+'_trial_0:', qv_fitter._heavy_output_counts['qv_depth_'+str(l)+'_trial_0']) plt.figure(figsize=(10, 6)) ax = plt.gca() # Plot the essence by calling plot_rb_data qv_fitter.plot_qv_data(ax=ax, show_plt=False) # Add title and label ax.set_title('Quantum Volume for up to %d Qubits \n and %d Trials'%(len(qubit_lists[-1]), ntrials), fontsize=18) plt.show() qv_success_list = qv_fitter.qv_success() qv_list = qv_fitter.ydata QV = 1 for qidx, qubit_list in enumerate(qubit_lists): if qv_list[0][qidx]>2/3: if qv_success_list[qidx][0]: print("Width/depth %d greater than 2/3 (%f) with confidence %f (successful). Quantum volume %d"% (len(qubit_list),qv_list[0][qidx],qv_success_list[qidx][1],qv_fitter.quantum_volume()[qidx])) QV = qv_fitter.quantum_volume()[qidx] else: print("Width/depth %d greater than 2/3 (%f) with confidence %f (unsuccessful)."% (len(qubit_list),qv_list[0][qidx],qv_success_list[qidx][1])) else: print("Width/depth %d less than 2/3 (unsuccessful)."%len(qubit_list)) print ("The Quantum Volume is:", QV)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXSimple())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2 pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc = QuantumCircuit(pw_approximation.num_qubits) qc.h(list(range(num_state_qubits))) qc.append(pw_approximation.to_instruction(), qc.qubits) qc.draw(output='mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test QGT.""" import unittest from ddt import ddt, data import numpy as np from qiskit import QuantumCircuit from qiskit_algorithms.gradients import DerivativeType, LinCombQGT, ReverseQGT from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit.test import QiskitTestCase from .logging_primitives import LoggingEstimator @ddt class TestQGT(QiskitTestCase): """Test QGT""" def setUp(self): super().setUp() self.estimator = Estimator() @data(LinCombQGT, ReverseQGT) def test_qgt_derivative_type(self, qgt_type): """Test QGT derivative_type""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0], [np.pi / 2, np.pi / 4]] correct_values = [ np.array([[1, 0.707106781j], [-0.707106781j, 0.5]]) / 4, np.array([[1, 1j], [-1j, 1]]) / 4, ] # test real derivative with self.subTest("Test with DerivativeType.REAL"): qgt.derivative_type = DerivativeType.REAL for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].real, atol=1e-3) # test imaginary derivative with self.subTest("Test with DerivativeType.IMAG"): qgt.derivative_type = DerivativeType.IMAG for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].imag, atol=1e-3) # test real + imaginary derivative with self.subTest("Test with DerivativeType.COMPLEX"): qgt.derivative_type = DerivativeType.COMPLEX for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_phase_fix(self, qgt_type): """Test the phase-fix argument in a QGT calculation""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, phase_fix=False) # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0], [np.pi / 2, np.pi / 4]] correct_values = [ np.array([[1, 0.707106781j], [-0.707106781j, 1]]) / 4, np.array([[1, 1j], [-1j, 1]]) / 4, ] # test real derivative with self.subTest("Test phase fix with DerivativeType.REAL"): qgt.derivative_type = DerivativeType.REAL for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].real, atol=1e-3) # test imaginary derivative with self.subTest("Test phase fix with DerivativeType.IMAG"): qgt.derivative_type = DerivativeType.IMAG for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].imag, atol=1e-3) # test real + imaginary derivative with self.subTest("Test phase fix with DerivativeType.COMPLEX"): qgt.derivative_type = DerivativeType.COMPLEX for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_coefficients(self, qgt_type): """Test the derivative option of QGT""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) qc = RealAmplitudes(num_qubits=2, reps=1) qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0) qc.rx(3.0 * qc.parameters[2] + qc.parameters[3].sin(), 1) # test imaginary derivative param_list = [ [np.pi / 4 for param in qc.parameters], [np.pi / 2 for param in qc.parameters], ] correct_values = ( np.array( [ [ [5.707309, 4.2924833, 1.5295868, 0.1938604], [4.2924833, 4.9142136, 0.75, 0.8838835], [1.5295868, 0.75, 3.4430195, 0.0758252], [0.1938604, 0.8838835, 0.0758252, 1.1357233], ], [ [1.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 10.0, -0.0], [0.0, 0.0, -0.0, 1.0], ], ] ) / 4 ) for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_parameters(self, qgt_type): """Test the QGT with specified parameters""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.ry(b, 0) param_values = [np.pi / 4, np.pi / 4] qgt_result = qgt.run([qc], [param_values], [[a]]).result().qgts np.testing.assert_allclose(qgt_result[0], [[1 / 4]], atol=1e-3) with self.subTest("Test with different parameter orders"): c = Parameter("c") qc2 = QuantumCircuit(1) qc2.rx(a, 0) qc2.rz(b, 0) qc2.rx(c, 0) param_values = [np.pi / 4, np.pi / 4, np.pi / 4] params = [[a, b, c], [c, b, a], [a, c], [b, a]] expected = [ np.array( [ [0.25, 0.0, 0.1767767], [0.0, 0.125, -0.08838835], [0.1767767, -0.08838835, 0.1875], ] ), np.array( [ [0.1875, -0.08838835, 0.1767767], [-0.08838835, 0.125, 0.0], [0.1767767, 0.0, 0.25], ] ), np.array([[0.25, 0.1767767], [0.1767767, 0.1875]]), np.array([[0.125, 0.0], [0.0, 0.25]]), ] for i, param in enumerate(params): qgt_result = qgt.run([qc2], [param_values], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], expected[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_multi_arguments(self, qgt_type): """Test the QGT for multiple arguments""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.ry(b, 0) qc2 = QuantumCircuit(1) qc2.rx(a, 0) qc2.ry(b, 0) param_list = [[np.pi / 4], [np.pi / 2]] correct_values = [[[1 / 4]], [[1 / 4, 0], [0, 0]]] param_list = [[np.pi / 4, np.pi / 4], [np.pi / 2, np.pi / 2]] qgt_results = qgt.run([qc, qc2], param_list, [[a], None]).result().qgts for i, _ in enumerate(param_list): np.testing.assert_allclose(qgt_results[i], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_validation(self, qgt_type): """Test estimator QGT's validation""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args) a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) parameter_values = [[np.pi / 4]] with self.subTest("assert number of circuits does not match"): with self.assertRaises(ValueError): qgt.run([qc, qc], parameter_values) with self.subTest("assert number of parameter values does not match"): with self.assertRaises(ValueError): qgt.run([qc], [[np.pi / 4], [np.pi / 2]]) with self.subTest("assert number of parameters does not match"): with self.assertRaises(ValueError): qgt.run([qc], parameter_values, parameters=[[a], [a]]) def test_options(self): """Test QGT's options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) estimator = Estimator(options={"shots": 100}) with self.subTest("estimator"): qgt = LinCombQGT(estimator) options = qgt.options result = qgt.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QGT init"): qgt = LinCombQGT(estimator, options={"shots": 200}) result = qgt.run([qc], [[1]]).result() options = qgt.options self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("QGT update"): qgt = LinCombQGT(estimator, options={"shots": 200}) qgt.update_default_options(shots=100) options = qgt.options result = qgt.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QGT run"): qgt = LinCombQGT(estimator, options={"shots": 200}) result = qgt.run([qc], [[0]], shots=300).result() options = qgt.options self.assertEqual(result.options.get("shots"), 300) self.assertEqual(options.get("shots"), 200) def test_operations_preserved(self): """Test non-parameterized instructions are preserved and not unrolled.""" x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(2) circuit.initialize([0.5, 0.5, 0.5, 0.5]) # this should remain as initialize circuit.crx(x, 0, 1) # this should get unrolled circuit.ry(y, 0) values = [np.pi / 2, np.pi] expect = np.diag([0.25, 0.5]) / 4 ops = [] def operations_callback(op): ops.append(op) estimator = LoggingEstimator(operations_callback=operations_callback) qgt = LinCombQGT(estimator, derivative_type=DerivativeType.REAL) job = qgt.run([circuit], [values]) result = job.result() with self.subTest(msg="assert initialize is preserved"): self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops)) with self.subTest(msg="assert result is correct"): np.testing.assert_allclose(result.qgts[0], expect, atol=1e-5) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit # Create a circuit with a register of three qubits circ = QuantumCircuit(3) # H gate on qubit 0, putting this qubit in a superposition of |0> + |1>. circ.h(0) # A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state. circ.cx(0, 1) # CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state. circ.cx(0, 2) # Draw the circuit circ.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, backend=FakeBoeblingen())
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
hamburgerguy
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a Statevector state = Statevector(qc) plot_state_city(state)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are on 3.10 > python < 3.12 %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U # Import all in one cell import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import RealAmplitudes from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.visualization import plot_gate_map, plot_circuit_layout, plot_distribution from qiskit.circuit import ParameterVector from qiskit_aer import AerSimulator from qiskit_ibm_runtime import ( QiskitRuntimeService, EstimatorV2 as Estimator, SamplerV2 as Sampler, EstimatorOptions ) import warnings warnings.filterwarnings('ignore') ### Save API Token, if needed %set_env QXToken=deleteThisAndPasteYourTokenHere # Set Grade only mode %set_env QC_GRADE_ONLY=true # Make sure there is no space between the equal sign # and the beginning of your token # qc-grader should be 0.18.13 (or higher) import qc_grader qc_grader.__version__ from qc_grader.challenges.iqc_2024 import grade_lab_bonus_ex1, grade_lab_bonus_ex2, grade_lab_bonus_ex3 def old_amplitude_embedding(num_qubits, bird_index): """Create amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ def generate_GHZ(qc): qc.h(0) for i, j in zip(range(num_qubits-1), range(1,num_qubits)): qc.cx(i, j) ### Write your code below here ### def generate_binary(qc, number): position=0 bit=1 while number >= bit: if number & bit: qc.x(position) bit <<= 1 position=position+1 qc = QuantumCircuit(num_qubits) if bird_index < 5: generate_GHZ(qc) generate_binary(qc, bird_index) ### Don't change any code past this line ### return qc num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_osaka") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 # You can check different birds by changing the index qc = old_amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) source_list= [1 , 1 , 2 , 2 , 3 , 3 , 4 , 5 , 6, 7, 8, 9, 10, 8, 9, 10, 11, 12, 13, 14, 11, 15, 16, 17, 18, 19, 20, 21, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 38, 39, 40, 31, 33, 34, 35, 36, 37, 23, 25, 26] target_list=[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52] layer_list=[1, 2, 2, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] premade_layout= [63, 64, 62, 65, 54, 61, 72, 66, 45, 60, 81, 73, 46, 53, 67, 44, 59, 80, 85, 47, 41, 82, 68, 43, 58, 79, 86, 35, 40, 84, 48, 42, 83, 69, 34, 71, 91, 87, 28, 39, 93, 29, 33, 49, 92, 70, 24, 77, 98, 55, 57, 78] def new_amplitude_embedding(num_qubits, bird_index): """Create efficient amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ ### Write your code below here ### def generate_GHZ(qubits): qc = QuantumCircuit(qubits) qc.h(0) for i in range(qubits-1): qc.cx(source_list[i]-1, target_list[i]-1) return qc def generate_shifted_encoding(qubits, number, shift=0): qc = QuantumCircuit(qubits) position=shift bit=1 while number >= bit: if number & bit: qc.x(position) bit <<= 1 position=position+1 return qc def generate_normal_bird(qubits, number): return generate_shifted_encoding(qubits, number, 0) def generate_quantum_bird(qubits, number): return (generate_GHZ(qubits)).compose(generate_shifted_encoding(qubits, number, 0)) if bird_index < 5: qc = generate_quantum_bird(num_qubits,bird_index) else: qc = generate_normal_bird(num_qubits,bird_index) ### Don't change any code past this line ### return qc num_qubits = 50 index = 0 # Change to different values for testing qc = new_amplitude_embedding(num_qubits, index) qc.measure_all() # Define the backend and the pass manager aer_sim = AerSimulator(method='matrix_product_state') pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(qc) # Define the sampler with the number of shots sampler = Sampler(backend=aer_sim) result = sampler.run([isa_circuit]).result() samp_dist = result[0].data.meas.get_counts() plot_distribution(samp_dist, figsize=(10, 3)) num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_kyoto") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 #You can check different birds by changing the index qc = new_amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab_bonus_ex1(new_amplitude_embedding(50,3)) # Expected answer type: QuantumCircuit def generate_old_ansatz(qubits): qc = RealAmplitudes(qubits, reps=1, entanglement='pairwise') return qc num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_kyoto") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 # You can check different birds by changing the index qc = new_amplitude_embedding(num_qubits, index_bird) ansatz = generate_old_ansatz(num_qubits) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) transpiled_qc = pm.run(qc.compose(ansatz)) print('Depth new mapping + old ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) # transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) def generate_ansatz(num_qubits): """Generate a `RealAmplitudes` ansatz where all qubits are entangled with each other Parameters: num_qubits (int): Number of qubits for the ansatz Returns: qc (QuantumCircuit): Quantum circuit with the generated ansatz """ ### Write your code below here ### qc = QuantumCircuit(num_qubits) params=ParameterVector("x",num_qubits*2) for i in range(num_qubits): qc.ry(params[i],i) for n in range(3): for i in range(num_qubits-1): if layer_list[i] == n+1: qc.cx(source_list[i]-1, target_list[i]-1) for i in range(num_qubits): qc.ry(params[i+num_qubits],i) ### Don't change any code past this line ### return qc index_bird = 0 # You can check different birds by changing the index new_mapping_qc = new_amplitude_embedding(num_qubits, index_bird) ansatz = generate_ansatz(num_qubits) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) transpiled_qc = pm.run(new_mapping_qc.compose(ansatz)) print('Depth new mapping + new ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) # transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab_bonus_ex2(transpiled_qc) # Expected answer type: QuantumCircuit # Generate this to match your ansatz source_list= [1 , 1 , 2 , 2 , 3 , 3 , 4 , 5 , 6, 7, 8, 9, 10, 8, 9, 10, 11, 12, 13, 14, 11, 15, 16, 17, 18, 19, 20, 21, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 38, 39, 40, 31, 33, 34, 35, 36, 37, 23, 25, 26] def generalize_optimal_params(num_qubits, ansatz, source_list): """Generate a `list of optimal parameters for N qubits Parameters: num_qubits (int): Number of qubits for the ansatz ansatz (QuantumCircuit): Ansatz for our VQC source_list (list): List of qubits used as source to entangle other qubits Returns: opt_params (list): List of optimal parameters generated for N qubits """ opt_params = np.zeros(ansatz.num_parameters) for i in range(ansatz.num_parameters//2): if i in source_list: opt_params[i] = np.pi return opt_params def test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend): """Tests the shallow VQC on a QPU Parameters: num_qubits (int): Number of qubits for the ansatz list_labels (list): List of labels obs: (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Options for Estimator primitive backend (Backend): Real backend from IBM Quantum to run the job Returns: job_id (str): Job ID for Quantum job """ ### Write your code below here ### results_test = [] estimator = Estimator(backend=backend, options=options) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) pubs = [] for bird, label in enumerate(list_labels): new_mapping_qc = new_amplitude_embedding(num_qubits, bird) #ansatz = generate_old_ansatz(num_qubits) ansatz = generate_ansatz(num_qubits) classifier = new_mapping_qc.compose(ansatz) transpiled_classifier = pm.run(classifier) transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) pub = (transpiled_classifier, transpiled_obs, opt_params) pubs.append(pub) job = estimator.run(pubs) job_id = job.job_id() print(f"Job ID: {job_id}") print(f"Status: {job.status()}") ### Don't change any code past this line ### return job_id def retrieve_job(job_id): """Retrieve test results from job id Parameters: job_id (str): Job ID Returns: results_test (list): List of test results errors_test (list): List of test errors """ job = service.job(job_id) results_test = [] errors_test = [] for result in job.result(): results_test.append(abs(abs(result.data.evs)-1)) #COST FUNCTION HAS A -1 NOW!!! errors_test.append(abs(result.data.stds)) return results_test, errors_test def test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, backend): """Tests the shallow VQC on a QPU Parameters: num_qubits (int): Number of qubits for the ansatz list_labels (list): List of labels obs: (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Options for Estimator primitive backend (Backend): AerSimulator backend to run the job Returns: results_test (list): List of test results """ results_test = [] ### Write your code below here ### estimator = Estimator(backend=backend) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) results_test = [] for bird, label in enumerate(list_labels): new_mapping_qc = new_amplitude_embedding(num_qubits, bird) #ansatz = generate_old_ansatz(num_qubits) ansatz = generate_ansatz(num_qubits) classifier = new_mapping_qc.compose(ansatz) transpiled_classifier = pm.run(classifier) transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) pub = (transpiled_classifier, transpiled_obs, opt_params) job = estimator.run([pub]) ### Don't change any code past this line ### result = job.result()[0].data.evs results_test.append(abs(abs(result)-1)) # COST FUNCTION NOW HAS A -1!!! return results_test def compute_performance(result_list, list_labels): """Return the performance of the classifier Parameters: result_list (list): List of results list_labels (list): List of labels Returns: performance (float): Performance of the classifier """ ### Write your code below here ### performance = 100 for result, label in zip(result_list, list_labels): performance -= np.abs(abs(result) - label)/len(list_labels)*100 ### Don't change any code past this line ### return performance num_qubits = 50 aer_sim = AerSimulator(method='matrix_product_state') pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(new_mapping_qc) list_labels = np.append(np.ones(5), np.zeros(5)) obs = SparsePauliOp("Z"*num_qubits) opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list) options = EstimatorOptions() results_test_aer_sim = test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, aer_sim) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data MPS') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for resilience 0: {compute_performance(results_test_aer_sim, list_labels)}") ax.plot(results_test_aer_sim, 'o-', color='tab:red', label='MPS Num qubits = ' + str(num_qubits)) ax.plot(list_labels, 'k-', label='Labels') ax.legend() # Submit your answer using following code grade_lab_bonus_ex3(results_test_aer_sim) # Expected variable types: List service = QiskitRuntimeService() backend = service.backend("select_your_device") # RUN JOBS num_qubits = 50 obs = SparsePauliOp("Z"*num_qubits) opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list) for resilience in [0,1]: DD = True options = EstimatorOptions(default_shots = 5_000, optimization_level=0, resilience_level=resilience) options.dynamical_decoupling.enable = DD options.dynamical_decoupling.sequence_type = 'XpXm' # OPTIONAL # options.resilience.zne_mitigation = True # options.resilience.zne.noise_factors = (1, 1.2, 1.5) # options.resilience.zne.extrapolator = ('exponential', 'linear', 'polynomial_degree_2') #order matters job_id = test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend) results_test_0_DD, errors_test_0_DD = retrieve_job('Enter your JobID for resilience level 0') results_test_1_DD, errors_test_1_DD = retrieve_job('Enter your JobID for resilience level 1') fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title(f'Test of a {num_qubits} qubit VQC on {backend.name}') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for no DD + no TREX: {compute_performance(results_test_0_DD, list_labels):.3f}") print(f"Performance for DD + TREX: {compute_performance(results_test_1_DD, list_labels):.3f}") ax.errorbar(range(10), results_test_0_DD, fmt='--o', yerr=errors_test_0_DD, color='tab:orange', label=f'{backend.name} RL=0 shots={options.default_shots} DD={options.dynamical_decoupling.enable}') ax.errorbar(range(10), results_test_1_DD, fmt='--o', yerr=errors_test_1_DD, color='tab:blue', label=f'{backend.name} RL=1 shots={options.default_shots} DD={options.dynamical_decoupling.enable}') ax.plot(list_labels, 'k-', label='Labels') ax.legend()
https://github.com/mareksubocz/QRBM-qiskit
mareksubocz
from qiskit import IBMQ # IBMQ.save_account(MY_API_TOKEN) import qiskit qiskit.__version__ import scipy import numpy as np import random from sklearn import preprocessing from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.quantum_info.operators import Operator from qiskit import(QuantumCircuit, execute, Aer) from qiskit.visualization import plot_histogram from qiskit.extensions import Initialize # Import the Inititialize function from qiskit.aqua.circuits.gates import multi_control_toffoli_gate from qiskit.aqua.circuits.gates import multi_control_multi_target_gate import torch from torch.autograd import Function import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, transforms import timeit import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['image.cmap'] = 'gray' import pandas as pd from skimage import data, color from skimage.transform import rescale, resize, downscale_local_mean from skimage import img_as_bool import cv2 as cv def exctract_single_qubit_measurment(dict_of_counts, qubit_range): # print(dict_of_counts) # print(len(list(dict_of_counts.keys())[0])) num_qubits = len(list(dict_of_counts.keys())[0]) # result = np.zeros(len(qubit_range)) result = np.zeros(num_qubits) # print(result) for el in dict_of_counts: for i in range(num_qubits): # print("i", i) # print("el[i]", el[i]) if i in qubit_range and el[i] == '1': result[i] += dict_of_counts[el] # print(result) # print(result[qubit_range]) return result[qubit_range] # Wczytywanie danych inną metodą # Concentrating on the first 100 samples n_samples = 100 X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) # Leaving only labels 0 and 1 idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True) n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 n_samples = 50 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True) class QMLCircuit(): def __init__(self, visible, hidden, num_shots=1000): self.visible = visible self.hidden = hidden self.ancilla = visible-1 self.qr = QuantumRegister((self.visible + self.hidden + self.ancilla), 'q') self.cr = ClassicalRegister(self.hidden, 'c') self.qc = QuantumCircuit(self.qr, self.cr) self.num_shots = num_shots # def run(self, thetas): def circuit_function(self, x, weight_matrix): self.qc.data = [] # print("x: ",x) # print("x[0]: ", x[0]) # inicjalizacja wartości qubitów wejściowych (x) initial_state = [[np.sqrt(1-x[i]*x[i]), x[i]] for i in range(len(x))] # inicjalizacja wartości qubitów wejściowych i bramka Hadamarda for i in range(visible): initialize_qubit = Initialize(initial_state[i]) self.qc.append(initialize_qubit, [i]) self.qc.h(i) # ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów) for i in range(self.hidden): for j in range(self.visible): self.qc.ry(weight_matrix[j][i], j) # print([self.qr[k] for k in range(self.visible)]) # print(self.qr[self.visible + i]) # print([self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)]) multi_control_toffoli_gate.mct(self.qc, [self.qr[k] for k in range(self.visible)], self.qr[self.visible + i], [self.qr[i] for i in range(self.visible + self.hidden, self.visible + self.hidden + self.ancilla)], mode='basic') # pomiar linii visible self.qc.measure(list(range(self.visible, self.visible+self.hidden)), list(range(self.hidden))) #eksperyment: simulator = Aer.get_backend('qasm_simulator') job = execute(self.qc, simulator, shots=self.num_shots) result = job.result() counts = result.get_counts(self.qc) ph = exctract_single_qubit_measurment(counts, list(range(self.hidden))) / self.num_shots # print("\nProbabilities are:",ph) return ph visible = 2 hidden = 2 QMLC = QMLCircuit(visible, hidden, 1000) #definicja wejścia (x)oraz inicjalizacja macierzy wag x = np.array([random.uniform(0, 1) for n in range(visible)]) weight_matrix = np.random.rand(visible, hidden) * np.pi ph = QMLC.circuit_function(x, weight_matrix) print("ph: ", ph) QMLC.qc.draw() # global weight_matrix # weight_matrix = nn.Parameter(torch.tensor(np.random.rand(visible, hidden) * np.pi)) # print("self.weight_matrix: ", weight_matrix) class QFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, input, weight_matrix, QMLC, epsilon): """ Forward pass computation """ print("FORWARD BEGIN") ctx.epsilon = epsilon ctx.QMLC = QMLC ctx.weight_matrix = weight_matrix print("input from forward: ", input) print("weight_matrix: ", ctx.weight_matrix) wm = ctx.weight_matrix.tolist() print("wm: ", wm) ph = ctx.QMLC.circuit_function(input.tolist()[0], wm) result = torch.tensor([ph]) print("result: ", result) ctx.save_for_backward(input, result) print("FORWARD END") return result @staticmethod def backward(ctx, grad_output): print("BACKWARD BEGIN") print("grad_output: ", grad_output) input, ph = ctx.saved_tensors input_list = np.array(input.tolist()) wm = ctx.weight_matrix.tolist() # print("wm: ", wm) # print(len(wm)) # print(len(wm[0])) gradient = [] # wyliczam część gradientu dy/dw for i in range(len(wm)): gradient_row = [] for j in range(len(wm[0])): wm[i][j] += ctx.epsilon result_plus = ctx.QMLC.circuit_function(input_list.tolist()[0], wm) print(wm) wm[i][j] -= 2*ctx.epsilon result_minus = ctx.QMLC.circuit_function(input_list.tolist()[0], wm) print(wm) wm[i][j] += ctx.epsilon result_0 = ctx.QMLC.circuit_function(input_list.tolist()[0], wm) print(wm) # print("exp_ph", expected_ph) # print(result_plus - result_minus) dydw = (result_plus - result_minus)/(2*ctx.epsilon) djdy = (result_0 - grad_output.tolist()) lr = 0.05 print("dydw: ", dydw) print("djdy: ", djdy) result = djdy * dydw * lr # print("result: ", result) gradient_row.append(np.sum(result)) gradient.append(gradient_row) # print("gradient: ", gradient) gradient = np.array(gradient) # print("gradient size: ", gradient) # print("wm size: ", wm) wm -= gradient # print("self.weight_matrix: ", wm) # print(torch.tensor(gradient).float() * grad_output.float(), None, None) # print("BACKWARD END") ret = np.zeros((len(wm), 1)).T # print(ret) return torch.tensor(ret).float(), None, None, None class QuantumLayer(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, visible, hidden, backend, shots, epsilon): super(QuantumLayer, self).__init__() self.visible = visible self.hidden = hidden self.QMLC = QMLCircuit(self.visible, self.hidden, 1000) self.epsilon = epsilon # self.weight_matrix = nn.Parameter(torch.randn(visible, hidden)) # self.weight_matrix = np.random.rand(visible, hidden) * np.pi self.weight_matrix = nn.Parameter(torch.tensor(np.random.rand(visible, hidden) * np.pi)) print("self.weight_matrix: ", self.weight_matrix) def forward(self, input): return QFunction.apply(input, self.weight_matrix, self.QMLC, self.epsilon) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, kernel_size=5) self.conv2 = nn.Conv2d(32, 64, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(6400, 64) self.fc2 = nn.Linear(64, 2) self.quantum = QuantumLayer(2, 2, qiskit.Aer.get_backend('qasm_simulator'), 1000, 0.01) self.fc3 = nn.Linear(2, 2) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(-1, 6400) x = F.relu(self.fc1(x)) x = self.fc2(x) x = F.softmax(x) # print("softmax x: ", x) x = self.quantum(x) # print("x after quantum: ", x) # print("x after quantum: ", x.size()) x = self.fc3(x.float()) # print("x after fc3: ", x.size()) # print("x after fc3: ", x) return F.log_softmax(x) # return x # trenowanie modelu model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 20 loss_list = [] model.train() for epoch in range(epochs): print("epoch: ", epoch) print("weight_matrix: ", weight_matrix) # print("wm: ", weight_matrix) total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): # target = target.float() # for MSELoss() function optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model.eval() with torch.no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model(data) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('Predicted {}'.format(pred.item())) count += 1 # nie trzeba odpalać STARE FUNKCJE epsilon = 0.01 def update(ph, expected_ph, weight_matrix, lr): gradient = [] for i, row in enumerate(weight_matrix): gradient_row = [] for j, el in enumerate(row): weight_matrix[i][j] += epsilon result_plus = circuit_function(qc, weight_matrix) weight_matrix[i][j] -= 2*epsilon result_minus = circuit_function(qc, weight_matrix) weight_matrix[i][j] += epsilon # result_zero = circuit_function(qc, weight_matrix) # print("ph", result_zero) # print("exp_ph", expected_ph) # print("el final:", el) # print(result_plus - result_minus) result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph) gradient_row.append(result) gradient.append(gradient_row) # print("gradient", gradient) weight_matrix = weight_matrix - gradient return weight_matrix def create_dataset(dataset_size): dataset = [] for i in range(dataset_size): x = np.array([random.choice([0,1]), random.choice([0,1])]) y = 1 if np.array_equal(x, np.array([0,0])) or np.array_equal(x, np.array([1,1])): y = 0 dataset.append({"x": x, "y": y}) return dataset dataset = create_dataset(4) print(dataset) # template do uczenia import matplotlib.pyplot as plt %matplotlib inline #definicja rozmiaru sieci visible = 2 hidden = 1 ancilla = visible-1 #definicja wejścia (x)oraz inicjalizacja macierzy wag # x = np.array([random.uniform(0, 1) for n in range(visible)]) dataset = create_dataset(10) print(dataset[0]["x"][0]) print(dataset[0]["x"][1]) print([n for n in range(visible)]) weight_matrix = np.random.rand(visible, hidden) * np.pi #definicja parametrów uczenia num_shots = 1000 num_epochs = 100 qr = QuantumRegister(visible + hidden + ancilla, 'q') cr = ClassicalRegister(hidden, 'c') qc = QuantumCircuit(qr, cr) cost_function_data = [] lr = 0.05 for epoch in range(num_epochs): print("epoch: ", epoch) for i, element in enumerate(dataset): # print(element) x = np.array([dataset[i]["x"][n] for n in range(visible)]) exp_ph = dataset[i]["y"] ph = circuit_function(qc, weight_matrix) weight_matrix = update(ph, exp_ph, weight_matrix, lr) # print("exp_ph", exp_ph, "ph", ph, "weight_matrix", weight_matrix, "cost_function", 0.5 * (ph - exp_ph)**2) cost_function_data.append(0.5 * (ph - exp_ph)**2) qc.draw() plt.xlabel('number of epochs') plt.ylabel('cost') plt.plot(cost_function_data) for i in range(len(dataset)): x = np.array([dataset[i]["x"][n] for n in range(visible)]) exp_ph = dataset[i]["y"] ph = circuit_function(qc, weight_matrix) print(ph) print(exp_ph, "\n") qc.draw() ph = circuit_function(qc, weight_matrix) print(ph)
https://github.com/sathayen/qiskit-docker
sathayen
# Creating quantum circuits from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import execute, Aer from qiskit.tools.visualization import circuit_drawer, plot_histogram qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) # Apply a single H gate qc.h(qr) qc.measure(qr, cr) circuit_drawer(qc) # Create a backend object local_simulator = Aer.get_backend('qasm_simulator') # Run the circuit job = execute(qc, backend=local_simulator, shots=100) result = job.result() counts = result.get_counts() plot_histogram(counts) print(counts) qc2 = QuantumCircuit(qr, cr) qc2.h(qr) qc2.h(qr) qc2.measure(qr, cr) circuit_drawer(qc2) # Run the circuit with 2 H gates applied in succession job = execute(qc2, backend=local_simulator, shots=100) result = job.result() counts = result.get_counts() plot_histogram(counts) print(counts)
https://github.com/chaitanya-bhargava/QiskitSolutions
chaitanya-bhargava
## Enter Team ID import os os.environ["TEAMID"] = "Excalibur" def get_min_swaps_line(N, controls, targets, connectivity_map): min_swaps = [] ### You code goes here length=len(controls) for i in range(length): if(targets[i] in connectivity_map[controls[i]]): min_swaps.append(0) else: min_swaps.append(abs(targets[i]-controls[i])-1) ### your code goes here return min_swaps def test_function_1(): controls = [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5] targets = [2,3,4,5,1,3,4,5,1,2,4,5,1,2,3,5,1,2,3,4] connectivity_map = { 1 : [2], 2 : [1,3], 3 : [2,4], 4 : [3,5], 5 : [4] } N = 5 min_swaps = get_min_swaps_line(N, controls, targets, connectivity_map) return min_swaps test_function_1() from grader.graders.problem_2.grader import grader1 grader1.evaluate(get_min_swaps_line) import sys def get_min_swaps_graph(N, M, controls, targets, connectivity_map): min_swaps = [] ### You code goes here length=len(controls) for i in range(length): if(targets[i] in connectivity_map[controls[i]]): min_swaps.append(0) else: u=controls[i] v=targets[i] visited=[] distance=[] q=[] for i in range(N): visited.append(0) distance.append(sys.maxsize) for k in connectivity_map[u]: distance[k-1]=1 distance[u-1]=0 q.append(u) visited[u-1]=1 while(q): x=q.pop(0) templist=connectivity_map[x] length2=len(templist) for j in range(length2): if(visited[templist[j]-1]==1): continue if((distance[x-1]+1)<distance[templist[j]-1]): distance[templist[j]-1]=distance[x-1]+1 q.append(templist[j]) visited[templist[j]-1]=1 if(distance[v-1]==sys.maxsize): min_swaps.append(-1) continue min_swaps.append(distance[v-1]-1) ### your code goes here return min_swaps def test_function_2(): controls = [1, 2] targets = [2, 5] connectivity_map = { 1 : [2], 2 : [1,3], 3 : [2,4,5], 4 : [3], 5 : [3] } N = 5 M = 4 min_swaps = get_min_swaps_graph(N, M, controls, targets, connectivity_map) return min_swaps test_function_2() from grader.graders.problem_2.grader import grader2 grader2.evaluate(get_min_swaps_graph)
https://github.com/fedimser/quantum_decomp
fedimser
import quantum_decomp as qd from scipy.stats import unitary_group from collections import Counter import time for qubits_count in range(1,10): time_start = time.time() gates = qd.matrix_to_gates(unitary_group.rvs(2 ** qubits_count)) duration = time.time() - time_start total = len(gates) print("%d qubits" % qubits_count) ctr = Counter([gate.type() for gate in gates]) for t, count in ctr.most_common(10): print("%s: %d" % (t, count)) print("%d total, %.02f gates per matrix element." % (total, total/(4**qubits_count))) print("Time: %.03fs" % duration) print("\n")
https://github.com/CQCL/pytket-qiskit
CQCL
import qiskit from qiskit.dagcircuit import DAGCircuit from qiskit.providers import BaseBackend from qiskit.transpiler.basepasses import TransformationPass, BasePass from qiskit.converters import circuit_to_dag, dag_to_circuit from pytket._transform import Transform from pytket._routing import route, Architecture from pytket.qiskit import qiskit_to_tk, tk_to_qiskit class TketPass(TransformationPass): """The :math:`\\mathrm{t|ket}\\rangle` compiler to be plugged in to the Qiskit compilation sequence""" filecount = 0 def __init__(self,backend:BaseBackend, DROP_CONDS:bool=False,BOX_UNKNOWN:bool=True,name:str="T|KET>") : BasePass.__init__(self) self.DROP_CONDS=DROP_CONDS self.BOX_UNKNOWN=BOX_UNKNOWN self.name = name my_backend = None if isinstance(backend, BaseBackend): my_backend = backend else: raise RuntimeError("Requires BaseBackend instance") self.coupling_map = my_backend.configuration().to_dict().get('coupling_map', None) def process_circ(self, circ): num_qubits = circ.n_qubits if num_qubits == 1 or self.coupling_map == "all-to-all": coupling_map = None else: coupling_map = self.coupling_map # pre-routing optimise Transform.OptimisePhaseGadgets().apply(circ) circlay = list(range(num_qubits)) if coupling_map: directed_arc = Architecture(coupling_map) # route_ibm fnction that takes directed Arc, returns dag with cnots etc. circ, circlay = route(circ,directed_arc) circ.apply_boundary_map(circlay[0]) # post route optimise Transform.OptimisePostRouting().apply(circ) circ.remove_blank_wires() return circ, circlay 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
https://github.com/COFAlumni-USB/qiskit-fall-2022
COFAlumni-USB
import qiskit as qiskit import numpy as np import math from numpy import sqrt from random import randint from qiskit import * from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_histogram from qiskit.tools import job_monitor provider = IBMQ.load_account() belem = provider.get_backend('ibmq_belem') print('se ha ejecutado correctamente') def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc print('se ha ejecutado correctamente') x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.h(range(x_register+y_register)) circ.draw('mpl') #se añade una barra para separar la x-gate de la h-gate (compuerta de Hadamard) x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.draw('mpl') #es una evolución de la anterior, y podemos ver que entre la dos barras se añade el random_oracle # con sus valores respectivos. x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() circ.draw('mpl') circ.count_ops() circ.depth() def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit): qc.ccx(x_qubit_0,x_qubit_1,y_qubit) return qc def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) return qc def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_1) return qc def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit): qc.x(x_qubit_0) qc.x(x_qubit_1) qc.ccx(x_qubit_0,x_qubit_1,y_qubit) qc.x(x_qubit_0) qc.x(x_qubit_1) return qc def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit): rand=randint(0,3) if rand==3: SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==2: SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit) elif rand==1: SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit) else: SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit) return qc #nota: podemos ver la definición y su respectivo comportamiento def Grover_Iteration(qc, x_qubit_0,x_qubit_1): qc.h(range(2)) qc.x(range(2)) qc.h(x_qubit_1) qc.cx(x_qubit_0,x_qubit_1) qc.h(x_qubit_1) qc.x(range(2)) qc.h(range(2)) return qc print('se ha ejecutado correctamente') #Como podemos ver se ha añadido la def Grover_Iteration x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.draw('mpl') #Se añade el circ_measure, con rangos de registro x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) circ.draw('mpl') circ.count_ops() circ.depth() transpile_circuit = qiskit.transpile(circ,basis_gates =['u1', 'u2', 'u3', 'cx'],optimization_level=3) transpile_circuit.draw('mpl') transpile_circuit.depth() Ahora con la última definición con la cual hemos estructurado el circuito, vamos a probarla y lo que vamos a hacer es inducirle las instrucciones al qiskit.circuit y los vamos a llevar a la simulación con el Aer_Simulator el cual nos dará el estado que debe dar el algoritmo de Grover. x_register=2 y_register=1 measure_register=2 y_position=x_register+y_register-1 circ = QuantumCircuit(x_register+y_register,measure_register) circ.x(y_position) circ.barrier() circ.h(range(x_register+y_register)) circ.barrier() random_oracle(circ, 0,1,2) circ.barrier() Grover_Iteration(circ, 0,1) circ.measure(range(x_register),range(measure_register)) #nota: son las mismas instruccions expresadas a la hora de dar el resultado gráfico arriba, el circuito #completamente estructurado. #circ.draw('mpl') EN ESTE CASO NO LO UTILIZAREMOS solo daremos instrucciones al circuito #simulación backend = Aer.get_backend('aer_simulator') #simulador a usar job = execute(circ, backend, shots=1024) #descripción del trabajo result = job.result() counts = result.get_counts(circ) plot_histogram(counts) #expresa los datos en un histograma #Se establecen las instrucciones para ejecutarlo en el procesador. job_q = execute(circ,belem,shots=1024) job_monitor(job_q) result = job.result() counts = result.get_counts(circ) plot_histogram(counts)
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with 2 qubits # The default initial state of qubits will be |0> or [1,0] B1 = QuantumCircuit(2) # Apply h gate to the control qubit B1.h(0) #Applying the CNOT gate B1.cx(0,1) #Draw the circuit # qc.draw() B1.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(B1,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(B1,backend).result().get_statevector() #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{Statevector} = ") #plot the result as a bloch sphere visualization plot_bloch_multivector(out) #execute the circuit and get the plain result out = execute(B1,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts)
https://github.com/quantum-kittens/quantum-computing-basics
quantum-kittens
# run this cell if you're executing this notebook in your browser !pip install qiskit from IPython.display import clear_output clear_output() from qiskit import * from qiskit import IBMQ # IBMQ.save_account('APITOKEN', overwrite=True) ## Uncomment and replace APITOKEN with your API token to save new credentials IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider('ibm-q') for backend in provider.backends(): print(backend) import qiskit.tools.jupyter backend = provider.get_backend('ibmq_manila') # replace ibmq_manila with whatever backend you want information on backend eligible_devices = provider.backends(filters=lambda x:x.configuration().n_qubits>3 and not x.configuration().simulator) for backend in eligible_devices: print(backend) from qiskit.providers.ibmq import least_busy chosen_backend = least_busy(eligible_devices) print(chosen_backend.name()) chosen_backend from qiskit.visualization import plot_gate_map plot_gate_map(chosen_backend, plot_directed = False) # toggle plot_directed and see what happens from qiskit.visualization import plot_error_map plot_error_map(chosen_backend) qc_bell = QuantumCircuit(2) qc_bell.h(0) qc_bell.cx(0,1) qc_bell.x(1) qc_bell.z(1) qc_bell.measure_all() display(qc_bell.draw('mpl')) from qiskit.tools import job_monitor job = execute(qc_bell, chosen_backend) job_monitor(job) job_id = job.job_id() retrieved_job = chosen_backend.retrieve_job(job_id) result = retrieved_job.result() counts_real = result.get_counts() print(counts_real) from qiskit.visualization import plot_histogram sim_backend = Aer.get_backend('qasm_simulator') job_sim = execute(qc_bell, sim_backend) counts_sim = job_sim.result().get_counts() title = 'Real vs. Simulated' legend = ['Real Counts', 'Sim Counts'] plot_histogram([counts_real, counts_sim], legend = legend, title = title, color = ['teal', 'black'], bar_labels = False)
https://github.com/Qubico-Hack/tutorials
Qubico-Hack
import matplotlib.pyplot as plt import numpy as np !pip install qiskit from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler !pip install qiskit_algorithms from qiskit_algorithms.optimizers import COBYLA from qiskit_algorithms.utils import algorithm_globals from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder, MinMaxScaler !pip install qiskit_machine_learning from qiskit_machine_learning.algorithms.classifiers import VQC from IPython.display import clear_output algorithm_globals.random_seed = 42 sampler1 = Sampler() sampler2 = Sampler() num_samples = 40 num_features = 2 features = 2 * algorithm_globals.random.random([num_samples, num_features]) - 1 labels = 1 * (np.sum(features, axis=1) >= 0) # in { 0, 1} features = MinMaxScaler().fit_transform(features) features.shape features[0:5, :] labels = OneHotEncoder(sparse_output=False).fit_transform(labels.reshape(-1, 1)) labels.shape labels[0:5, :] train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=30, random_state=algorithm_globals.random_seed ) train_features.shape def plot_dataset(): plt.scatter( train_features[np.where(train_labels[:, 0] == 0), 0], train_features[np.where(train_labels[:, 0] == 0), 1], marker="o", color="b", label="Label 0 train", ) plt.scatter( train_features[np.where(train_labels[:, 0] == 1), 0], train_features[np.where(train_labels[:, 0] == 1), 1], marker="o", color="g", label="Label 1 train", ) plt.scatter( test_features[np.where(test_labels[:, 0] == 0), 0], test_features[np.where(test_labels[:, 0] == 0), 1], marker="o", facecolors="w", edgecolors="b", label="Label 0 test", ) plt.scatter( test_features[np.where(test_labels[:, 0] == 1), 0], test_features[np.where(test_labels[:, 0] == 1), 1], marker="o", facecolors="w", edgecolors="g", label="Label 1 test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.plot([1, 0], [0, 1], "--", color="black") plot_dataset() plt.show() maxiter = 20 objective_values = [] # callback function that draws a live plot when the .fit() method is called def callback_graph(_, objective_value): clear_output(wait=True) objective_values.append(objective_value) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") stage1_len = np.min((len(objective_values), maxiter)) stage1_x = np.linspace(1, stage1_len, stage1_len) stage1_y = objective_values[:stage1_len] stage2_len = np.max((0, len(objective_values) - maxiter)) stage2_x = np.linspace(maxiter, maxiter + stage2_len - 1, stage2_len) stage2_y = objective_values[maxiter : maxiter + stage2_len] plt.plot(stage1_x, stage1_y, color="orange") plt.plot(stage2_x, stage2_y, color="purple") plt.show() plt.rcParams["figure.figsize"] = (12, 6) original_optimizer = COBYLA(maxiter=maxiter) ansatz = RealAmplitudes(num_features) initial_point = np.asarray([0.5] * ansatz.num_parameters) original_classifier = VQC( ansatz=ansatz, optimizer=original_optimizer, callback=callback_graph, sampler=sampler1 ) original_classifier.fit(train_features, train_labels) print("Train score", original_classifier.score(train_features, train_labels)) print("Test score ", original_classifier.score(test_features, test_labels)) original_classifier.save("vqc_classifier.model") loaded_classifier = VQC.load("vqc_classifier.model") loaded_classifier.warm_start = True loaded_classifier.neural_network.sampler = sampler2 loaded_classifier.optimizer = COBYLA(maxiter=80) loaded_classifier.fit(train_features, train_labels) print("Train score", loaded_classifier.score(train_features, train_labels)) print("Test score", loaded_classifier.score(test_features, test_labels)) train_predicts = loaded_classifier.predict(train_features) test_predicts = loaded_classifier.predict(test_features) # return plot to default figsize plt.rcParams["figure.figsize"] = (6, 4) plot_dataset() # plot misclassified data points plt.scatter( train_features[np.all(train_labels != train_predicts, axis=1), 0], train_features[np.all(train_labels != train_predicts, axis=1), 1], s=200, facecolors="none", edgecolors="r", linewidths=2, ) plt.scatter( test_features[np.all(test_labels != test_predicts, axis=1), 0], test_features[np.all(test_labels != test_predicts, axis=1), 1], s=200, facecolors="none", edgecolors="r", linewidths=2, ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test RemoveDiagonalGatesBeforeMeasure pass""" import unittest from copy import deepcopy from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.circuit.library import U1Gate, CU1Gate from qiskit.transpiler import PassManager from qiskit.transpiler.passes import RemoveDiagonalGatesBeforeMeasure, DAGFixedPoint from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TesRemoveDiagonalGatesBeforeMeasure(QiskitTestCase): """Test remove_diagonal_gates_before_measure optimizations.""" def test_optimize_1rz_1measure(self): """Remove a single RZGate qr0:-RZ--m-- qr0:--m- | | qr1:-----|-- ==> qr1:--|- | | cr0:-----.-- cr0:--.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.rz(0.1, qr[0]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1z_1measure(self): """Remove a single ZGate qr0:--Z--m-- qr0:--m- | | qr1:-----|-- ==> qr1:--|- | | cr0:-----.-- cr0:--.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.z(qr[0]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1t_1measure(self): """Remove a single TGate, SGate, TdgGate, SdgGate, U1Gate qr0:--T--m-- qr0:--m- | | qr1:-----|-- ==> qr1:--|- | | cr0:-----.-- cr0:--.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.t(qr[0]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1s_1measure(self): """Remove a single SGate qr0:--S--m-- qr0:--m- | | qr1:-----|-- ==> qr1:--|- | | cr0:-----.-- cr0:--.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.s(qr[0]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1tdg_1measure(self): """Remove a single TdgGate qr0:-Tdg-m-- qr0:--m- | | qr1:-----|-- ==> qr1:--|- | | cr0:-----.-- cr0:--.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.tdg(qr[0]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1sdg_1measure(self): """Remove a single SdgGate qr0:-Sdg--m-- qr0:--m- | | qr1:------|-- ==> qr1:--|- | | cr0:------.-- cr0:--.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.sdg(qr[0]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1u1_1measure(self): """Remove a single U1Gate qr0:--U1-m-- qr0:--m- | | qr1:-----|-- ==> qr1:--|- | | cr0:-----.-- cr0:--.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(U1Gate(0.1), [qr[0]]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1rz_1z_1measure(self): """Remove a single RZ and leave the other Z qr0:-RZ--m-- qr0:----m- | | qr1:--Z--|-- ==> qr1:--Z-|- | | cr0:-----.-- cr0:----.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.rz(0.1, qr[0]) circuit.z(qr[1]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.z(qr[1]) expected.measure(qr[0], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_simple_if_else(self): """Test that the pass recurses into an if-else.""" pass_ = RemoveDiagonalGatesBeforeMeasure() base_test = QuantumCircuit(1, 1) base_test.z(0) base_test.measure(0, 0) base_expected = QuantumCircuit(1, 1) base_expected.measure(0, 0) test = QuantumCircuit(1, 1) test.if_else( (test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits ) expected = QuantumCircuit(1, 1) expected.if_else( (expected.clbits[0], True), base_expected.copy(), base_expected.copy(), expected.qubits, expected.clbits, ) self.assertEqual(pass_(test), expected) def test_nested_control_flow(self): """Test that the pass recurses into nested control flow.""" pass_ = RemoveDiagonalGatesBeforeMeasure() base_test = QuantumCircuit(2, 1) base_test.cz(0, 1) base_test.measure(0, 0) base_expected = QuantumCircuit(2, 1) base_expected.measure(1, 0) body_test = QuantumCircuit(2, 1) body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits) body_expected = QuantumCircuit(2, 1) body_expected.for_loop( (0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits ) test = QuantumCircuit(2, 1) test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits) expected = QuantumCircuit(2, 1) expected.while_loop( (expected.clbits[0], True), body_expected, expected.qubits, expected.clbits ) self.assertEqual(pass_(test), expected) class TesRemoveDiagonalControlGatesBeforeMeasure(QiskitTestCase): """Test remove diagonal control gates before measure.""" def test_optimize_1cz_2measure(self): """Remove a single CZGate qr0:--Z--m--- qr0:--m--- | | | qr1:--.--|-m- ==> qr1:--|-m- | | | | cr0:-----.-.- cr0:--.-.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) expected.measure(qr[1], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1crz_2measure(self): """Remove a single CRZGate qr0:-RZ--m--- qr0:--m--- | | | qr1:--.--|-m- ==> qr1:--|-m- | | | | cr0:-----.-.- cr0:--.-.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.crz(0.1, qr[0], qr[1]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) expected.measure(qr[1], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1cu1_2measure(self): """Remove a single CU1Gate qr0:-CU1-m--- qr0:--m--- | | | qr1:--.--|-m- ==> qr1:--|-m- | | | | cr0:-----.-.- cr0:--.-.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(CU1Gate(0.1), [qr[0], qr[1]]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) expected.measure(qr[1], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1rzz_2measure(self): """Remove a single RZZGate qr0:--.----m--- qr0:--m--- |zz | | qr1:--.----|-m- ==> qr1:--|-m- | | | | cr0:-------.-.- cr0:--.-.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.rzz(0.1, qr[0], qr[1]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) expected.measure(qr[1], cr[0]) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) class TestRemoveDiagonalGatesBeforeMeasureOveroptimizations(QiskitTestCase): """Test situations where remove_diagonal_gates_before_measure should not optimize""" def test_optimize_1cz_1measure(self): """Do not remove a CZGate because measure happens on only one of the wires Compare with test_optimize_1cz_2measure. qr0:--Z--m--- | | qr1:--.--|--- | cr0:-----.--- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = deepcopy(dag) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(expected, after) def test_do_not_optimize_with_conditional(self): """Diagonal gates with conditionals on a measurement target. See https://github.com/Qiskit/qiskit-terra/pull/2208#issuecomment-487238819 ░ ┌───┐┌─┐ qr_0: |0>────────────░─┤ H ├┤M├ ┌─────────┐ ░ └───┘└╥┘ qr_1: |0>┤ Rz(0.1) ├─░───────╫─ └─┬──┴──┬─┘ ░ ║ cr_0: 0 ══╡ = 1 ╞═══════════╩═ └─────┘ """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.rz(0.1, qr[1]).c_if(cr, 1) circuit.barrier() circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = deepcopy(dag) pass_ = RemoveDiagonalGatesBeforeMeasure() after = pass_.run(dag) self.assertEqual(expected, after) class TestRemoveDiagonalGatesBeforeMeasureFixedPoint(QiskitTestCase): """Test remove_diagonal_gates_before_measure optimizations in a transpiler, using fixed point.""" def test_optimize_rz_z(self): """Remove two swaps that overlap qr0:--RZ-Z--m-- qr0:--m-- | | cr0:--------.-- cr0:--.-- """ qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.rz(0.1, qr[0]) circuit.z(qr[0]) circuit.measure(qr[0], cr[0]) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_manager = PassManager() pass_manager.append( [RemoveDiagonalGatesBeforeMeasure(), DAGFixedPoint()], do_while=lambda property_set: not property_set["dag_fixed_point"], ) after = pass_manager.run(circuit) self.assertEqual(expected, after) if __name__ == "__main__": unittest.main()