repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
!pip install qutip -q !pip install qiskit -q !pip install qiskit[visualization] -q !pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src -q import numpy as np np.set_printoptions(precision=3, suppress=True) import qutip as qt from matplotlib import pyplot as plt %matplotlib inline import pandas as pd import sklearn as sk import qiskit as qk # Remember that qiskit has to be already installed in the Python environment. # Otherwise the import command will fail import qiskit as qk # A circuit composed of just one qubit qc = qk.QuantumCircuit(1) qc.draw('mpl') import qiskit as qiskit # A qubit initialized in the state |0> qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.draw('mpl') import qiskit as qk # A qubit initialized in |0> and a measurement qc = qk.QuantumCircuit(1) qc.initialize([1,0]) qc.measure_all() qc.draw('mpl') import qiskit as qk # A list of possible measurements. The results of measurements are obtained # by executing an object called backend a = [print(i) for i in qk.Aer.backends()] import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() # Let's choose the statevector simulator from the Aer backend backend = qk.Aer.get_backend('statevector_simulator') # And execute the circuit qc in the simulator backend # getting as final result the counts from 1.000 measures # of the qubit state result = qk.execute(qc, backend, shots=1000).result().get_counts() result import qiskit as qk qc = qk.QuantumCircuit(1) qc.initialize([1,0],0) qc.measure_all() backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_histogram(result) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.measure(0,0) qc.draw('mpl') backend = qk.Aer.get_backend('statevector_simulator') result = qk.execute(qc, backend, shots=1000).result().get_counts() qk.visualization.plot_histogram(result) import numpy as np v0 = np.array([[1],[0]]);v0 v1 = np.array([[0],[1]]); v1 X = np.array([[0,1],[1,0]]); X X.dot(v0) X.dot(v1) import qiskit as qk qr = qk.QuantumRegister(1,"q0") cr = qk.ClassicalRegister(1,"c0") qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.measure(qr[0], cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=1000).result().get_counts() results qk.visualization.plot_histogram(results) import numpy as np # Notice that we are creating the v0 matrix using the transpose operation v0 = np.array([[1,0]]).T; v0 # Here it is created again de X matrix X = np.array([[0,1],[1,0]]); X # Multiplying v0 by the X matrix twice you get again v0 X.dot(X).dot(v0) # Multiplying the X matrix by itself you get the Identity matrix X.dot(X) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.x(0) qc.x(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') # The result of 1000 measures of the qubit above gives the |0> state as result # in all measures simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() results qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,2**-0.5],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np v0 = np.array([[1,0]]).T; v0 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H.dot(v0) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.h(qr[0]) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([2**-0.5,-(2**-0.5)],0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(1,'q0') cr = qk.ClassicalRegister(1,'c0') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.h(0) qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np # First let's start with the qubit in the state |psi> = (|0> - |1>)/sqrt(2) psi = np.array([[1,-1]]).T/(2**0.5); psi H = np.array([[1,1],[1,-1]])/2**0.5; H # Now let's pass the qubit Psi through an Hadamard gate. # The result is a qubit in the state |1> H.dot(psi) # Let's start with a qubit in the state |1>, pass it through a # a hadamard gate twice and check the result v0 = np.array([[0,1]]).T; v0 H.dot(H).dot(v0) # This means that if we multiply the H gate by itself the result # will be an Identity matrix. Let's check it. H.dot(H) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[1,0]]).T; psi1 psi2 = np.array([[1,0]]).T; psi2 # In numpy the tensor product is calculated with the function kron np.kron(psi1,psi2) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[1,0]]).T;psi1 psi2 = np.array([[1,0]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np psi1 = np.array([[0,1]]).T;psi1 psi2 = np.array([[0,1]]).T;psi2 H = np.array([[1,1],[1,-1]])/2**0.5;H # When we want to combine two vector states or gate matrices we tensor product them. psi3 = np.kron(psi1,psi2);psi3 H2 = np.kron(H,H);H2 # When we want to pass a vetor through a gate we calculate the dot product # of the total gate matrix with the total vector. # As we have predicted, the resulting vector state has a=b=c=d=1/2 psi4 = H2.dot(psi3); psi4 import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v00 = np.array([[1,0,0,0]]).T;v00 # C.v00 = v00 C.dot(v00) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') # Please notice that Qiskit's qubits presentation order is reversed. # Therefore 10 in the histogram's x axis should be read as 01 (from # inside out or right to left). simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v01 = np.array([[0,1,0,0]]).T;v01 # C.v01 = v01 C.dot(v01) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([1,0],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v10 = np.array([[0,0,1,0]]).T; v10 # C.v10 = v11 C.dot(v10) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([0,1],0) qc.initialize([0,1],1) qc.cnot(0,1) qc.measure(qr,cr) qc.draw('mpl') # Again remember to read qiskit qubits state presentation order # from right to left. Therefore 01 in the x axis is in fact 10 simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc, simulator, shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C v11 = np.array([[0,0,0,1]]).T; v11 # C.v11 = v10 C.dot(v11) import qiskit as qk qr = qk.QuantumRegister(2, 'q') cr = qk.ClassicalRegister(2, 'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr, cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np va = np.array([[1,0]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout import qiskit as qk qr = qk.QuantumRegister(2, 'q') cr = qk.ClassicalRegister(2, 'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([0,1],0) qc.initialize([1,0],1) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr, cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np va = np.array([[0,1]]).T; va vb = np.array([[1,0]]).T; vb H = np.array([[1,1],[1,-1]])/2**0.5;H vaH = H.dot(va); vaH vaHvb = np.kron(vaH,vb); vaHvb C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C vout = C.dot(vaHvb); vout # Get the IBM API key in: https://quantum-computing.ibm.com # chave = 'My key is already saved in this environment' # qk.IBMQ.save_account(chave) # Load the account in the active session qk.IBMQ.load_account() # The default provider is é hub='ibm-q', group='open, project='main' # The code below is executed as an example provider_1 = qk.IBMQ.get_provider(hub='ibm-q', group='open', project='main') # In the public provider we will use a cloud simulator. backend_1 = provider_1.get_backend('ibmq_qasm_simulator') # The provider listed below has unlimited jobs provider_2 = qk.IBMQ.get_provider(hub='ibm-q-education', group='fgv-1', project='ml-business-app') # For this provider we will use the ibmq_jakarta machine backend_2 = provider_2.get_backend('ibmq_jakarta') # With n Qubits we can generate a random number from 0 to 2^n - 1 n = 3 qr = qk.QuantumRegister(n,'q') cr = qk.ClassicalRegister(n,'c') qc = qk.QuantumCircuit(qr, cr) # Applying a Hadamard to each of the three qubits for i in range(n): qc.h(q[i]) # Measuring the three qubits qc.measure(q,c) # Visualizing the circuit qc.draw('mpl') # qk.execute envia para o backend. Conferindo no iqmq explorer aparece o job new_job = qk.execute(circ, backend_2, shots=1) # this result is stored on the local machine. However, it will only be available # after the job has been executed. It returns a python dictionary. new_job.result().get_counts() int(list(new_job.result().get_counts().keys())[0],2) from qiskit import QuantumCircuit circuit = QuantumCircuit(2, 2) circuit.h(0) circuit.cx(0,1) circuit.measure([0,1], [0,1]) display(circuit.draw('mpl')) from qiskit.providers.aer import AerSimulator print(AerSimulator().run(circuit, shots=1000).result().get_counts()) print(AerSimulator().run(circuit, shots=1000).result().get_counts()) from qiskit import QuantumCircuit circuito = QuantumCircuit(3,3) for i in range(3): circuito.h(i) circuito.measure(i,i) display(circuito.draw('mpl')) from qiskit.providers.aer import AerSimulator AerSimulator().run(circuito, shots = 1000).result().get_counts() from qiskit import QuantumCircuit qc = QuantumCircuit(4,4) qc.x([0,1]) qc.cx([0,1],[2,2]) qc.ccx(0,1,3) qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw(output='mpl')) from qiskit.providers.aer import AerSimulator AerSimulator().run(qc, shots = 10000).result().get_counts() import qiskit as qk qr = qk.QuantumRegister(1,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr, cr) qc.initialize([1,0],0) print("Circuit 1 - Registers Only") display(qc.draw('mpl')) qc.x(qr) print("Circuit 1 - Quantum Register with a Gate X ") display(qc.draw('mpl')) job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('statevector_simulator')) result1 = job.result().get_statevector() print("Quantum Register Vector State") from qiskit.tools.visualization import plot_bloch_multivector display(plot_bloch_multivector(result1)) job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('unitary_simulator')) print("Transformation Matrix (up to this stage)") print(job.result().get_unitary()) qc.measure(qr, cr) print() print("Circuit 1 - Registers, Gate X and Quantum Register Measure") display(qc.draw('mpl')) print("Quantum Register Thousand Measures") job = qk.execute(experiments = qc, backend = qk.Aer.get_backend('statevector_simulator'), shots = 1000) print(job.result().get_counts()) print() print("Result's Histogram") from qiskit.tools.visualization import plot_histogram plot_histogram(data = job.result().get_counts(), figsize=(4,3)) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) display(qc.draw('mpl')) sv = Statevector.from_label('000') state_data = lambda qc,sv: np.round(np.asarray(sv.evolve(qc).data),4) state_bloch = lambda qc,sv: plot_bloch_multivector(sv.evolve(qc).data, reverse_bits=True) print(state_data(qc,sv)) state_bloch(qc,sv) qc.x(0) qc.barrier() display(qc.draw('mpl')) print(state_data(qc,sv)) display(state_bloch(qc,sv)) qc.h(1) display(qc.draw('mpl')) print(state_data(qc,sv)) state_bloch(qc,sv) qc.cnot(1,2) display(qc.draw("mpl")) state_data(qc,sv) state_bloch(qc,sv) qc.cnot(0,1) display(qc.draw('mpl')) state_data(qc,sv) qc.h(0) qc.barrier() display(qc.draw('mpl')) state_data(qc,sv) qc.measure(0,0) qc.measure(1,1) qc.barrier() qc.cnot(1,2) qc.cz(0,2) qc.measure(2,2) display(qc.draw('mpl')) simulador = qk.Aer.get_backend('statevector_simulator') resultado = qk.execute(qc, simulador, shots=10000).result() qk.visualization.plot_histogram(resultado.get_counts()) import numpy as np V = np.array([[3+2j],[4-2j]]) modV = np.real(V.T.conjugate().dot(V)[0,0])**0.5 Vn = V/modV; Vn v0 = np.array([[1,0]]).T v1 = np.array([[0,1]]).T Vn[0,0]*v0 + Vn[1,0]*v1 import qiskit as qk qr = qk.QuantumRegister(1,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([Vn[0,0],Vn[1,0]],0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) Vn[0,0].conjugate()*Vn[0,0] Vn[1,0].conjugate()*Vn[1,0] import numpy as np CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT.dot(CNOT) import numpy as np H = np.array([[1,1],[1,-1]])/2**0.5 H.dot(H) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.cnot(qr[0],qr[1]) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(2,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.cnot(qr[0],qr[1]) qc.cnot(qr[0],qr[1]) qc.h(0) qc.measure(qr,cr) qc.draw('mpl') simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np X = np.array([[0,1], [1,0]]) X X.conj().T.dot(X) Y = np.array([[0,-1j], [1j,0]]) Y Y.conj().T.dot(Y) Z = np.array([[1,0], [0,-1]]) Z Z.conj().T.dot(Z) H = (X+Z)/np.sqrt(2); H H.dot(Z).dot(H) H.dot(X).dot(H) -H.dot(Y).dot(H) import numpy as np S = np.array([[1,0], [0,1j]]) S S.conj().T.dot(S) T = np.array([[1,0], [0,np.exp(1j*np.pi/4)]]) T T.conj().T.dot(T) S = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]); S S.dot(v00) S.dot(v01) S.dot(v10) S.dot(v11) C = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]);C C_ = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]);C_ C.dot(C_).dot(C) v = v0 + v1; v n = np.array([[0,0],[0,1]]); n n.dot(v) n_ = np.array([[1,0],[0,0]]);n_ I2 = np.identity(2); I2 I2 - n n_.dot(v) n.dot(n) n_.dot(n_) n.dot(n_) n_.dot(n) n+n_ n.dot(X) X.dot(n_) import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # ni nj operam em bits distintos. Como cada operador n atua em um vetor de # 2 dimensões, ni nj é um operador de 4 dimensões. Sendo assim, fica implícito # pelos subscritos que ni nj é um produto tensorial. np.kron(n,n) # O mesmo vale para n'i n'j np.kron(n_,n_) # Para ni n'j np.kron(n,n_) # E para n'i nj np.kron(n_,n) # Xi Xj são dois operadores 2x2 de inversão, cada um atuando em um bit # distinto. Sendo assim, fazemos o produto tensorial entre ambos # para obter XiXj np.kron(X,X) # No caso da expressão XiXj(ninj' + ni'nj) temos entre parênteses duas # matrizes 4x4 (ninj'+ni'nj) e fora dos parênteses uma matriz 4x4 (XiXj) # Sendo assim fazemos neste caso o produto matricial normal para # calcular esta expressão. np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # E por último somamos com o resultado inicial de ninj + ni'nj' # Como pode-se ver, esta expressão gera o operador de SWAP np.kron(n,n) + np.kron(n_,n_) + np.kron(X,X).dot(np.kron(n,n_)+np.kron(n_,n)) # É importante observar que ninj forma um operador que projeta um vetor de # 4 dimensões (00, 01, 10, 11) em sua componente 11 np.kron(n,n) # De maneira similar ni'nj' projeta um vetor de 4 dimensões em sua componente 00 np.kron(n_,n_) # ni'nj projeta em 01 np.kron(n_,n) # Assim como ninj' projeta em 10 np.kron(n,n_) # E por último vemos que ni'nj' + ni'nj + ninj' + ninj = I nn = np.kron(n,n) nn_ = np.kron(n,n_) n_n = np.kron(n_,n) n_n_ = np.kron(n_,n_) nn + nn_ + n_n + n_n_ import numpy as np n = np.array([[0,0],[0,1]]); n n_ = np.array([[1,0],[0,0]]);n_ # (n x n).(n_ x n_) np.kron(n,n).dot(np.kron(n_,n_)) # Faz sentido que (ni x nj).(ni_ x nj_) seja o vetor nulo pois: # ni_ x nj_ é um operador que recebe um vetor de 4 dimensões e # produz como resultado apenas sua componente |00>. Por sua # vez ni x nj é um operador que recebe um vetor de 4 dimensões # e produz como resultado apenas sua componente |11>. Esta # componente foi zerada pelo primeiro operador, logo o resultado # será nulo. Isto vai acontecer sempre que a componente não # zerada do primeiro operador for diferente da do segundo em # outras palavras sempre que ij do primeiro for diferente de ij # do segundo. np.kron(n,n).dot(np.kron(n_,n_)) # Outra forma de entender é transformar (n x n).(n_ x n_) em # (n.n_) x (n.n_). Como n é ortogonal a n_, a projeção de n # em n_ dará zero também. np.kron(n.dot(n_),n.dot(n_)) nn.dot(n_n_) # (n_ x n).(n x n_) np.kron(n_,n).dot(np.kron(n,n_)) n_n.dot(nn_) # (n x n_).(n_ x n) np.kron(n, n_).dot(np.kron(n_,n)) nn_.dot(n_n) # (n_ x n_).(n x n) np.kron(n_, n_).dot(np.kron(n, n)) n_n_.dot(nn) NOT = np.array([[0,1],[1,0]]); NOT NOT.dot(D0) NOT.dot(D1) AND = np.array([[1,1,1,0],[0,0,0,1]]); AND AND.dot(np.kron(D0,D0)) AND.dot(np.kron(D0,D1)) AND.dot(np.kron(D1,D0)) AND.dot(np.kron(D1,D1)) OR = np.array([[1,0,0,0],[0,1,1,1]]); OR OR.dot(np.kron(D0,D0)) OR.dot(np.kron(D0,D1)) OR.dot(np.kron(D1,D0)) OR.dot(np.kron(D1,D1)) NAND = np.array([[0,0,0,1],[1,1,1,0]]); NAND NOT.dot(AND) NOR = np.array([[0,1,1,1],[1,0,0,0]]);NOR NOT.dot(OR) np.kron(NOT,AND) OR.dot(np.kron(NOT,AND)) NOT.dot(AND).dot(np.kron(NOT,NOT)) OR NOT.dot(OR).dot(np.kron(NOT,NOT)) AND import numpy as np k = np.kron XOR = np.array([[1,0,0,1], [0,1,1,0]]) AND = np.array(([1,1,1,0], [0,0,0,1])) k(XOR,AND) def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) k(XOR,AND).dot(criaCompat(2,2)) import numpy as np k = np.kron def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) NOT = np.array([[0,1], [1,0]]) AND3 = np.array([[1,1,1,1,1,1,1,0], [0,0,0,0,0,0,0,1]]) OR4 = np.array([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]) I2 = np.array([[1,0], [0,1]]) t1z = k(NOT,k(NOT,I2)) t2z = k(NOT,k(I2,NOT)) t3z = k(I2,k(NOT,NOT)) t4z = k(I2,k(I2,I2)) ORz = k(AND3,k(AND3,k(AND3,AND3))) ORz = OR4.dot(ORz).dot(k(t1z,k(t2z,k(t3z,t4z)))) t1c = k(NOT,k(I2,I2)) t2c = k(I2,k(NOT,I2)) t3c = k(I2,k(I2,NOT)) t4c = k(I2,k(I2,I2)) ORc = k(AND3,k(AND3,k(AND3,AND3))) ORc = OR4.dot(ORc).dot(k(t1c,k(t2c,k(t3c,t4c)))) compat = criaCompat(3,8) k(ORz,ORc).dot(compat) import numpy as np TOFFOLI = np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0]]) TOFFOLI.dot(TOFFOLI) Z1 = np.array([[0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) Z1 Z1I4 = np.array([[0,0,0,0], [1,0,0,0], [0,0,0,0], [0,1,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,0], [0,0,0,1]]) TOFFOLI.dot(ZpY).dot(TOFFOLI).dot(Z1I4) ZpY = np.zeros([8,8]) ZpY[0,0] = 1; ZpY[1,2] = 1; ZpY[2,1] = 1; ZpY[3,3] = 1 ZpY[4,4] = 1; ZpY[5,6] = 1; ZpY[6,5] = 1; ZpY[7,7] = 1 ZpY Zfim = np.array([[1,0,1,0,1,0,1,0], [0,1,0,1,0,1,0,1]]) Zfim.dot(TOFFOLI).dot(ZpY).dot(TOFFOLI).dot(Z1I4) import numpy as np fred = np.identity(8) fred[5,5] = 0; fred[5,6] = 1 fred[6,5] = 1; fred[6,6] = 0 fred fred.dot(fred) import numpy as np Fy0 = np.zeros([8,4]) Fy0[0,0] = 1; Fy0[1,1] = 1; Fy0[4,2] = 1; Fy0[5,3] = 1 Fy0 xYz = np.array([[1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1]]) xYz.dot(fred).dot(Fy0) import numpy as np q0 = np.array([[1,0]]).T; q0 q1 = np.array([[0,1]]).T; q1 q01 = np.kron(q0,q1); q01 H = np.array([[1,1],[1,-1]])/np.sqrt(2); H H2 = np.kron(H,H); H2 H2.dot(q01) I4 = np.eye(4); I4 I4.dot(H2).dot(q01) I2 = np.eye(2); I2 HI2 = np.kron(H,I2); HI2 HI2.dot(I4).dot(H2).dot(q01) X = np.array([[0,1],[1,0]]); X I2 = np.eye(2); I2 I2X = np.kron(I2,X); I2X HI2.dot(I2X).dot(H2).dot(q01) CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT HI2.dot(CNOT).dot(H2).dot(q01) X = np.array([[0,1],[1,0]]); X I2 = np.eye(2); I2 XI2 = np.kron(X,I2); XI2 CNOT = np.array([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) CNOT CNOT.dot(XI2) HI2.dot(CNOT).dot(XI2).dot(H2).dot(q01) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.x(1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.cx(0,1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np qr = qk.QuantumRegister(2,'q') cr = qk.ClassicalRegister(1,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([0,1],1) qc.h(0) qc.h(1) qc.barrier() qc.x(0) qc.cx(0,1) qc.barrier() qc.h(0) qc.measure(qr[0],cr[0]) qc.draw('mpl') simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.barrier() qc.cnot(1,2) qc.barrier() qc.draw('mpl') import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(1,2) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') def histograma(qc): import qiskit as qk from qiskit.visualization import plot_histogram simulador = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulador,shots=10000).result().get_counts() grafico = plot_histogram(results) return(grafico) histograma(qc) import numpy as np x1 = np.array([[1,0]]).T x0 = np.array([[1,0]]).T y = np.array([[0,1]]).T psi0 = np.kron(y,np.kron(x1,x0)); psi0.T import numpy as np H = np.array([[1, 1], [1,-1]])/np.sqrt(2) H3 = np.kron(H,np.kron(H,H)); np.round(H3,3) psi0 = np.array([[0,0,0,0,1,0,0,0]]).T psi1 = H3.dot(psi0); psi1.T CNOTsm = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]) I2 = np.array([[1,0], [0,1]]) CNOTsm_I2 = np.kron(CNOTsm,I2) psi0 = np.array([[0,0,0,0,1,0,0,0]]).T CNOTsm_I2.dot(H3).dot(psi0).T psi = np.array([[1,1,-1,-1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(0,2) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np v0 = np.array([[0,0,0,0,1,0,0,0]]).T; v0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) H3.dot(v0).T CNOTs_I_m = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0]]) v0 = np.array([[0,0,0,0,1,0,0,0]]).T CNOTs_I_m.dot(H3).dot(v0).T psi = np.array([[+1,-1,+1,-1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk qc = qk.QuantumCircuit(3,3) qc.initialize([0,0,0,0,1,0,0,0],[0,1,2]) qc.h([0,1,2]) qc.barrier() qc.cnot(0,1) qc.cnot(1,2) qc.cnot(0,1) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) v0 = np.array([[0,0,0,0,1,0,0,0]]).T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) H3.dot(v0).T CNOT_CNOT = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) v0 = np.array([[0,0,0,0,1,0,0,0]]).T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H); H3 = np.kron(H2,H) CNOT_CNOT.dot(H3).dot(v0).T psi = np.array([[+1,-1,-1,+1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import numpy as np CNOTsm = np.array([[1,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0]]) I = np.array([[1,0], [0,1]]) ISM = np.kron(I,CNOTsm) SMI = np.kron(CNOTsm,I) H = np.array([[1, 1], [1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H2,H) IH2 = np.kron(I,H2) v0 = np.array([[0,0,0,0,1,0,0,0]]).T IH2.dot(ISM).dot(SMI).dot(ISM).dot(H3).dot(v0).round(3) CNOT_CNOT = np.array([[1,0,0,0,0,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1]]) ISM.dot(SMI).dot(ISM) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) psi = np.array([[1,1,1,1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.x(2) qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) psi = np.array([[1,1,1,1]]).T/2 H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H2.dot(psi) import qiskit as qk from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram qr = qk.QuantumRegister(3,'q') cr = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(qr,cr) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([0,1],2) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.h(0) qc.h(1) qc.measure(0,0) qc.measure(1,1) display(qc.draw('mpl')) histograma(qc) import qiskit as qk qrx = qk.QuantumRegister(2,'x') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.draw('mpl') def histograma(qc): simulador = qk.Aer.get_backend('statevector_simulator') resultado = qk.execute(qc,simulador,shots=10000).result() contagens = resultado.get_counts() grafico = qk.visualization.plot_histogram(contagens) return(grafico) def simon(initial_y, initial_x): import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(4,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize(initial_x,qrx) qc.initialize(initial_y,qry) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.measure([0,1,2,3],[0,1,2,3]) display(qc.draw('mpl')) grafico = histograma(qc) return(grafico) simon([1,0,0,0],[1,0,0,0]) simon([1,0,0,0],[0,0,0,1]) simon([1,0,0,0],[0,1,0,0]) simon([1,0,0,0],[0,0,1,0]) import qiskit as qk qrx = qk.QuantumRegister(2,'x') crx = qk.ClassicalRegister(2,'c') qry = qk.QuantumRegister(2,'y') qc = qk.QuantumCircuit(qrx,qry,crx) qc.initialize([1,0,0,0],qrx) qc.initialize([1,0,0,0],qry) qc.h([0,1]) qc.barrier() qc.cx(0,2) qc.cx(0,3) qc.cx(1,2) qc.cx(1,3) qc.barrier() qc.h([0,1]) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) histograma(qc) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x1x0 = np.kron(x1,x0) y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y1y0 = np.kron(y1,y0) psi0 = np.kron(y1y0,x1x0) psi0.T H = np.array([[1,1],[1,-1]],dtype='int') H2 = np.kron(H,H) I2 = np.eye(4) I2H2 = np.kron(I2,H2) psi1 = I2H2.dot(psi0)/(np.sqrt(2)*np.sqrt(2)) I2H2.dot(psi0).T Tf1_2 = np.eye(16) Tf1_2 = Tf1_2[:,[0,5,2,7,4,1,6,3,8,9,10,11,12,13,14,15]] psi2 = Tf1_2.dot(psi1); psi2.T*2 Tf2_3 = np.eye(16) Tf2_3 = Tf2_3[:,[0,1,2,3,4,13,6,15,8,9,10,11,12,5,14,7]] psi3 = Tf2_3.dot(psi2); psi3.T*2 Tf3_4 = np.eye(16) Tf3_4 = Tf3_4[:,[0,1,6,3,4,5,2,7,8,9,10,15,12,13,14,11]] psi4 = Tf3_4.dot(psi3); psi4.T*2 Tf4_5 = np.eye(16) Tf4_5 = Tf4_5[:,[0,1,2,11,4,5,14,7,8,9,10,3,12,13,6,15]] psi5 = Tf4_5.dot(psi4); psi5.T*2 I2 = np.eye(4) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) I2H2 = np.kron(I2,H2) psi6 = I2H2.dot(psi5) print(psi6.T*2) import numpy as np I2 = np.eye(4, dtype='int'); H2 = np.array([[1, 1, 1, 1], [1,-1, 1,-1], [1, 1,-1,-1], [1,-1,-1, 1]])/2; I2H2 = np.kron(I2,H2); print(I2H2*2) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T y0 = np.array([[1,0]]).T y1 = np.array([[1,0]]).T y2 = np.array([[1,0]]).T y2y1y0 = np.kron(y2,np.kron(y1,y0)) y2y1y0.T psi0 = np.kron(y2y1y0,x2x1x0) psi0.T I3 = np.eye(2**3) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) I3H3 = np.kron(I3,H3) psi1 = I3H3.dot(psi0) psi1.T.round(2) n = 2*3 # 2 números de 3 digitos cada Uf = np.eye(2**n) # 2^6 = 64 posições Uf = Uf[:,[ 0, 9,18,27,12, 5,30,23, 8, 1,10,11, 4,13,14,15, 16,17, 2,19,20,21,22, 7, 24,25,26, 3,28,29, 6,31, 32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47, 48,49,50,51,52,53,54,55, 56,57,58,59,60,61,62,63]] psi5 = Uf.dot(psi1) psi5.T.round(2) psi6 = I3H3.dot(psi5) psi6.T np.where(psi6 > 0)[0] [format(i,'#08b')[2:] for i in np.where(psi6 > 0)[0]] import numpy as np CCNOT = np.eye(8) CCNOT = CCNOT[:,[0,1,2,7,4,5,6,3]] CCNOT.dot(CCNOT) import qiskit as qk def qNAND(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(x,y,z,u,c) # Put qubits u and z in state |0> qc.initialize([1,0],z) qc.initialize([1,0],u) qc.initialize(y0,y) qc.initialize(x0,x) # Perform computation qc.barrier() qc.ccx(x,y,z) qc.x(z) # Copy CLASSICALY state of z to u qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc, simulator, shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) print("0 NAND 0 = 1") qNAND([1,0],[1,0]) print("0 NAND 1 = 1") qNAND([1,0],[0,1]) print("1 NAND 0 = 1") qNAND([0,1],[1,0]) print("1 NAND 1 = 0") qNAND([0,1],[0,1]) import qiskit as qk def qOR(y0,x0): x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") z = qk.QuantumRegister(1,"z") u = qk.QuantumRegister(1,"u") c = qk.ClassicalRegister(3,'c') # Initialize qubits qc = qk.QuantumCircuit(x,y,z,u,c) qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],u) # Compute function qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.x(z) qc.cx(z,u) qc.barrier() # Reverse computation qc.x(z) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() # Measure results qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(u,c[2]) display(qc.draw('mpl')) # Simulate circuit simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) qOR([1,0],[1,0]) qOR([1,0],[0,1]) qOR([0,1],[1,0]) qOR([0,1],[0,1]) import qiskit as qk def qNXOR(y0,x0,calc=True,show=False): ################################################## # Create registers # ################################################## # Base registers x = qk.QuantumRegister(1,"x") y = qk.QuantumRegister(1,"y") # Auxiliary register (for x and y) z = qk.QuantumRegister(1,"z") # Auxiliary register (to store x AND y) a1 = qk.QuantumRegister(1,"a1") # Auxiliary register (to store NOT(x) AND NOT(y)) a2 = qk.QuantumRegister(1,"a2") # Auxiliary register (for a1 and a2) b1 = qk.QuantumRegister(1,"b1") # Auxiliary register (to store a1 OR a2) b2 = qk.QuantumRegister(1,"b2") # Classical Registers to store x,y and final measurement c = qk.ClassicalRegister(3,"c") ################################################## # Create Circuit # ################################################## qc = qk.QuantumCircuit(x,y,z,a1,a2,b1,b2,c) ################################################## # Initialize registers # ################################################## qc.initialize(x0,x) qc.initialize(y0,y) qc.initialize([1,0],z) qc.initialize([1,0],a1) qc.initialize([1,0],a2) qc.initialize([1,0],b1) qc.initialize([1,0],b2) ################################################### # Calculate x AND y. Copy result to a1. Reverse z # ################################################### qc.barrier() qc.ccx(x,y,z) qc.cx(z,a1) qc.ccx(x,y,z) qc.barrier() ######################################################### # Calc. NOT(x) AND NOT(y). Copy result to a2. Reverse z # ######################################################### qc.barrier() qc.x(x) qc.x(y) qc.ccx(x,y,z) qc.cx(z,a2) qc.ccx(x,y,z) qc.x(y) qc.x(x) qc.barrier() ################################################# # Calc. a1 OR a2. Copy result to b2. Reverse b1 # ################################################# qc.barrier() qc.x(a1) qc.x(a2) qc.ccx(a1,a2,b1) qc.x(b1) qc.cx(b1,b2) qc.x(b1) qc.ccx(a1,a2,b1) qc.barrier() ################################################# # Measure b2 # ################################################# qc.measure(x,c[0]) qc.measure(y,c[1]) qc.measure(b2,c[2]) ################################################# # Draw circuit # ################################################# if show: display(qc.draw("mpl")) ################################################# # Run circuit. Collect results # ################################################# if calc: simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc,simulator,shots=10000).result().get_counts() grafico = qk.visualization.plot_histogram(results) return(grafico) else: return() qNXOR([1,0],[1,0],False,True) qNXOR([1,0],[1,0]) qNXOR([1,0],[0,1]) qNXOR([0,1],[1,0]) qNXOR([0,1],[0,1]) x0 = np.array([1,1])/np.sqrt(2) y0 = np.array([1,1])/np.sqrt(2) qNXOR(y0,x0) import qiskit as qk from qiskit.quantum_info.operators import Operator qr = qk.QuantumRegister(6,"q") cr = qk.ClassicalRegister(6,"c") qc = qk.QuantumCircuit(qr,cr) for i in range(6): qc.initialize([1,0],i) for i in range(3): qc.h(i) oracle = np.eye(2**6) oracle[:,[ 0, 0]] = oracle[:,[ 0, 0]] oracle[:,[ 1, 9]] = oracle[:,[ 9, 1]] oracle[:,[ 2, 18]] = oracle[:,[ 18, 2]] oracle[:,[ 3, 27]] = oracle[:,[ 27, 3]] oracle[:,[ 4, 12]] = oracle[:,[ 12, 4]] oracle[:,[ 5, 5]] = oracle[:,[ 5, 5]] oracle[:,[ 6, 30]] = oracle[:,[ 30, 6]] oracle[:,[ 7, 23]] = oracle[:,[ 23, 7]] oracle = Operator(oracle) qc.append(oracle,qr) for i in range(3): qc.h(i) qc.barrier() for i in range(3): qc.measure(i,i) display(qc.draw("mpl")) simulator = qk.Aer.get_backend("statevector_simulator") results = qk.execute(qc,simulator,shots=10000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T psi0 = np.kron(x1,x0) H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) psi1 = H2.dot(psi0) psi1.T # Initialize a qubit y in state |1> y = np.array([[0,1]]).T # Pass it through a Hadamard gate and obtain state psi2a H = np.array([[1,1],[1,-1]])/np.sqrt(2) psi2a = H.dot(y) psi2a.T psi2 = np.kron(psi2a,psi1) psi2.T oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle psi3 = oracle.dot(psi2) psi3.T v0 = np.array([[10,20,-30,40,50]]).T mu = np.mean(v0) v0.T, mu D = v0 - mu D.T v1 = 2*np.mean(v0)-v0 v1.T import numpy as np A = np.ones(5**2).reshape(5,5) A = A/5 I = np.eye(5) R = 2*A-I R R.dot(R) n = 4 I = np.eye(n) A = np.ones(n**2).reshape(n,n)/n R = 2*A-I R I2 = np.eye(2) I2R = np.kron(I2,R) I2R psi4 = I2R.dot(psi3) psi4.T import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(3,'q') c = qk.ClassicalRegister(3,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.h(0) qc.h(1) qc.initialize([0,1],2) qc.h(2) qc.barrier() oracle = np.eye(8) oracle[:,[2,6]] = oracle[:,[6,2]] oracle = Operator(oracle) qc.append(oracle,q) # n = 2 (two digits number to look for) A = np.ones(4*4).reshape(4,4)/4 I4 = np.eye(4) R = 2*A - I4 I2 = np.eye(2) boost = np.kron(I2,R) boost = Operator(boost) qc.append(boost,q) qc.barrier() qc.measure(q[:2],c[:2]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np x0 = np.array([[1,0]]).T x1 = np.array([[1,0]]).T x2 = np.array([[1,0]]).T x2x1x0 = np.kron(x2,np.kron(x1,x0)) x2x1x0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) H2 = np.kron(H,H) H3 = np.kron(H,H2) x = H3.dot(x2x1x0) x.T y0 = np.array([[0,1]]).T y0.T H = np.array([[1,1],[1,-1]])/np.sqrt(2) y = H.dot(y0) y.T psi0 = np.kron(y,x) psi0.T oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] psi1 = oracle.dot(psi0) psi1.T # n = 8 A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A-I8 R I2 = np.eye(2) I2R = np.kron(I2,R) psi2 = I2R.dot(psi1) psi2.T 0.625**2 + 0.625**2 psi3 = I2R.dot(oracle).dot(psi2) psi3.T 0.687**2 + 0.687**2 I2R.dot(oracle).dot(psi3).T T = I2R.dot(oracle) psi = psi1 prob = [] for i in range(25): prob.append(psi[5,0]**2 + psi[13,0]**2) psi = T.dot(psi) from matplotlib import pyplot as plt plt.plot(list(range(25)), prob); import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(4,'q') c = qk.ClassicalRegister(4,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.h(0) qc.h(1) qc.h(2) qc.initialize([0,1],3) qc.h(3) qc.barrier() # Create oracle matrix oracle = np.eye(16) oracle[:,[5,13]] = oracle[:,[13,5]] # Create rotation about the mean matrix # n = 3 (three digits number to look for) A = np.ones(8*8).reshape(8,8)/8 I8 = np.eye(8) R = 2*A - I8 # Identity matrix to leave fourth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) T = Operator(T) # Apply operator twice (2 phase inversions and # rotations about the mean) qc.append(T,q) qc.append(T,q) qc.barrier() qc.measure(q[:3],c[:3]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import qiskit as qk import numpy as np from qiskit.quantum_info.operators import Operator q = qk.QuantumRegister(5,'q') c = qk.ClassicalRegister(5,'c') qc = qk.QuantumCircuit(q,c) qc.initialize([1,0],0) qc.initialize([1,0],1) qc.initialize([1,0],2) qc.initialize([1,0],3) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.initialize([0,1],4) qc.h(4) qc.barrier() # Create oracle matrix oracle = np.eye(32) oracle[:,[13,29]] = oracle[:,[29,13]] # Create rotation about the mean matrix # n = 4 (four digits number to look for) A = np.ones(16*16).reshape(16,16)/16 I16 = np.eye(16) R = 2*A - I16 # Identity matrix to leave fifth qubit undisturbed I2 = np.eye(2) # Create second transformation matrix boost = np.kron(I2,R) # Combine oracle with second transformation matrix in # an unique operator T = boost.dot(oracle) # n = 4. Therefore it will be necessary 4 T operations # to get maximum probability. Tn = T.dot(T).dot(T) Tn = Operator(Tn) # Apply operator Tn once (n phase inversions and # rotations about the mean) qc.append(Tn,q) qc.barrier() qc.measure(q[:4],c[:4]) display(qc.draw('mpl')) simulator = qk.Aer.get_backend('statevector_simulator') results = qk.execute(qc,simulator,shots=1000).result().get_counts() qk.visualization.plot_histogram(results) import numpy as np import pandas as pd N = 35; a = 6 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = GCD.append(temp, ignore_index=True) GCD import numpy as np import pandas as pd N = 15; a = 9 GCD = pd.DataFrame({'N':[N], 'a':[a], 'N-a':[N-a]}) while GCD.iloc[-1,2] != 0: temp = GCD.iloc[-1].values temp = np.sort(temp); temp[-1] = temp[-2] - temp[-3] temp = pd.DataFrame(data = temp.reshape(-1,3), columns = ['N','a','N-a']) GCD = GCD.append(temp, ignore_index=True) GCD import numpy as np np.gcd(6,35), np.gcd(9,15) import numpy as np np.gcd(215,35), np.gcd(217,35) 20 % 7 import numpy as np f = lambda x,a,N: a**x % N [f(x,2,15) for x in range(10)] import numpy as np (13*35)%11, ((2%11)*(24%11))%11 import numpy as np def f(x,a,N): a0 = 1 for i in range(x): a0 = ((a%N)*(a0))%N return(a0) [f(x,2,371) for x in range(8)] [f(x,2,371) for x in range(154,159)] [f(x,24,371) for x in range(77,81)] import numpy as np def fr(a,N): ax = ((a%N)*(1))%N x = 1 while ax != 1: ax = ((a%N)*(ax))%N x = x+1 return(x) fr(2,371), fr(6,371), fr(24,371) import numpy as np def fr(a,N): a0 = 1 a0 = ((a%N)*a0)%N x = 2 find = False while find==False: a0 = ((a%N)*(a0))%N if a0 == 1: find = True x = x+1 return(x-1) N = 35 a = 2 fr(a,N) 2**(12/2)-1, 2**(12/2)+1 np.gcd(63,35), np.gcd(65,35) import numpy as np # Function to calculate the period of f(x) = a^x MOD N def fr(a,N): a1 = ((a%N)*(1))%N x = 1 while a1 != 1: a1 = ((a%N)*a1)%N x = x+1 return(x) # Function to factor N based on a def factor(N, a=2): r = fr(a,N) g1 = a**(int(r/2)) - 1 g2 = a**(int(r/2)) + 1 f1 = np.gcd(g1,N) f2 = np.gcd(g2,N) return(f1,f2, f1*f2) factor(247) factor(1045) import numpy as np N = 15 # number to be factored n = 4 # number of bits necessary to represent N m = 8 # number of bits necessary to represent N^2 x = np.zeros(2**m).reshape(-1,1) x[0,0] = 1 x.shape # since x is a 2^8 = 256 positions vector it will not be showed here y = np.zeros(2**n).reshape(-1,1) y[0,0] = 1; y.T # y is a 2^4 = 16 positions vector shown below psi0 = np.kron(y,x) psi0.shape # psi0 is a 256 x 16 = 4.096 positions vector In = np.eye(2**n); In.shape H = np.array([[1,1],[1,-1]])/np.sqrt(2) Hm = H.copy() for i in range(1,m): Hm = np.kron(Hm,H) Hm.shape psi1 = np.kron(In,Hm).dot(psi0); psi1.shape
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
0.4*7.6
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo import qiskit import numpy as np import networkx as nx import matplotlib.pyplot as plt from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * import json import csv # Gloabal _lambda variable _LAMBDA = 10 _SHOTS = 10000 _UNIFORM_CONVERGENCE_SAMPLE = [] # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def tsp_obj(x, G): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _LAMBDA) cost = 0 # z term for index in range(len(x)): z = (int(x[index]) * 2 ) -1 cost += z_classic_term[index] * z ## zz term for i in range(len(x)): z_1 = (int(x[i]) * 2 ) -1 for j in range(len(x)): z_2 = (int(x[j]) * 2 ) -1 cost += zz_classic_term[i][j] * z_1 * z_1 return cost # Sample expectation value def compute_tsp_energy(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj(meas, G) energy += obj_for_meas*meas_count total_counts += meas_count return energy/total_counts # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, _LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_black_box_objective(G,p): backend = Aer.get_backend('qasm_simulator') def f(theta): beta = theta[:p] gamma = theta[p:] _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) counts = execute(qc, backend, seed_simulator=10, shots=_SHOTS).result().get_counts() return compute_tsp_energy(invert_counts(counts),G) return f def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') def f(theta): beta = theta[:p] gamma = theta[p:] #print(beta) _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) #print(beta) result = execute(qc, backend, seed_simulator=10, shots=_SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() # expected value #print("prob-dict") #print(state_vector.probabilities_dict()) probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): # get cost from state cost = tsp_obj_2(state, G, _LAMBDA) expected_value += cost*probability #print(probabilities) counts = result.get_counts() #qc.save_statevector() # Tell simulator to save statevector #qobj = assemble(qc) # Create a Qobj from the circuit for the simulator to run #state_vector = sim.run(qobj).result().get_statevector() #state_vector = Statevector(state_vector) #probabilities = state_vector.probabilities() mean = compute_tsp_energy_2(invert_counts(counts),G) global _UNIFORM_CONVERGENCE_SAMPLE _UNIFORM_CONVERGENCE_SAMPLE.append({ "beta" : beta, "gamma" : gamma, "counts" : counts, "mean" : mean, "probabilities" : probabilities, "expected_value" : expected_value }) return mean return f def compute_tsp_min_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 min = 1000000000000000000000 index = 0 min_meas = "" for meas, meas_count in counts.items(): index = index + 1 obj_for_meas = tsp_obj_2(meas, G, _LAMBDA) if obj_for_meas < min: min = obj_for_meas min_meas = meas return index, min, min_meas def compute_tsp_min_energy_1(counts, G): energy = 0 get_counts = 0 total_counts = 0 min = 1000000000000000000000 index = 0 min_meas = "" for meas, meas_count in counts.items(): index = index + 1 obj_for_meas = tsp_obj(meas, G) if obj_for_meas < min: min = obj_for_meas min_meas = meas return index, min, min_meas def test_counts_2(counts, G): mean_energy2 = compute_tsp_energy_2(invert_counts(counts),G) cantidad, min, min_meas = compute_tsp_min_energy_2(invert_counts(counts),G) print("*************************") print("En el algoritmo 2 (Marina) el valor esperado como resultado es " + str(mean_energy2)) print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad)) print("El vector minimo es " + min_meas) def test_counts_1(counts, G): mean_energy1 = compute_tsp_energy(invert_counts(counts),G) cantidad, min, min_meas = compute_tsp_min_energy_1(invert_counts(counts),G) print("*************************") print("En el algoritmo 1 (Pablo) el valor esperado como resultado es " + str(mean_energy1)) print("El valor minimo de todos los evaluados es " + str(min) + " se evaluaron un total de " + str(cantidad)) print("El vector minimo es " + min_meas) def test_solution(grafo=None, p=7): global _UNIFORM_CONVERGENCE_SAMPLE _UNIFORM_CONVERGENCE_SAMPLE = [] if grafo == None: cantidad_ciudades = 2 pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) print(mejor_costo) print(mejor_camino) print(G.edges()) print(G.nodes()) else: G = grafo # beta [0,pi], gamma [0, 2pi] # create bounds for beta [0,pi] bounds = [] intial_random = [] for i in range(p): bounds.append((0, np.pi)) intial_random.append(np.random.uniform(0,np.pi)) # create bounds for gamma [0,2*pi] for i in range(p): bounds.append((0, np.pi * 2)) intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) # Pablo Solutions #obj = get_black_box_objective(G,p) #res_sample_1 = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) #print(res_sample_1) # Marina Solutions obj = get_black_box_objective_2(G,p) res_sample_2 = minimize(obj, init_point, method="COBYLA", options={"maxiter":2500,"disp":True}) print(res_sample_2) #theta_1 = res_sample_1.x theta_2 = res_sample_2.x #beta = theta_1[:p] #gamma = theta_1[p:] #_lambda = _LAMBDA # get global _lambda #qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) #backend = Aer.get_backend('qasm_simulator') #job_1 = execute(qc, backend, shots=_SHOTS) #resutls_1 = job_1.result().get_counts() #test_counts_1(resutls_1, G) beta = theta_2[:p] gamma = theta_2[p:] _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) backend = Aer.get_backend('qasm_simulator') job_2 = execute(qc, backend, shots=_SHOTS) resutls_2 = job_2.result().get_counts() test_counts_2(resutls_2, G) #print( _UNIFORM_CONVERGENCE_SAMPLE) return job_2, G, _UNIFORM_CONVERGENCE_SAMPLE def create_multiple_p_mismo_grafo(): header = ['p', 'state', 'probability', 'mean'] length_p = 10 with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) first_p = False UNIFORM_CONVERGENCE_SAMPLE = [] for p in range(length_p): p = p+1 if first_p == False: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p) first_p = True else: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) mean = UNIFORM_CONVERGENCE_SAMPLE[0]["mean"] print(mean) state = 0 for probability in UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"]: state += 1 writer.writerow([p,state, probability,mean]) def create_multiple_p_mismo_grafo_multiples_instanncias(): header = ['instance','p','distance', 'mean'] length_p = 4 length_instances = 10 with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) instance_index = 0 for instance in range(length_instances): instance_index += 1 first_p = False UNIFORM_CONVERGENCE_P = [] UNIFORM_CONVERGENCE_SAMPLE = [] for p in range(length_p): p = p+1 print("p es igual " + str(p)) if first_p == False: print("Vuelve a llamar a test_solution") job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p) first_p = True else: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["expected_value"]) convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0] UNIFORM_CONVERGENCE_P.append({ "mean":convergence_min["expected_value"], "probabilities": convergence_min["probabilities"] }) print("expected value min con p =" + str(p) + " : " + str(convergence_min["expected_value"])) cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1] p_index = 0 for p_state in UNIFORM_CONVERGENCE_P: p_index += 1 print(p_index) mean = p_state["mean"] #print(p_state) print("expected value min") print(mean) distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"])) writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean]) if __name__ == '__main__': #create_multiple_p_mismo_grafo() create_multiple_p_mismo_grafo_multiples_instanncias() def defult_init(): cantidad_ciudades = 2 pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) print(mejor_costo) print(mejor_camino) print(G.edges()) print(G.nodes()) print("labels") labels = nx.get_edge_attributes(G,'weight') #z_term, zz_term = get_classical_simplified_hamiltonian(G, 1) #print("z term") #print(z_term) #print("*****************") #print("zz term") #print(zz_term) #print(get_QAOA_circuit(G, beta = [2,3], gamma = [4,5], _lambda = 1)) p = 5 obj = get_black_box_objective(G,p) init_point = np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1]) #res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) #print(res_sample) # Marina Solutions obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) theta_2 = [0.72685401, 2.15678239, 0.86389827, 2.19403121, 0.26916675, 2.19832144, 7.06651453, 3.20333137, 3.81301611, 6.08893568] theta_1 = [0.90644898, 2.15994212, 1.8609325 , 2.14042604, 1.49126214, 2.4127999, 6.10529434, 2.18238732, 3.84056674, 6.07097744] beta = theta_1[:p] gamma = theta_1[p:] _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) print(plot_histogram(job.result().get_counts(), color='midnightblue', title="New Histogram")) beta = theta_2[:p] gamma = theta_2[p:] _lambda = _LAMBDA # get global _lambda qc = get_QAOA_circuit(G, beta, gamma, _LAMBDA) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) print(plot_histogram(job.result().get_counts(), color='midnightblue', title="New Histogram"))
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.opflow import I, X, Y, Z print(I, X, Y, Z) print(1.5 * I) print(2.5 * X) print(X + 2.0 * Y) print(X^Y^Z) print(X @ Y @ Z) print((X + Y) @ (Y + Z)) print((X + Y) ^ (Y + Z)) (I, X) 2.0 * X^Y^Z print(1.1 * ((1.2 * X)^(Y + (1.3 * Z)))) from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H, DictStateFn, VectorStateFn, CircuitStateFn, OperatorStateFn) print(Zero, One) print(Plus, Minus) print(Zero.eval('0')) print(Zero.eval('1')) print(One.eval('1')) print(Plus.eval('0')) print(Minus.eval('1')) One.adjoint() ~One (2.0 + 3.0j) * Zero print(Zero + One) import math v_zero_one = (Zero + One) / math.sqrt(2) print(v_zero_one) print(Plus + Minus) print(~One @ One) (~One @ One).eval() (~v_zero_one @ v_zero_one).eval() (~Minus @ One).eval() print((~One).compose(One)) (~One).eval(One) print(Zero^Plus) print((Zero^Plus).to_circuit_op()) print(600 * ((One^5) + (Zero^5))) print((One^Zero)^3) print(((Plus^Minus)^2).to_matrix_op()) print(((Plus^One)^2).to_circuit_op()) print(((Plus^One)^2).to_matrix_op().sample()) print(StateFn({'0':1})) print(StateFn({'0':1}) == Zero) print(StateFn([0,1,1,0])) from qiskit.circuit.library import RealAmplitudes print(StateFn(RealAmplitudes(2))) from qiskit.opflow import X, Y, Z, I, CX, T, H, S, PrimitiveOp X print(X.eval('0')) X.eval('0').eval('1') print(CX) print(CX.to_matrix().real) # The imaginary part vanishes. CX.eval('01') # 01 is the one in decimal. We get the first column. CX.eval('01').eval('11') # This returns element with (zero-based) index (1, 3) print(X @ One) (X @ One).eval() X.eval(One) print(((~One^2) @ (CX.eval('01'))).eval()) print(((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) print((((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) @ (Minus^5)) print(((H^I^I)@(X^I^I)@Zero)) print(~One @ Minus) from qiskit.opflow import ListOp print((~ListOp([One, Zero]) @ ListOp([One, Zero]))) print((~ListOp([One, Zero]) @ ListOp([One, Zero])).reduce()) print(StateFn(Z).adjoint()) StateFn(Z).adjoint() print(StateFn(Z).adjoint().eval(Zero)) print(StateFn(Z).adjoint().eval(One)) print(StateFn(Z).adjoint().eval(Plus)) import numpy as np from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki from qiskit.circuit import Parameter from qiskit import Aer two_qubit_H2 = (-1.0523732 * I^I) + \ (0.39793742 * I^Z) + \ (-0.3979374 * Z^I) + \ (-0.0112801 * Z^Z) + \ (0.18093119 * X^X) print(two_qubit_H2) evo_time = Parameter('θ') evolution_op = (evo_time*two_qubit_H2).exp_i() print(evolution_op) # Note, EvolvedOps print as exponentiations print(repr(evolution_op)) h2_measurement = StateFn(two_qubit_H2).adjoint() print(h2_measurement) bell = CX @ (I ^ H) @ Zero print(bell) evo_and_meas = h2_measurement @ evolution_op @ bell print(evo_and_meas) trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas) # We can also set trotter_mode='suzuki' or leave it empty to default to first order Trotterization. print(trotterized_op) bound = trotterized_op.bind_parameters({evo_time: .5}) bound[1].to_circuit().draw() # Note that XX was the only non-diagonal measurement in our H2 Observable print(PauliExpectation(group_paulis=False).convert(h2_measurement)) print(PauliExpectation().convert(h2_measurement)) diagonalized_meas_op = PauliExpectation().convert(trotterized_op) print(diagonalized_meas_op) evo_time_points = list(range(8)) h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points}) h2_trotter_expectations.eval() sampler = CircuitSampler(backend=Aer.get_backend('aer_simulator')) # sampler.quantum_instance.run_config.shots = 1000 sampled_trotter_exp_op = sampler.convert(h2_trotter_expectations) sampled_trotter_energies = sampled_trotter_exp_op.eval() print('Sampled Trotterized energies:\n {}'.format(np.real(sampled_trotter_energies))) print('Before:\n') print(h2_trotter_expectations.reduce()[0][0]) print('\nAfter:\n') print(sampled_trotter_exp_op[0][0]) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute, Aer from qiskit.tools.jupyter import * provider = IBMQ.load_account() # import basic plot tools from qiskit.visualization import plot_histogram def initialize(circuit, n, m): circuit.h(range(n)) # Hadamard transform on measurment register circuit.x(n+m-1) # X gate on last qubit def c_amod15(a, x): if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") # remember that a needs to be co-prime with N unitary = QuantumCircuit(4) for iteration in range(x): # bitwise arithmetic to represent modular exponentiation function if a in [2,13]: unitary.swap(0,1) unitary.swap(1,2) unitary.swap(2,3) if a in [7,8]: unitary.swap(2,3) unitary.swap(1,2) unitary.swap(0,1) if a == 11: unitary.swap(1,3) unitary.swap(0,2) if a in [7,11,13]: for q in range(4): unitary.x(q) unitary = unitary.to_gate() unitary.name = "%i^%i mod 15" % (a, x) # But we need to make it a controlled operation for phase kickback c_unitary = unitary.control() return c_unitary def modular_exponentiation(circuit, n, m, a): for exp in range(n): exponent = 2**exp circuit.append(a_x_mod15(a, exponent), [exp] + list(range(n, n+m))) from qiskit.circuit.library import QFT def apply_iqft(circuit, measurement_qubits): circuit.append(QFT( len(measurement_qubits), do_swaps=False).inverse(), measurement_qubits) def shor_algo(n, m, a): # set up the circuit circ = QuantumCircuit(n+m, n) # initialize the registers initialize(circ, n, m) circ.barrier() # map modular exponentiation problem onto qubits modular_exponentiation(circ, n, m, a) circ.barrier() # apply inverse QFT -- expose period apply_iqft(circ, range(n)) # measure the measurement register circ.measure(range(n), range(n)) return circ n = 4; m = 4; a = 11 mycircuit = shor_algo(n, m, a) mycircuit.draw('mpl') simulator = Aer.get_backend('qasm_simulator') counts = execute(mycircuit, backend=simulator, shots=1024).result().get_counts(mycircuit) plot_histogram(counts) for measured_value in counts: print(f"Measured {int(measured_value[::-1], 2)}") from math import gcd from math import sqrt from itertools import count, islice for measured_value in counts: measured_value_decimal = int(measured_value[::-1], 2) print(f"Measured {measured_value_decimal}") if measured_value_decimal % 2 != 0: print("Failed. Measured value is not an even number") continue x = int((a ** (measured_value_decimal/2)) % 15) if (x + 1) % 15 == 0: print("Failed. x + 1 = 0 (mod N) where x = a^(r/2) (mod N)") continue guesses = gcd(x + 1, 15), gcd(x - 1, 15) print(guesses) def is_prime(n): return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1))) if is_prime(guesses[0]) and is_prime(guesses[1]): print(f"**The prime factors are {guesses[0]} and {guesses[1]}**")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer from qiskit_optimization.translators import from_docplex_mp from docplex.mp.model import Model model = Model() x0 = model.binary_var(name="x0") x1 = model.binary_var(name="x1") x2 = model.binary_var(name="x2") model.minimize(-x0 + 2 * x1 - 3 * x2 - 2 * x0 * x2 - 1 * x1 * x2) qp = from_docplex_mp(model) print(qp.prettyprint()) grover_optimizer = GroverOptimizer(6, num_iterations=10, sampler=Sampler()) results = grover_optimizer.solve(qp) print(results.prettyprint()) exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver()) exact_result = exact_solver.solve(qp) print(exact_result.prettyprint()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# load necessary Runtime libraries from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session backend = "ibmq_qasm_simulator" # use the simulator from qiskit.circuit import Parameter from qiskit.opflow import I, X, Z mu = Parameter('$\\mu$') ham_pauli = mu * X cc = Parameter('$c$') ww = Parameter('$\\omega$') ham_res = -(1/2)*ww*(I^Z) + cc*(X^X) + (ham_pauli^I) tt = Parameter('$t$') U_ham = (tt*ham_res).exp_i() from qiskit import transpile from qiskit.circuit import ClassicalRegister from qiskit.opflow import PauliTrotterEvolution, Suzuki import numpy as np num_trot_steps = 5 total_time = 10 cr = ClassicalRegister(1, 'c') spec_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=num_trot_steps)).convert(U_ham) spec_circ = spec_op.to_circuit() spec_circ_t = transpile(spec_circ, basis_gates=['sx', 'rz', 'cx']) spec_circ_t.add_register(cr) spec_circ_t.measure(0, cr[0]) spec_circ_t.draw('mpl') # fixed Parameters fixed_params = { cc: 0.3, mu: 0.7, tt: total_time } # Parameter value for single circuit param_keys = list(spec_circ_t.parameters) # run through all the ww values to create a List of Lists of Parameter value num_pts = 101 wvals = np.linspace(-2, 2, num_pts) param_vals = [] for wval in wvals: all_params = {**fixed_params, **{ww: wval}} param_vals.append([all_params[key] for key in param_keys]) with Session(backend=backend): sampler = Sampler() job = sampler.run( circuits=[spec_circ_t]*num_pts, parameter_values=param_vals, shots=1e5 ) result = job.result() Zexps = [] for dist in result.quasi_dists: if 1 in dist: Zexps.append(1 - 2*dist[1]) else: Zexps.append(1) from qiskit.opflow import PauliExpectation, Zero param_bind = { cc: 0.3, mu: 0.7, tt: total_time } init_state = Zero^2 obsv = I^Z Zexp_exact = (U_ham @ init_state).adjoint() @ obsv @ (U_ham @ init_state) diag_meas_op = PauliExpectation().convert(Zexp_exact) Zexact_values = [] for w_set in wvals: param_bind[ww] = w_set Zexact_values.append(np.real(diag_meas_op.bind_parameters(param_bind).eval())) import matplotlib.pyplot as plt plt.style.use('dark_background') fig, ax = plt.subplots(dpi=100) ax.plot([-param_bind[mu], -param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot([param_bind[mu], param_bind[mu]], [0, 1], ls='--', color='purple') ax.plot(wvals, Zexact_values, label='Exact') ax.plot(wvals, Zexps, label=f"{backend}") ax.set_xlabel(r'$\omega$ (arb)') ax.set_ylabel(r'$\langle Z \rangle$ Expectation') ax.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can choose different colors for the real and imaginary parts of the density matrix. from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
https://github.com/Z-928/Bugs4Q
Z-928
# The snipplet above ==== is buggy version; the code below ==== is fixed version. from math import pi,pow from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, BasicAer, execute def IQFT(circuit, qin, n): for i in range (int(n/2)): circuit.swap(qin[i], qin[n -1 -i]) for i in range (n): circuit.h(qin[i]) for j in range (i +1, n, 1): circuit.cu1(-pi/ pow(2, j-i), qin[j], qin[i]) n = 3 qin = QuantumRegister(n) cr = ClassicalRegister(n) circuit = QuantumCircuit(qin, cr, name="Inverse_Quantum_Fourier_Transform") circuit.h(qin) circuit.z(qin[2]) circuit.s(qin[1]) circuit.z(qin[0]) circuit.t(qin[0]) IQFT(circuit, qin, n) circuit.measure (qin, cr) backend = BasicAer.get_backend("qasm_simulator") result = execute(circuit, backend, shots = 500).result() counts = result.get_counts(circuit) print(counts) #============ from math import pi,pow from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, BasicAer, execute def QFT(n, inverse=False): """This function returns a circuit implementing the (inverse) QFT.""" circuit = QuantumCircuit(n, name='IQFT' if inverse else 'QFT') # here's your old code, building the inverse QFT for i in range(int(n/2)): # note that I removed the qin register, since registers are not # really needed and you can just use the qubit indices circuit.swap(i, n - 1 - i) for i in range(n): circuit.h(i) for j in range(i + 1, n, 1): circuit.cu1(-pi / pow(2, j - i), j, i) # now we invert it to get the regular QFT if inverse: circuit = circuit.inverse() return circuit n = 3 qin = QuantumRegister(n) cr = ClassicalRegister(n) circuit = QuantumCircuit(qin, cr) circuit.h(qin) circuit.z(qin[2]) circuit.s(qin[1]) circuit.z(qin[0]) circuit.t(qin[0]) # get the IQFT and add it to your circuit with ``compose`` # if you want the regular QFT, just set inverse=False iqft = QFT(n, inverse=True) circuit.compose(iqft, inplace=True) circuit.measure (qin, cr) backend = BasicAer.get_backend("qasm_simulator") result = execute(circuit, backend, shots = 500).result() counts = result.get_counts(circuit) print(counts)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # 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 swap strategy pass for blocks of commuting gates.""" from __future__ import annotations from collections import defaultdict from qiskit.circuit import Gate, QuantumCircuit, Qubit from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.transpiler import TransformationPass, Layout, TranspilerError from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.swap_strategy import SwapStrategy from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.commuting_2q_block import ( Commuting2qBlock, ) class Commuting2qGateRouter(TransformationPass): """A class to swap route one or more commuting gates to the coupling map. This pass routes blocks of commuting two-qubit gates encapsulated as :class:`.Commuting2qBlock` instructions. This pass will not apply to other instructions. The mapping to the coupling map is done using swap strategies, see :class:`.SwapStrategy`. The swap strategy should suit the problem and the coupling map. This transpiler pass should ideally be executed before the quantum circuit is enlarged with any idle ancilla qubits. Otherwise we may swap qubits outside of the portion of the chip we want to use. Therefore, the swap strategy and its associated coupling map do not represent physical qubits. Instead, they represent an intermediate mapping that corresponds to the physical qubits once the initial layout is applied. The example below shows how to map a four qubit :class:`.PauliEvolutionGate` to qubits 0, 1, 3, and 4 of the five qubit device with the coupling map .. parsed-literal:: 0 -- 1 -- 2 | 3 | 4 To do this we use a line swap strategy for qubits 0, 1, 3, and 4 defined it in terms of virtual qubits 0, 1, 2, and 3. .. code-block:: python from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.transpiler import Layout, CouplingMap, PassManager from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import ApplyLayout from qiskit.transpiler.passes import SetLayout from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import ( SwapStrategy, FindCommutingPauliEvolutions, Commuting2qGateRouter, ) # Define the circuit on virtual qubits op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) # Define the swap strategy on qubits before the initial_layout is applied. swap_strat = SwapStrategy.from_line([0, 1, 2, 3]) # Chose qubits 0, 1, 3, and 4 from the backend coupling map shown above. backend_cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (1, 3), (3, 4)]) initial_layout = Layout.from_intlist([0, 1, 3, 4], *circ.qregs) pm_pre = PassManager( [ FindCommutingPauliEvolutions(), Commuting2qGateRouter(swap_strat), SetLayout(initial_layout), FullAncillaAllocation(backend_cmap), EnlargeWithAncilla(), ApplyLayout(), ] ) # Insert swap gates, map to initial_layout and finally enlarge with ancilla. pm_pre.run(circ).draw("mpl") This pass manager relies on the ``current_layout`` which corresponds to the qubit layout as swap gates are applied. The pass will traverse all nodes in the dag. If a node should be routed using a swap strategy then it will be decomposed into sub-instructions with swap layers in between and the ``current_layout`` will be modified. Nodes that should not be routed using swap strategies will be added back to the dag taking the ``current_layout`` into account. """ def __init__( self, swap_strategy: SwapStrategy | None = None, edge_coloring: dict[tuple[int, int], int] | None = None, ) -> None: r""" Args: swap_strategy: An instance of a :class:`.SwapStrategy` that holds the swap layers that are used, and the order in which to apply them, to map the instruction to the hardware. If this field is not given if should be contained in the property set of the pass. This allows other passes to determine the most appropriate swap strategy at run-time. edge_coloring: An optional edge coloring of the coupling map (I.e. no two edges that share a node have the same color). If the edge coloring is given then the commuting gates that can be simultaneously applied given the current qubit permutation are grouped according to the edge coloring and applied according to this edge coloring. Here, a color is an int which is used as the index to define and access the groups of commuting gates that can be applied simultaneously. If the edge coloring is not given then the sets will be built-up using a greedy algorithm. The edge coloring is useful to position gates such as ``RZZGate``\s next to swap gates to exploit CX cancellations. """ super().__init__() self._swap_strategy = swap_strategy self._bit_indices: dict[Qubit, int] | None = None self._edge_coloring = edge_coloring def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the pass by decomposing the nodes it applies on. Args: dag: The dag to which we will add swaps. Returns: A dag where swaps have been added for the intended gate type. Raises: TranspilerError: If the swap strategy was not given at init time and there is no swap strategy in the property set. TranspilerError: If the quantum circuit contains more than one qubit register. TranspilerError: If there are qubits that are not contained in the quantum register. """ if self._swap_strategy is None: swap_strategy = self.property_set["swap_strategy"] if swap_strategy is None: raise TranspilerError("No swap strategy given at init or in the property set.") else: swap_strategy = self._swap_strategy if len(dag.qregs) != 1: raise TranspilerError( f"{self.__class__.__name__} runs on circuits with one quantum register." ) if len(dag.qubits) != next(iter(dag.qregs.values())).size: raise TranspilerError("Circuit has qubits not contained in the qubit register.") new_dag = dag.copy_empty_like() current_layout = Layout.generate_trivial_layout(*dag.qregs.values()) # Used to keep track of nodes that do not decompose using swap strategies. accumulator = new_dag.copy_empty_like() for node in dag.topological_op_nodes(): if isinstance(node.op, Commuting2qBlock): # Check that the swap strategy creates enough connectivity for the node. self._check_edges(dag, node, swap_strategy) # Compose any accumulated non-swap strategy gates to the dag accumulator = self._compose_non_swap_nodes(accumulator, current_layout, new_dag) # Decompose the swap-strategy node and add to the dag. new_dag.compose(self.swap_decompose(dag, node, current_layout, swap_strategy)) else: accumulator.apply_operation_back(node.op, node.qargs, node.cargs) self._compose_non_swap_nodes(accumulator, current_layout, new_dag) return new_dag def _compose_non_swap_nodes( self, accumulator: DAGCircuit, layout: Layout, new_dag: DAGCircuit ) -> DAGCircuit: """Add all the non-swap strategy nodes that we have accumulated up to now. This method also resets the node accumulator to an empty dag. Args: layout: The current layout that keeps track of the swaps. new_dag: The new dag that we are building up. accumulator: A DAG to keep track of nodes that do not decompose using swap strategies. Returns: A new accumulator with the same registers as ``new_dag``. """ # Add all the non-swap strategy nodes that we have accumulated up to now. order = layout.reorder_bits(new_dag.qubits) order_bits: list[int | None] = [None] * len(layout) for idx, val in enumerate(order): order_bits[val] = idx new_dag.compose(accumulator, qubits=order_bits) # Re-initialize the node accumulator return new_dag.copy_empty_like() def _position_in_cmap(self, dag: DAGCircuit, j: int, k: int, layout: Layout) -> tuple[int, ...]: """A helper function to track the movement of virtual qubits through the swaps. Args: j: The index of decision variable j (i.e. virtual qubit). k: The index of decision variable k (i.e. virtual qubit). layout: The current layout that takes into account previous swap gates. Returns: The position in the coupling map of the virtual qubits j and k as a tuple. """ bit0 = dag.find_bit(layout.get_physical_bits()[j]).index bit1 = dag.find_bit(layout.get_physical_bits()[k]).index return bit0, bit1 def _build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """A helper method to build-up sets of gates to simultaneously apply. This is done with an edge coloring if the ``edge_coloring`` init argument was given or with a greedy algorithm if not. With an edge coloring all gates on edges with the same color will be applied simultaneously. These sublayers are applied in the order of their color, which is an int, in increasing color order. Args: current_layer: All gates in the current layer can be applied given the qubit ordering of the current layout. However, not all gates in the current layer can be applied simultaneously. This function creates sub-layers by building up sub-layers of gates. All gates in a sub-layer can simultaneously be applied given the coupling map and current qubit configuration. Returns: A list of gate dicts that can be applied. The gates a position 0 are applied first. A gate dict has the qubit tuple as key and the gate to apply as value. """ if self._edge_coloring is not None: return self._edge_coloring_build_sub_layers(current_layer) else: return self._greedy_build_sub_layers(current_layer) def _edge_coloring_build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The edge coloring method of building sub-layers of commuting gates.""" sub_layers: list[dict[tuple[int, int], Gate]] = [ {} for _ in set(self._edge_coloring.values()) ] for edge, gate in current_layer.items(): color = self._edge_coloring[edge] sub_layers[color][edge] = gate return sub_layers @staticmethod def _greedy_build_sub_layers( current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The greedy method of building sub-layers of commuting gates.""" sub_layers = [] while len(current_layer) > 0: current_sub_layer, remaining_gates = {}, {} blocked_vertices: set[tuple] = set() for edge, evo_gate in current_layer.items(): if blocked_vertices.isdisjoint(edge): current_sub_layer[edge] = evo_gate # A vertex becomes blocked once a gate is applied to it. blocked_vertices = blocked_vertices.union(edge) else: remaining_gates[edge] = evo_gate current_layer = remaining_gates sub_layers.append(current_sub_layer) return sub_layers def swap_decompose( self, dag: DAGCircuit, node: DAGOpNode, current_layout: Layout, swap_strategy: SwapStrategy ) -> DAGCircuit: """Take an instance of :class:`.Commuting2qBlock` and map it to the coupling map. The mapping is done with the swap strategy. Args: dag: The dag which contains the :class:`.Commuting2qBlock` we route. node: A node whose operation is a :class:`.Commuting2qBlock`. current_layout: The layout before the swaps are applied. This function will modify the layout so that subsequent gates can be properly composed on the dag. swap_strategy: The swap strategy used to decompose the node. Returns: A dag that is compatible with the coupling map where swap gates have been added to map the gates in the :class:`.Commuting2qBlock` to the hardware. """ trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) gate_layers = self._make_op_layers(dag, node.op, current_layout, swap_strategy) # Iterate over and apply gate layers max_distance = max(gate_layers.keys()) circuit_with_swap = QuantumCircuit(len(dag.qubits)) for i in range(max_distance + 1): # Get current layer and replace the problem indices j,k by the corresponding # positions in the coupling map. The current layer corresponds # to all the gates that can be applied at the ith swap layer. current_layer = {} for (j, k), local_gate in gate_layers.get(i, {}).items(): current_layer[self._position_in_cmap(dag, j, k, current_layout)] = local_gate # Not all gates that are applied at the ith swap layer can be applied at the same # time. We therefore greedily build sub-layers. sub_layers = self._build_sub_layers(current_layer) # Apply sub-layers for sublayer in sub_layers: for edge, local_gate in sublayer.items(): circuit_with_swap.append(local_gate, edge) # Apply SWAP gates if i < max_distance: for swap in swap_strategy.swap_layer(i): (j, k) = [trivial_layout.get_physical_bits()[vertex] for vertex in swap] circuit_with_swap.swap(j, k) current_layout.swap(j, k) return circuit_to_dag(circuit_with_swap) def _make_op_layers( self, dag: DAGCircuit, op: Commuting2qBlock, layout: Layout, swap_strategy: SwapStrategy ) -> dict[int, dict[tuple, Gate]]: """Creates layers of two-qubit gates based on the distance in the swap strategy.""" gate_layers: dict[int, dict[tuple, Gate]] = defaultdict(dict) for node in op.node_block: edge = (dag.find_bit(node.qargs[0]).index, dag.find_bit(node.qargs[1]).index) bit0 = layout.get_virtual_bits()[dag.qubits[edge[0]]] bit1 = layout.get_virtual_bits()[dag.qubits[edge[1]]] distance = swap_strategy.distance_matrix[bit0, bit1] gate_layers[distance][edge] = node.op return gate_layers def _check_edges(self, dag: DAGCircuit, node: DAGOpNode, swap_strategy: SwapStrategy): """Check if the swap strategy can create the required connectivity. Args: node: The dag node for which to check if the swap strategy provides enough connectivity. swap_strategy: The swap strategy that is being used. Raises: TranspilerError: If there is an edge that the swap strategy cannot accommodate and if the pass has been configured to raise on such issues. """ required_edges = set() for sub_node in node.op: edge = (dag.find_bit(sub_node.qargs[0]).index, dag.find_bit(sub_node.qargs[1]).index) required_edges.add(edge) # Check that the swap strategy supports all required edges if not required_edges.issubset(swap_strategy.possible_edges): raise TranspilerError( f"{swap_strategy} cannot implement all edges in {required_edges}." )
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import copy from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute, transpile, assemble from qiskit.tools.visualization import * from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) import json from scipy.signal import savgol_filter import time from qiskit.tools.monitor import job_monitor from o_utils import ora # classifier utilities from o_plot import opl # utilities for result plot from c_utils import new_cut # circuit building utilities def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) # common code for calling the classifier for ideal device and for real devices def add_single_dic(target_data_list): start_time = time.time() print("started",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name) # added for D,S,M choice. Mainstream : mixed set of 20 states first = 0 last = nb_states if unique_char == "D": last = int(nb_states/2) elif unique_char == "S": first = int(nb_states/2) # get the classifier error curve in function of the number of shot and the "safe shot number" error_curve, safe_rate, ernb = ora.provide_error_curve(PD_model=model_dic[model_name][first:last,:], PD_test=PD_test[first:last,:], trials=trials, window=window, epsilon=epsilon, max_shots=max_shots, pol=pol, verbosality=verbosality) tail = savgol_filter(ernb, window, pol, axis=0) len_curve = len(error_curve) safe_shot_nb = len_curve - int((window-1)/2) # OK print('safe_shot_nb',safe_shot_nb, 'safe_rate',safe_rate, "nb trials:",trials) err_rates = tail[int((window-1)/2),:]/trials err_rate_max = np.max(err_rates) err_rate_min = np.min(err_rates) r=4 print("savgol interpolated error rate mean:", np.round(np.mean(err_rates),r), "min:", np.round(err_rate_min,r), "max:", np.round(err_rate_max,r), "for", [ien for ien, jen in enumerate(err_rates) if jen == err_rate_max]) end_time = time.time() #save the data in a list of dictionaries : single_dic={"project":mitig_name, "id_gates":id_gates, "mitigation":mit_str, "model":model_name, "metric":o_metric, "device":project_device, "curve_length":len_curve, "shots": safe_shot_nb, "shots_rate": safe_rate, "error_curve":error_curve, "trials":trials,"window":window, "epsilon":epsilon,"SG_pol": pol, "computation_time":end_time-start_time, "time_completed":time.strftime('%d/%m/%Y %H:%M:%S'), "trials":trials, "QV": QV_dic[project_device], "fidelity": fidelity_dic[project_device], "error_nb":ernb} target_data_list.append(single_dic) print("completed",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name,"\n") simulator = Aer.get_backend('qasm_simulator') #specify the layout of the devices used_qubits = 5 qubit_list = [0,1,2,3,4] #short_version = False #program_name="QAD" # 1st pilot project GHZ Psi+ / W Phi+ program_name="AL2" # 2d pilot project W Psi+ / Wbar Phi+ Flag_char = "DS" # this for a mix of two types of separable states if len(Flag_char) >= 2: unique_char = "M" else: unique_char = Flag_char # These dictionaries for the devices used in the study if program_name == "QAD": fidelity_dic = {'ibmq_athens': 0.925110, 'ibmq_valencia': 0.809101, 'ibmq_ourense': 0.802380, "ibmqx2": 0.627392, 'ibmq_santiago': 0.919399, 'ibmq_vigo': 0.908840, 'ideal_device': 1.0} data_directory = "data_files/" elif program_name == "AL2": fidelity_dic = {'ibmq_athens': 0.910145, 'ibmq_valencia': 0.794262, 'ibmq_ourense': 0.818974, "ibmqx2": 0.359528, 'ibmq_santiago': 0.900024, 'ibmq_vigo': 0.841831, 'ideal_device': 1.0} data_directory = "data2_files/" QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0, "ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf} dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our", "ibmqx2": 'Yor', 'ideal_device': "Ide"} # specify the device: here first the ideal noise-free device project_device = 'ideal_device' device_name = dev_dic[project_device] # specify the nb of id gates between state creation and measurements # zero for the ideal device id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) # tail of the file names for RAM storage mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # establish the result label list # meas_calibs will be used for mitigation in the real device section qr = QuantumRegister(used_qubits) meas_calibs, label_list = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') nb_labels=len(label_list) print(nb_labels,label_list) len(meas_calibs) # permutation list # here it is simple to write down the list, # but a version using itertools will be wellcome for >5 qubits projects if used_qubits == 5: q_perm = [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 1, 4, 2, 3], [0, 2, 3, 1, 4], [0, 2, 4, 1, 3], [0, 3, 4, 1, 2], [1, 2, 3, 0, 4], [1, 2, 4, 0, 3], [1, 3, 4, 0, 2], [2, 3, 4, 0, 1]] else: print("work in progress - meanwhile please provide the list of permutations") # define the two subsets of 10 separable states if program_name == "QAD": state_1a = ["W","Phi+"] state_1b = ["GHZ","Psi+"] elif program_name == "ALT" or "AL2": state_1a = ["W","Psi+"] state_1b = ["Wbar","Phi+"] l_states = state_1a+state_1b l_states # version 20 circuits for demonstration # (in the version run on real devices: two batches of 10 circuits, "shallow" and "deep") # these circuits limited to state creation are ready to be saved # for ultimately building circuits adapted to noisy simulator and real devices # as option, these circuits will include a row of id gates between creation and measurements circ_ori = [] for i_s in range(0,len(l_states),2): for perm in q_perm: mycircuit = QuantumCircuit(used_qubits, used_qubits) mycircuit = new_cut.circuit_builder(mycircuit, perm, l_states[i_s],l_states[i_s+1]) circ_ori.append(mycircuit) # add measurement section to the circuit set newly created: nb_states = len(circ_ori) circ_ideal = copy.deepcopy(circ_ori) for i_state in range(nb_states): new_cut.add_barrier_and_measure(circ_ideal[i_state],qubit_list) ideal_dic = {} # execute on noise free simulator s_sim = 12000 job_simul = execute(circ_ideal, backend=simulator, shots=s_sim) tot_results_simul = job_simul.result() # establish a dictionary of count results on noise free simulator: # (this step is only useful if ram storage is performed) void_counts = dict(zip(label_list, np.zeros(2**used_qubits))) tot_results_sim_dic = {} for i_state in range(nb_states): counts_simul = copy.deepcopy(void_counts) counts_simul.update(tot_results_simul.get_counts(i_state)) ideal_dic[str(i_state)]=counts_simul i_state_test = 10 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) i_state_test = 10 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) # try loading the dictionary of results if its creation was skipped if len(ideal_dic) == 0: ideal_dic = json_dic_loader("ideal_dic_"+project_name) nb_states = len(ideal_dic) nb_labels = len(list(ideal_dic.values())[0]) s_sim = sum(list(ideal_dic.values())[0].values()) PD_ideal = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): PD_ideal[i_state, :] = list(ideal_dic[str(i_state)].values()) # now a little trick to get the ideal values from the simulator approximated values with np.errstate(divide='ignore'): # ignore the divide by zero warning PD_ideal = 1/np.round(s_sim/(PD_ideal)) # have a look at the matrix head and tail: print("first and last state probability distributions:") print(np.round(np.vstack((PD_ideal[0:1,:],PD_ideal[-1:,:])),4)) # here will be appended the data we want for the curve plot ideal_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary (readme file): trials=100 # to be set to 10000 if not demo window=5 # shorter window than for the real device counts epsilon = .001 min_shots = 5 max_shots = 100 pol=2 subset = None # variable not used here verbosality = 5 # printing step for intermediate results when increasing the experiment shot number PD_test = PD_ideal mitigation_dic = {"Na": None} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] model_dic = {"ideal_sim": PD_ideal} for mit_str, mitigation in mitigation_dic.items(): if mitigation != None: # thus only for counts on real device PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: for model_name in model_dic.keys(): add_single_dic(ideal_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(ideal_data_list) == 0: ideal_data_list = json_dic_loader("ideal_device_data_list_"+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors the unsmoothed values opl.plot_curves(ideal_data_list,np.array([0,1]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$" , ["model"], ["device","metric"], right_xlimit = 20, bottom_ylimit = -0.001, top_ylimit = 0.05) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() project_device = 'ibmq_valencia'# you may choice here a different backend device_name = dev_dic[project_device] mitig_name = program_name + "_" + device_name print(mitig_name) #determine here the backend device = provider.get_backend(project_device) # the backend names are listed here above properties = device.properties() coupling_map = device.configuration().coupling_map # retrieve the corresponding measurement mitigation filter obtained at experimental time # use a fake job because use of the from_dict method simulator = Aer.get_backend('qasm_simulator') fake_job_cal = execute(meas_calibs, backend=simulator, shots=1) fake_cal_results = fake_job_cal.result() cal_results_dic = json_dic_loader("cal_results_dic_"+mitig_name) if 'date' in cal_results_dic.keys(): str(cal_results_dic['date']) cal_results = fake_cal_results.from_dict(cal_results_dic) meas_fitter = CompleteMeasFitter(cal_results, label_list, qubit_list=qubit_list, circlabel='mcal') meas_filter = meas_fitter.filter # have a look at the average measurement fidefily of this device: print("Average Measurement Fidelity was: %f" % meas_fitter.readout_fidelity(), "for",project_device) id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) project_name = mitig_name + "_" + unique_char + zfilled print(project_name) # transpile verbose = True summary_dic = {} seed_transpiler_list = list(range(nb_states)) real_circs = [] start_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Start at DMY: ",start_time) for i_state in list(range(nb_states)): # prepare circuit to be transpiled circuit = copy.deepcopy(circ_ori[i_state]) if id_gates > 0: circuit.barrier() for id_gates_index in range(id_gates): for index, value in enumerate(qubit_list): circuit.id(value) new_cut.add_barrier_and_measure(circuit, qubit_list) summary = [] depth_list = [] Q_state_opt_new = transpile(circuit, backend=device, coupling_map = coupling_map, seed_transpiler=seed_transpiler_list[i_state], optimization_level=2, initial_layout=qubit_list) summary_dic[i_state] = {"depth": Q_state_opt_new.depth(), 'circuit':Q_state_opt_new} real_circs.append(Q_state_opt_new) if verbose: print("circuit %2i" % i_state,"length",summary_dic[i_state]["depth"], "DMY: ",time.strftime('%d/%m/%Y %H:%M:%S')) end_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Completed at DMY: ",end_time) i_state_test = 10 print(project_device, "circuit #",i_state_test, "circuit length:",real_circs[i_state_test].depth()) #summary_dic[i_state_test]['depth']) # you may want to skip this if large nb of id gates before measurement real_circs[i_state_test].draw(output='mpl') #check a circuit on noise-free simulator job_simul = execute(real_circs[i_state_test], backend=simulator, shots=s_sim) print(project_device, "circuit #",i_state_test, "on noise free simulator") plot_histogram(job_simul.result().get_counts(), legend=['noise free simulation'], color = "b", figsize=(10.,5.)) #changing keys of dictionary for merging: def key_change(ini_dict, i_subset): ini_list = [] len_ini = len(ini_dict) for i in range(len_ini): ini_list.append(str(i+i_subset*len_ini)) return dict(zip(ini_list, list(ini_dict.values()))) if program_name == "QAD": #retrieve the data corresponding to the 1st project lfc = list(Flag_char) circ_ideal =[] empirical_dic = {} for i_subset, subset in enumerate(lfc): qasm_circs_dic = json_dic_loader('qasm_circs_dic_QAD_'+device_name+'_'+ subset + zfilled) j=0 # j included for project with several transpilation sessions for each device - not used here qasm_circs = qasm_circs_dic[str(j)] nb_circs = len(qasm_circs) for i_circs in range(nb_circs): circ_ideal.append(QuantumCircuit().from_qasm_str(qasm_circs[i_circs])) empirical_dic = {**empirical_dic, **key_change(json_dic_loader("experimental"+"_"+mitig_name +"_"\ +subset+zfilled), i_subset)} test_dic = copy.deepcopy(empirical_dic) #nb_states = len(circ_ideal) if program_name == "AL2": empirical_dic = json_dic_loader('experimental_'+project_name) test_dic = json_dic_loader('test_'+project_name) def rectify_counts(tot_res, test_cqi,mitigation,m_filter) : void_counts = dict(zip(label_list, np.zeros(2**used_qubits))) try: counts_results_real_test = tot_res[str(test_cqi)] except KeyError as error: counts_results_real_test = tot_res[test_cqi] raw_counts_test = copy.deepcopy(void_counts) raw_counts_test.update(counts_results_real_test) if mitigation: mitigated_results_test = meas_filter.apply(raw_counts_test, method = 'least_squares') returned_counts = copy.deepcopy(void_counts) returned_counts.update(mitigated_results_test) else: returned_counts = copy.deepcopy(raw_counts_test) return returned_counts def get_clean_matrix(dic, mitigation,m_filter): clean_matrix = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): rectified_counts = rectify_counts(dic,i_state, mitigation,m_filter) # get a rectified counts dictionary clean_matrix[i_state, :] = list(rectified_counts.values()) clean_matrix = clean_matrix/clean_matrix.sum(axis=1, keepdims=True) return clean_matrix # We need to create a first matrix version. It will then vary for each considered set of distribution mitigation = False PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_exper[0:1,:],PD_exper[-1:,:])),3)) if program_name == "QAD": PD_test = copy.deepcopy(PD_exper) elif program_name == "AL2": mitigation = False PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_test[0:1,:],PD_test[-1:,:])),3)) # here will be appended the data we want for the final plot of this notebook empirical_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary notebook: trials=100 # should be 1000 if not demo window=11 epsilon = .001 max_shots = 500 pol=2 verbosality = 10 # printing step for intermediate results when increasing the experiment shot number # In this section you can easily make your choice of combinations: # mitigation or not, metric, model mitigation_dic = {"no":False, "yes" : True} #mitigation_dic = {"no":False} #mitigation_dic = {"yes" : True} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] #o_metrics_desired = ['jensenshannon'] #o_metrics_desired = ['sqeuclidean'] model_dic = {"empirical": PD_exper, "ideal_sim": PD_ideal} #model_dic = {"empirical": PD_exper} #model_dic = {"ideal_sim": PD_ideal} # Obtain a sequence of results in form of a list of dictionaries for mit_str, mitigation in mitigation_dic.items(): # here we toggle PD_exper as we toggled mitigation status PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: print(project_name, model_dic.keys(), o_metric) for model_name in model_dic.keys(): add_single_dic(empirical_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(empirical_data_list) == 0: empirical_data_list = json_dic_loader('Nemp_data_list_'+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors are the unsmoothed values opl.plot_curves(ideal_data_list + empirical_data_list, np.array(range(2+len(empirical_data_list))), "$\epsilon=0.001$" , ["device"], ["model","metric","mitigation","id_gates"], right_xlimit = 80, bottom_ylimit = -0.02, top_ylimit = 1) import winsound duration = 2000 # milliseconds freq = 800 # Hz winsound.Beep(freq, duration) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.problems import ElectronicBasis driver = PySCFDriver() driver.run_pyscf() ao_problem = driver.to_problem(basis=ElectronicBasis.AO) print(ao_problem.basis) ao_hamil = ao_problem.hamiltonian print(ao_hamil.electronic_integrals.alpha) from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema qcschema = driver.to_qcschema() basis_transformer = get_ao_to_mo_from_qcschema(qcschema) print(basis_transformer.initial_basis) print(basis_transformer.final_basis) mo_problem = basis_transformer.transform(ao_problem) print(mo_problem.basis) mo_hamil = mo_problem.hamiltonian print(mo_hamil.electronic_integrals.alpha) import numpy as np from qiskit_nature.second_q.operators import ElectronicIntegrals from qiskit_nature.second_q.problems import ElectronicBasis from qiskit_nature.second_q.transformers import BasisTransformer ao2mo_alpha = np.random.random((2, 2)) ao2mo_beta = np.random.random((2, 2)) basis_transformer = BasisTransformer( ElectronicBasis.AO, ElectronicBasis.MO, ElectronicIntegrals.from_raw_integrals(ao2mo_alpha, h1_b=ao2mo_beta), ) from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5") full_problem = driver.run() print(full_problem.molecule) print(full_problem.num_particles) print(full_problem.num_spatial_orbitals) from qiskit_nature.second_q.transformers import FreezeCoreTransformer fc_transformer = FreezeCoreTransformer() fc_problem = fc_transformer.transform(full_problem) print(fc_problem.num_particles) print(fc_problem.num_spatial_orbitals) print(fc_problem.hamiltonian.constants) fc_transformer = FreezeCoreTransformer(remove_orbitals=[4, 5]) fc_problem = fc_transformer.transform(full_problem) print(fc_problem.num_particles) print(fc_problem.num_spatial_orbitals) from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5") full_problem = driver.run() print(full_problem.num_particles) print(full_problem.num_spatial_orbitals) from qiskit_nature.second_q.transformers import ActiveSpaceTransformer as_transformer = ActiveSpaceTransformer(2, 2) as_problem = as_transformer.transform(full_problem) print(as_problem.num_particles) print(as_problem.num_spatial_orbitals) print(as_problem.hamiltonian.electronic_integrals.alpha) as_transformer = ActiveSpaceTransformer(2, 2, active_orbitals=[0, 4]) as_problem = as_transformer.transform(full_problem) print(as_problem.num_particles) print(as_problem.num_spatial_orbitals) print(as_problem.hamiltonian.electronic_integrals.alpha) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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. """ Drawing objects for timeline drawer. Drawing objects play two important roles: - Allowing unittests of visualization module. Usually it is hard for image files to be tested. - Removing program parser from each plotter interface. We can easily add new plotter. This module is based on the structure of matplotlib as it is the primary plotter of the timeline drawer. However this interface is agnostic to the actual plotter. Design concept ~~~~~~~~~~~~~~ When we think about dynamically updating drawings, it will be most efficient to update only the changed properties of drawings rather than regenerating entirely from scratch. Thus the core :py:class:`~qiskit.visualization.timeline.core.DrawerCanvas` generates all possible drawings in the beginning and then the canvas instance manages visibility of each drawing according to the end-user request. Data key ~~~~~~~~ In the abstract class ``ElementaryData`` common attributes to represent a drawing are specified. In addition, drawings have the `data_key` property that returns an unique hash of the object for comparison. This key is generated from a data type, the location of the drawing in the canvas, and associated qubit or classical bit objects. See py:mod:`qiskit.visualization.timeline.types` for detail on the data type. If a data key cannot distinguish two independent objects, you need to add a new data type. The data key may be used in the plotter interface to identify the object. Drawing objects ~~~~~~~~~~~~~~~ To support not only `matplotlib` but also multiple plotters, those drawings should be universal and designed without strong dependency on modules in `matplotlib`. This means drawings that represent primitive geometries are preferred. It should be noted that there will be no unittest for each plotter API, which takes drawings and outputs image data, we should avoid adding a complicated geometry that has a context of the scheduled circuit program. For example, a two qubit scheduled gate may be drawn by two rectangles that represent time occupation of two quantum registers during the gate along with a line connecting these rectangles to identify the pair. This shape can be represented with two box-type objects with one line-type object instead of defining a new object dedicated to the two qubit gate. As many plotters don't support an API that visualizes such a linked-box shape, if we introduce such complex drawings and write a custom wrapper function on top of the existing API, it could be difficult to prevent bugs with the CI tools due to lack of the effective unittest for image data. Link between gates ~~~~~~~~~~~~~~~~~~ The ``GateLinkData`` is the special subclass of drawing that represents a link between bits. Usually objects are associated to the specific bit, but ``GateLinkData`` can be associated with multiple bits to illustrate relationship between quantum or classical bits during a gate operation. """ from abc import ABC from enum import Enum from typing import Optional, Dict, Any, List, Union import numpy as np from qiskit import circuit from qiskit.visualization.timeline import types from qiskit.visualization.exceptions import VisualizationError class ElementaryData(ABC): """Base class of the scheduled circuit visualization object. Note that drawings are mutable. """ __hash__ = None def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bits: Optional[Union[types.Bits, List[types.Bits]]] = None, meta: Optional[Dict[str, Any]] = None, styles: Optional[Dict[str, Any]] = None, ): """Create new drawing. Args: data_type: String representation of this drawing. xvals: Series of horizontal coordinate that the object is drawn. yvals: Series of vertical coordinate that the object is drawn. bits: Qubit or Clbit object bound to this drawing. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ if bits and isinstance(bits, (circuit.Qubit, circuit.Clbit)): bits = [bits] if isinstance(data_type, Enum): data_type = data_type.value self.data_type = str(data_type) self.xvals = xvals self.yvals = yvals self.bits = bits self.meta = meta self.styles = styles @property def data_key(self): """Return unique hash of this object.""" return str( hash( ( self.__class__.__name__, self.data_type, tuple(self.bits), tuple(self.xvals), tuple(self.yvals), ) ) ) def __repr__(self): return f"{self.__class__.__name__}(type={self.data_type}, key={self.data_key})" def __eq__(self, other): return isinstance(other, self.__class__) and self.data_key == other.data_key class LineData(ElementaryData): """Drawing object that represents line shape.""" def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bit: types.Bits, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new line. Args: data_type: String representation of this drawing. xvals: Series of horizontal coordinate that the object is drawn. yvals: Series of vertical coordinate that the object is drawn. bit: Bit associated to this object. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ super().__init__( data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles ) class BoxData(ElementaryData): """Drawing object that represents box shape.""" def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bit: types.Bits, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new box. Args: data_type: String representation of this drawing. xvals: Left and right coordinate that the object is drawn. yvals: Top and bottom coordinate that the object is drawn. bit: Bit associated to this object. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. Raises: VisualizationError: When number of data points are not equals to 2. """ if len(xvals) != 2 or len(yvals) != 2: raise VisualizationError("Length of data points are not equals to 2.") super().__init__( data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles ) class TextData(ElementaryData): """Drawing object that represents a text on canvas.""" def __init__( self, data_type: Union[str, Enum], xval: types.Coordinate, yval: types.Coordinate, bit: types.Bits, text: str, latex: Optional[str] = None, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new text. Args: data_type: String representation of this drawing. xval: Horizontal coordinate that the object is drawn. yval: Vertical coordinate that the object is drawn. bit: Bit associated to this object. text: A string to draw on the canvas. latex: If set this string is used instead of `text`. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ self.text = text self.latex = latex super().__init__( data_type=data_type, xvals=[xval], yvals=[yval], bits=bit, meta=meta, styles=styles ) class GateLinkData(ElementaryData): """A special drawing data type that represents bit link of multi-bit gates. Note this object takes multiple bits and dedicates them to the bit link. This may appear as a line on the canvas. """ def __init__( self, xval: types.Coordinate, bits: List[types.Bits], styles: Dict[str, Any] = None ): """Create new bit link. Args: xval: Horizontal coordinate that the object is drawn. bits: Bit associated to this object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ super().__init__( data_type=types.LineType.GATE_LINK, xvals=[xval], yvals=[0], bits=bits, meta=None, styles=styles, )
https://github.com/grossiM/Qiskit_workshop1019
grossiM
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # qiskit-ibmq-provider has been deprecated. # Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail. from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options # Loading your IBM Quantum account(s) service = QiskitRuntimeService(channel="ibm_quantum") # Invoke a primitive. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html # result = Sampler("ibmq_qasm_simulator").run(circuits).result() # Built-in modules import math # Imports from Qiskit from qiskit import QuantumCircuit from qiskit.circuit.library import GroverOperator, MCMT, ZGate from qiskit.visualization import plot_distribution # Imports from Qiskit Runtime from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session # Add your token below service = QiskitRuntimeService(channel="ibm_quantum") from qiskit import IBMQ IBMQ.save_account('33b329939cf6fe545c64afb41b84e0993a774c578c2d3e3a07b2ed8644261511d4712974c684ae3050ca82dd8f4ca161930bb344995de7934be32214bdb17079')
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
import cirq ## Data qubit and target qubit q0, q1 = cirq.LineQubit.range(2) ## Dictionary of oracles oracles = {'0' : [], '1' : [cirq.X(q1)], 'x' : [cirq.CNOT(q0, q1)], 'notx' : [cirq.CNOT(q0, q1), cirq.X(q1)]} def deutsch_algorithm(oracle): ## Yield a circuit for Deustch algorithm given operations implementing yield cirq.X(q1) yield cirq.H(q0), cirq.H(q1) yield oracle yield cirq.H(q0) yield cirq.measure(q0) for key, oracle in oracles.items(): print('Circuit for {} :'. format(key)) print(cirq.Circuit.from_ops(deutsch_algorithm(oracle)), end = "\n\n") simulator = cirq.Simulator() for key, oracle in oracles.items(): result = simulator.run(cirq.Circuit.from_ops(deutsch_algorithm(oracle)), repetitions=20) print('Oracle : {:<4} results: {}'. format(key, result)) import cirq q0, q1, q2 = cirq.LineQubit.range(3) ## Oracles for constant functions constant = ([], [cirq.X(q2)]) ## Oracles for balanced functions balanced = ([cirq.CNOT(q0, q2)], [cirq.CNOT(q1, q2)], [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2)], [cirq.CNOT(q0, q2), cirq.X(q2)], [cirq.CNOT(q1, q2), cirq.X(q2)], [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2), cirq.X(q2)] ) def your_circuit(oracle): ## Phase kickback trick yield cirq.X(q2), cirq.H(q2) ## Equal Superposition over input bits yield cirq.H(q0), cirq.H(q1) ## Query the function yield oracle ## interface to get result, put last qubit into |1> yield cirq.H(q0), cirq.H(q1), cirq.H(q2) ## a final OR gate to put result in final qubit yield cirq.X(q0), cirq.X(q1), cirq.CCX(q0, q1, q2) yield cirq.measure(q2) simulator = cirq.Simulator() print("your result on constant functions:") for oracle in constant: result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10) print(result) print("your result on balanced functions:") for oracle in balanced: result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10) print(result)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') from qiskit import IBMQ from qiskit.providers.ibmq.visualization import iplot_error_map IBMQ.load_account() provider = IBMQ.get_provider(group='open', project='main') backend = provider.get_backend('ibmq_vigo') iplot_error_map(backend, as_widget=True)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
min_qubits=2 max_qubits=8 max_circuits=1 num_shots=1000 backend_id="qasm_simulator" hub="ibm-q"; group="open"; project="main" provider_backend = None exec_options = {} # # ========================== # # *** If using IBMQ hardware, run this once to authenticate # from qiskit import IBMQ # IBMQ.save_account('YOUR_API_TOKEN_HERE') # # *** If you are part of an IBMQ group, set hub, group, and project name here # hub="YOUR_HUB_NAME"; group="YOUR_GROUP_NAME"; project="YOUR_PROJECT_NAME" # # *** This example shows how to specify an IBMQ backend using a known "backend_id" # exec_options = { "optimization_level":3, "use_sessions":True, "resilience_level":1} # backend_id="ibmq_belem" # # ========================== # # *** If using Azure Quantum, use this hub identifier and specify the desired backend_id # # Identify your resources with env variables AZURE_QUANTUM_RESOURCE_ID and AZURE_QUANTUM_LOCATION # hub="azure-quantum"; group="open"; project="QED-C App-Oriented Benchmarks - Qiskit Version" # backend_id="<YOUR_BACKEND_NAME_HERE>" # # ========================== # The remaining examples create a provider instance and get a backend from it # # An example using IonQ provider # from qiskit_ionq import IonQProvider # provider = IonQProvider() # Be sure to set the QISKIT_IONQ_API_TOKEN environment variable # provider_backend = provider.get_backend("ionq_qpu") # backend_id="ionq_qpu" # # An example using BlueQubit provider # import sys # sys.path.insert(1, "../..") # import os, bluequbit, _common.executors.bluequbit_executor as bluequbit_executor # provider_backend = bluequbit.init() # backend_id="BlueQubit-CPU" # exec_options = { "executor": bluequbit_executor.run, "device":'cpu' } # # *** Here's an example of using a typical custom provider backend (e.g. AQT simulator) # import os # from qiskit_aqt_provider import AQTProvider # provider = AQTProvider(os.environ.get('AQT_ACCESS_KEY')) # get your key from environment # provider_backend = provider.backends.aqt_qasm_simulator_noise_1 # backend_id="aqt_qasm_simulator_noise_1" import os, hydrogen_lattice_benchmark #backend_id="qasm_simulator" # Additional arguments specific to Hydrogen Lattice benchmark method 2 plotting hl_app_args = dict( # display options for line plots (pairwise) line_y_metrics=['energy', 'accuracy_ratio_error'], # + 'solution_quality', 'accuracy_ratio', 'solution_quality_error' line_x_metrics=['iteration_count', 'cumulative_exec_time'], # + 'cumulative_elapsed_time' plot_layout_style='grid', # plot layout, can be 'grid', 'stacked', or 'individual' # display options for bar plots (exec time, accuracy ratio) bar_y_metrics=["average_exec_times", "accuracy_ratio_error"], bar_x_metrics=["num_qubits"], use_logscale_for_times=False, # use log scale for cumulative exec time bar chart show_elapsed_times=True, # include elapsed time in average_exec_times plot # display options for area plots (multiplicative) score_metric=['accuracy_ratio'], # + 'solution_quality' x_metric=['cumulative_exec_time', 'cumulative_elapsed_time'], # + 'cumulative_opt_exec_time', ) hydrogen_lattice_benchmark.load_data_and_plot(os.path.join('__data', backend_id, ''), backend_id=backend_id, **hl_app_args) import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # define a custom Nelder-Mead minimizer function from scipy.optimize import minimize tol=0.01 max_iter=30 def my_minimizer(objective_function, initial_parameters, callback): ret = minimize(objective_function, x0=initial_parameters, # a custom minimizer method='nelder-mead', options={'xatol':tol, 'fatol':tol, 'maxiter': max_iter, 'maxfev': max_iter, 'disp': False}, callback=callback) print(f"\n... my_minimizer completed, return = \n{ret}") return ret # Additional arguments specific to Hydrogen Lattice benchmark method 2 hl_app_args = dict( max_iter=30, # maximum minimizer iterations to perform comfort=True, # show 'comfort dots' during execution minimizer_function=my_minimizer, # use custom minimizer function ) # Run the benchmark in method 2 hydrogen_lattice_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args ) import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # Arguments specific to execution of single instance of the Hydrogen Lattice objective function hl_app_args = dict( num_qubits=4, # problem size, dexscribed by number of qubits num_shots=1000, # number of shots to perform radius=1.0, # select single problem radius, None = use first radius parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs thetas_array=[ 0.0 ], # use custom thetas_array backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, ) # Execute the objective function once with the given arguments energy, key_metrics = hydrogen_lattice_benchmark.run_objective_function(**hl_app_args) # Print the return value of energy print(f"Final Energy value = {energy}") # Print key metrics from execution print(f"Key Metrics = {key_metrics}") import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # Arguments specific to Hydrogen Lattice benchmark method (2) hl_app_args = dict( min_qubits=2, # configure min, max widths, and shots here max_qubits=4, num_shots=1000, max_circuits=4, # number of 'restarts' to perform at same radius radius=0.75, # select single problem radius for multiple execution of same circuit thetas_array=None, # specify a custom thetas_array parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs parameterized=False, # use Parameter objects in circuit, cache transpiled circuits for performance max_iter=30, # maximum minimizer iterations to perform minimizer_tolerance=0.001, # tolerance passed to the minimizer comfort=True, # show 'comfort dots' during execution # disable print of results at every iteration show_results_summary=False, # display options for bar plots (exec time, accuracy ratio) bar_y_metrics=["average_exec_times", "accuracy_ratio_error"], bar_x_metrics=["num_qubits"], use_logscale_for_times=True, # use log scale for cumulative exec time bar chart show_elapsed_times=True, # include elapsed time in average_exec_times plot # disable options for line plots and area plots line_y_metrics=None, score_metric=None, ) # Run the benchmark in method 2 hydrogen_lattice_benchmark.run(method=2, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. """Randomized tests of quantum synthesis.""" import unittest from test.python.quantum_info.test_synthesis import CheckDecompositions from hypothesis import given, strategies, settings import numpy as np from qiskit import execute from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.extensions import UnitaryGate from qiskit.providers.basicaer import UnitarySimulatorPy from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.synthesis.two_qubit_decompose import ( two_qubit_cnot_decompose, TwoQubitBasisDecomposer, Ud, ) class TestSynthesis(CheckDecompositions): """Test synthesis""" seed = strategies.integers(min_value=0, max_value=2**32 - 1) rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10) @given(seed) def test_1q_random(self, seed): """Checks one qubit decompositions""" unitary = random_unitary(2, seed=seed) self.check_one_qubit_euler_angles(unitary) self.check_one_qubit_euler_angles(unitary, "U3") self.check_one_qubit_euler_angles(unitary, "U1X") self.check_one_qubit_euler_angles(unitary, "PSX") self.check_one_qubit_euler_angles(unitary, "ZSX") self.check_one_qubit_euler_angles(unitary, "ZYZ") self.check_one_qubit_euler_angles(unitary, "ZXZ") self.check_one_qubit_euler_angles(unitary, "XYX") self.check_one_qubit_euler_angles(unitary, "RR") @settings(deadline=None) @given(seed) def test_2q_random(self, seed): """Checks two qubit decompositions""" unitary = random_unitary(4, seed=seed) self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose) @given(strategies.tuples(*[seed] * 5)) def test_exact_supercontrolled_decompose_random(self, seeds): """Exact decomposition for random supercontrolled basis and random target""" k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data) k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data) basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2 decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary)) self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer) @given(strategies.tuples(*[rotation] * 6), seed) def test_cx_equivalence_0cx_random(self, rnd, seed): """Check random circuits with 0 cx gates locally equivalent to identity.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0) @given(strategies.tuples(*[rotation] * 12), seed) def test_cx_equivalence_1cx_random(self, rnd, seed): """Check random circuits with 1 cx gates locally equivalent to a cx.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1) @given(strategies.tuples(*[rotation] * 18), seed) def test_cx_equivalence_2cx_random(self, rnd, seed): """Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) qc.cx(qr[0], qr[1]) qc.u(rnd[12], rnd[13], rnd[14], qr[0]) qc.u(rnd[15], rnd[16], rnd[17], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2) @given(strategies.tuples(*[rotation] * 24), seed) def test_cx_equivalence_3cx_random(self, rnd, seed): """Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) qc.cx(qr[0], qr[1]) qc.u(rnd[12], rnd[13], rnd[14], qr[0]) qc.u(rnd[15], rnd[16], rnd[17], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[18], rnd[19], rnd[20], qr[0]) qc.u(rnd[21], rnd[22], rnd[23], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3) if __name__ == "__main__": unittest.main()
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
AlphaMiyaL
my_list = [1,3,5,2,4,2,5,8,0,7,6] #classical computation method def oracle(my_input): winner =7 if my_input is winner: response = True else: response = False return response for index, trial_number in enumerate(my_list): if oracle(trial_number) is True: print("Winner is found at index %i" %index) print("%i calls to the oracle used " %(index +1)) break #quantum implemenation from qiskit import * import matplotlib.pyplot as plt import numpy as np from qiskit.tools import job_monitor # oracle circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) oracle.to_gate() oracle.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit, backend=backend) result= job.result() sv= result.get_statevector() np.around(sv,2) #amplitude amplification reflection = QuantumCircuit(2, name='reflection') reflection.h([0,1]) reflection.z([0,1]) reflection.cz(0,1) reflection.h([0,1]) reflection.to_gate() reflection.draw(output='mpl') #testing circuit on simulator simulator = Aer.get_backend('qasm_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.append(reflection, [0,1]) grover_circuit.barrier() grover_circuit.measure([0,1],[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit,backend=simulator,shots=1) result=job.result() result.get_counts() #testing on real backend system IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp= provider.get_backend('ibmq_manila') job = execute(grover_circuit,backend=qcomp) job_monitor(job) result=job.result() counts=result.get_counts(grover_circuit) from qiskit.visualization import plot_histogram plot_histogram(counts) counts['11']
https://github.com/ayushidubal/qram
ayushidubal
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library import ZGate from qiskit.quantum_info import Operator, Statevector from qiskit.extensions import Initialize from qiskit.providers.aer import AerSimulator from qiskit.providers.aer.backends import statevector_simulator, qasm_simulator from qiskit.visualization import plot_histogram, plot_state_city from qiskit import Aer, execute, transpile import numpy as np def targets(n): state1 = "" state2 = "" bits = ["0", "1"] for i in range(n): state1 += bits[i%2] state2 += bits[1-(i%2)] return state1, state2 def getData(input_array, mem_bits): state = "" for i in input_array: state += bin(i)[2:].rjust(mem_bits, '0') return state[::-1] def decoder(addr_bits, aux_bits, n): addr = QuantumRegister(addr_bits) tau = QuantumRegister(aux_bits) decoder = QuantumCircuit(addr, tau) decoder.x(tau[0]) decoder.cx(addr[addr_bits-1], tau[1]) decoder.cx(tau[1], tau[0]) c = 1 for i in range(1, addr_bits-1): p = 2**i for j in range(p): decoder.ccx(addr[addr_bits-i-1], tau[j], tau[p+j]) c += 1 for j in range(p): decoder.cx(tau[p+j], tau[j]) p = aux_bits - 1 - c for j in range(p): decoder.ccx(addr[0], tau[j], tau[p+j]) c += 1 for j in range(p): decoder.cx(tau[p+j], tau[j]) return decoder.to_gate(label = "Decoder") def groverOracle(aux_bits, mem_bits, n): winners = targets(mem_bits) tau = QuantumRegister(aux_bits) mem = QuantumRegister(mem_bits*n) oracle = QuantumCircuit(tau, mem) gate1 = ZGate().control(num_ctrl_qubits=mem_bits, ctrl_state=winners[0]) gate2 = ZGate().control(num_ctrl_qubits=mem_bits, ctrl_state=winners[1]) for i in range(aux_bits): qubits = [mem[mem_bits*i + j] for j in range(mem_bits)] oracle.append(gate1, qubits + [tau[i]]) oracle.append(gate2, qubits + [tau[i]]) return oracle.to_gate(label="Oracle") def groverDiffuser(addr_bits): d = 2**addr_bits s = np.array([[1.0/np.sqrt(d)] for i in range(d)]) op = np.matmul(s, s.T) U_S = Operator((2*op)-np.identity(d)) return U_S def qram(input_array): n = len(input_array) if n < 8: input_array += [0 for i in range(8-n)] n = len(input_array) addr_bits = len(bin(n-1)) - 2 # number of address bits aux_bits = n # number of memory locations mem_bits = len(bin(max(input_array))) - 2 # size of one memory location addr = QuantumRegister(addr_bits, name="a") # address register tau = QuantumRegister(aux_bits, name="tau") # auxillary register to store selected address mem = QuantumRegister(mem_bits*n, name="m") # memory register cr = ClassicalRegister(addr_bits) # to store final output qram_circ = QuantumCircuit(addr, tau, mem, cr) for i in range(addr_bits): qram_circ.h(addr[i]) # Load data into qRAM data = getData(input_array[::-1], mem_bits) for i in range(len(data)): if data[i] == "1": qram_circ.x(mem[i]) # End of loading # Entangle tau with addr decode = decoder(addr_bits, aux_bits, n) qram_circ.append(decode, addr[:] + tau[:]) # Grover oracle oracle = groverOracle(aux_bits, mem_bits, n) qram_circ.append(oracle, tau[:] + mem[:]) # End of grover oracle # Detangle tau from addr encode = decode.inverse() encode.label = "Encoder" qram_circ.append(encode, addr[:] + tau[:]) # Diffuser U_S = groverDiffuser(addr_bits) qram_circ.append(U_S, [addr[i] for i in range(addr_bits)]) # Measure qram_circ.measure([addr[i] for i in range(addr_bits)], [cr[i] for i in range(addr_bits)]) return qram_circ circ = qram([3, 2, 0, 1]) circ.draw('mpl') backend = Aer.get_backend("qasm_simulator") job = execute(circ, backend) res = job.result() counts = res.get_counts() print(counts) plot_histogram(counts) circ = qram([1, 0, 3, 2, 3]) circ.draw('mpl') backend = Aer.get_backend("qasm_simulator") job = execute(circ, backend) res = job.result() counts = res.get_counts() print(counts) plot_histogram(counts) circ = qram([0, 1, 3, 2, 2]) circ.draw('mpl') backend = Aer.get_backend("qasm_simulator") job = execute(circ, backend) res = job.result() counts = res.get_counts() print(counts) plot_histogram(counts)
https://github.com/ichen17/Learning-Qiskit
ichen17
# Importing Packages from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle bb = input("Enter the input string:\n") ### Using in-built "simon_oracle" from QISKIT # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle n = len(bb) simon_circuit = QuantumCircuit(n*2, n) # Apply Hadamard gates before querying the oracle simon_circuit.h(range(n)) # Apply barrier for visual separation simon_circuit.barrier() simon_circuit += simon_oracle(bb) # Apply barrier for visual separation simon_circuit.barrier() # Apply Hadamard gates to the input register simon_circuit.h(range(n)) # Measure qubits simon_circuit.measure(range(n), range(n)) simon_circuit.draw(output="mpl") # use local simulator aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(simon_circuit, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(counts) # Calculate the dot product of the results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) for z in counts: print( '{}.{} = {} (mod 2)'.format(b, z, bdotz(b,z)) ) b = input("Enter a binary string:\n") # Actual b = 011 b_rev = b[::-1] flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() qc.measure(q1,c1) qc.draw("mpl") aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(qc, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(counts) # Actual b = 011 b="1" b_rev = "1" flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() # qc.measure(q1,c1) # qc.draw("mpl") # Simulate the unitary usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import time, os, logging, warnings from qiskit_optimization.algorithms import CplexOptimizer warnings.filterwarnings("ignore", category=DeprecationWarning) from qiskit.optimization.algorithms.optimization_algorithm import OptimizationResultStatus from dwave.system import DWaveCliqueSampler from utilities.helpers import create_dwave_meo, create_quadratic_programs_from_paths TEST_DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") + "/DENSE/" RES_DIR = 'RESULTS' + "/" + time.strftime("%d_%m_%Y") + "/DENSE/" os.makedirs(RES_DIR, exist_ok=True) TEST_DIR # select linear programs to solve qps = create_quadratic_programs_from_paths(TEST_DIR, True) # init Optimizers cplex = CplexOptimizer() dwave = create_dwave_meo(DWaveCliqueSampler(), num_reads=4096) prelabel = "clique_dense_" logger = logging.getLogger() logger.setLevel(logging.INFO) warnings.filterwarnings("ignore", category=DeprecationWarning) count_fail_dwave = 0 for qp_name, qp in qps.items() : print(qp_name) print("number of qubits: ", qp.get_num_vars()) output_file_handler = logging.FileHandler(filename=RES_DIR + qp.name + ".log") logger.addHandler(output_file_handler) # set problem label dwave.min_eigen_solver.sampler.set_label(prelabel + qp_name + "_" + str(qp.get_num_vars())) with open(RES_DIR + qp.name + '.res', 'w') as file: file.write(str("Start " + qp.name + "\n " + str(qp.get_num_vars()) + " qubits needed")) file.write("\n DWave Quantum: \n") logger.info("\n DWave Quantum: \n ") try: res_classic = cplex.solve(qp) res_quantum = dwave.solve(qp) problem_id = str(res_quantum.min_eigen_solver_result.sampleset.info['problem_id']) logger.info("\n problem id " + problem_id) file.write("\n problem id: " + problem_id) if res_quantum.status != OptimizationResultStatus.SUCCESS: print("Dwave quantum solver found no solution.") file.write("\n No solution found with DWave Quantum Solver \n") count_fail_dwave = count_fail_dwave + 1 if count_fail_dwave == 3: file.write("\n Stop testing DWave Quantum Solver \n") break else: print("Dwave Quantum successful!") count_fail_dwave = 0 if res_quantum.fval == res_classic.fval: file.write("\n DWave quantum solver found optimal solution\n") else: print("\n optimal value Dwave quantum "+str(res_quantum.fval) \ + " , cplex:"+ str(res_classic.fval)) file.write("\n DWave quantum solver:\n") file.write(str(res_quantum)) file.write("\n CPLEX:\n") file.write(str(res_classic)) except Exception as ex: print(qp_name, " ", type(ex).__name__, " : ", ex) file.write("\n Cplex or DWave solver produced an exception:\n") file.write(str(ex)) count_fail_dwave = count_fail_dwave + 1 if count_fail_dwave == 3: file.write("\n Stop testing because of Exception! \n") break logger.removeHandler(output_file_handler)
https://github.com/QuantumVic/discrete-time-quantum-walks
QuantumVic
from qiskit import * import numpy as np import matplotlib as mpl from qiskit.tools.visualization import plot_histogram, plot_state_city from qiskit.tools.monitor import job_monitor state_sim = Aer.get_backend('statevector_simulator') qasm_sim = Aer.get_backend('qasm_simulator') unitary_sim = Aer.get_backend('unitary_simulator') qiskit.__qiskit_version__ #developed in q0.14.0, q-terra0.11.0 # Definition of c_Increment, c_Decrement gates def increment(qc,qr): """controlled-increment gate, cf. PhysRevA.72.032329""" for i in range(num_qubits - 1): qc.mct(qr[0:num_qubits - 1 - i], qr[num_qubits - 1 - i] , qr_aux) def decrement(qc,qr): """controlled-decrement gate, cf. PhysRevA.72.032329""" for i in range(num_qubits - 1): qc.mct(qr[0:i+1], qr[i+1], qr_aux) # Definition of QW cycle def quantum_walk(qc,qr): """implement DTQW on a previously defined circuit and register cf. PhysRevA.72.032329""" # coin operator qc.h(qr[0]) # conditional shift increment(qc,qr) qc.x(qr[0]) decrement(qc,qr) qc.x(qr[0]) def get_tot_gates(qc): """get the total number of basic gates of a circuit""" tot_gates = 0 for key in qc.decompose().count_ops(): tot_gates = tot_gates + qc.decompose().count_ops()[key] return tot_gates def get_cx_gates(qc): """get the total number of cx gates of a circuit""" cx_gates = qc.decompose().count_ops()['cx'] return cx_gates # Analysis of gate number x = [] # number of qubits y = [] # number of gates of one QW step for q in range(4,30): # Total number of qubits (nodes + coin) num_qubits = q # Define qRegister and qCircuit qr = QuantumRegister(num_qubits, 'qr') cr = ClassicalRegister(num_qubits - 1, 'cr') # We need (num_control - 2) aux qubits for mct if num_qubits > 3: qr_aux = QuantumRegister(num_qubits - 3, 'aux') qc = QuantumCircuit(qr,qr_aux,cr) else: qr_aux = None qc = QuantumCircuit(qr,cr) # Running the QW quantum_walk(qc,qr) x.append(q) y.append(get_cx_gates(qc)) print(x,y) mpl.pyplot.plot(x,y) mpl.pyplot.xlabel('number of qubits') mpl.pyplot.ylabel('number of gates') mpl.pyplot.title('Number of CX gates required for a QW step') mpl.pyplot.grid(True) mpl.pyplot.show()
https://github.com/drnickallgood/simonqiskit
drnickallgood
import sys import logging import matplotlib.pyplot as plt import numpy as np import operator import itertools #from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, IBMQ from qiskit.providers.ibmq import least_busy from collections import OrderedDict # AER is for simulators from qiskit import Aer from qiskit import QuantumCircuit from qiskit import ClassicalRegister from qiskit import QuantumRegister from qiskit import execute from qiskit import IBMQ #from qiskit.providers.ibmq.managed import IBMQJobManager from qiskit.tools.monitor import job_monitor from qiskit.tools.visualization import plot_histogram from qiskit.tools.visualization import circuit_drawer from sympy import Matrix, pprint, MatrixSymbol, expand, mod_inverse from qjob import QJob def blackbox(period_string): #### Blackbox Function ##### # QP's don't care about this, we do# ############################# # Copy first register to second by using CNOT gates for i in range(n): #simonCircuit.cx(qr[i],qr[n+i]) simonCircuit.cx(qr[i],qr[n+i]) # get the small index j such it's "1" j = -1 #reverse the string so that it takes s = period_string[::-1] for i, c in enumerate(s): if c == "1": j = i break # 1-1 and 2-1 mapping with jth qubit # x is control to xor 2nd qubit with a for i, c in enumerate(s): if c == "1" and j >= 0: #simonCircuit.x(qr[j]) simonCircuit.cx(qr[j], qr[n+i]) #the i-th qubit is flipped if s_i is 1 #simonCircuit.x(qr[j]) # Random peemutation # This part is how we can get by with 1 query of the oracle and better # simulates quantum behavior we'd expect perm = list(np.random.permutation(n)) # init position init = list(range(n)) i = 0 while i < n: if init[i] != perm[i]: k = perm.index(init[i]) simonCircuit.swap(qr[n+i],qr[n+k]) #swap gate on qubits init[i], init[k] = init[k], init[i] # mark the swapped qubits else: i += 1 # Randomly flip qubit # Seed random numbers for predictability / benchmark for i in range(n): if np.random.random() > 0.5: simonCircuit.x(qr[n+i]) simonCircuit.barrier() ### END OF BLACKBOX FUNCTION return simonCircuit def run_circuit(circuit,backend): # Default for this backend seems to be 1024 ibmqx2 shots = 1024 job = execute(simonCircuit,backend=backend, shots=shots) job_monitor(job,interval=2) results = job.result() return results ''' counts = results.get_counts() #print("Getting Results...\n") #print(qcounts) #print("") print("Submitting to IBM Q...\n") print("\nIBM Q Backend %s: Resulting Values and Probabilities" % qbackend) print("===============================================\n") print("Simulated Runs:",shots,"\n") # period, counts, prob,a0,a1,...,an # for key, val in qcounts.items(): prob = val / shots print("Period:", key, ", Counts:", val, ", Probability:", prob) print("") ''' def guass_elim(results): # Classical post processing via Guassian elimination for the linear equations # Y a = 0 # k[::-1], we reverse the order of the bitstring equations = list() lAnswer = [ (k[::-1],v) for k,v in results.get_counts().items() if k != "0"*n ] # Sort basis by probabilities lAnswer.sort(key = lambda x: x[1], reverse=True) Y = [] for k, v in lAnswer: Y.append( [ int(c) for c in k ] ) Y = Matrix(Y) Y_transformed = Y.rref(iszerofunc=lambda x: x % 2==0) # convert rational and negatives in rref def mod(x,modulus): numer,denom = x.as_numer_denom() return numer*mod_inverse(denom,modulus) % modulus # Deal with negative and fractial values Y_new = Y_transformed[0].applyfunc(lambda x: mod(x,2)) #print("\nThe hidden period a0, ... a%d only satisfies these equations:" %(n-1)) #print("===============================================================\n") rows,cols = Y_new.shape for r in range(rows): Yr = [ "a"+str(i)+"" for i,v in enumerate(list(Y_new[r,:])) if v==1] if len(Yr) > 0: tStr = " xor ".join(Yr) #single value is 0, only xor with perid string 0 to get if len(tStr) == 2: equations.append("period xor" + " 0 " + " = 0") else: equations.append("period" + " xor " + tStr + " = 0") return equations def print_list(results): # Sort list by value sorted_x = sorted(qcounts.items(), key=operator.itemgetter(1), reverse=True) print("Sorted list of result strings by counts") print("======================================\n") for i in sorted_x: print(i) #print(sorted_x) print("") ## easily create period strings ## We want to avoid using anything with all 0's as that gives us false results ## because anything mod2 00 will give results def create_period_str(strlen): str_list = list() for i in itertools.product([0,1],repeat=strlen): if "1" in ("".join(map(str,i))): #print("".join(map(str,i))) str_list.append("".join(map(str,i))) return str_list ## function to get dot product of result string with the period string to verify, result should be 0 #check the wikipedia for simons formula # DOT PRODUCT IS MOD 2 !!!! # Result XOR ?? = 0 -- this is what we're looking for! # We have to verify the period string with the ouptput using mod_2 addition aka XOR # Simply xor the period string with the output string # Simply xor the period string with the output string, result must be 0 or 0b0 def verify_string(ostr, pstr): """ Verify string with period string Does dot product and then mod2 addition """ temp_list = list() # loop through outstring, make into numpy array for o in ostr: temp_list.append(int(o)) ostr_arr = np.asarray(temp_list) temp_list.clear() # loop through period string, make into numpy array for p in pstr: temp_list.append(int(p)) pstr_arr = np.asarray(temp_list) temp_list.clear() # Per Simosn, we do the dot product of the np arrays and then do mod 2 results = np.dot(ostr_arr, pstr_arr) if results % 2 == 0: return True return False #### START #### # hidden stringsn period_strings_5qubit = list() period_strings_5qubit = create_period_str(2) period_strings_2bit = list() period_strings_3bit = list() period_strings_4bit = list() period_strings_5bit = list() period_strings_6bit = list() period_strings_7bit = list() # 2-bit strings period_strings_2bit = create_period_str(2) # 3-bit strings period_strings_3bit = create_period_str(3) # 4-bit strings period_strings_4bit = create_period_str(4) # 5-bit strings period_strings_5bit = create_period_str(5) # 6-bit strings period_strings_6bit = create_period_str(6) # 7-bit strings period_strings_7bit = create_period_str(7) # IBM Q stuff.. IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') # 14 qubit (broken?) melbourne = provider.get_backend('ibmq_16_melbourne') #5 qubit backends ibmqx2 = provider.get_backend('ibmqx2') # Yorktown london = provider.get_backend('ibmq_london') essex = provider.get_backend('ibmq_essex') burlington = provider.get_backend('ibmq_burlington') ourense = provider.get_backend('ibmq_ourense') vigo = provider.get_backend('ibmq_vigo') least = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator and x.status().operational==True)) # Setup logging # Will fail if file exists already -- because I'm lazy ''' logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', filename='results-2-7bit/' + melbourne.name() + '-2bit-12iter.txt', filemode='x') console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) ''' #Nam comes back as ibmq_backend, get the part after ibmq #least_name = least.name().split('_')[1] #print("Least busy backend: " + least_name) # 32 qubit qasm simulator - IBMQ ibmq_sim = provider.get_backend('ibmq_qasm_simulator') # Local Simulator, local_sim = Aer.get_backend('qasm_simulator') circuitList = list() backend_list = dict() #backend_list['local_sim'] = local_sim backend_list['ibmqx2'] = ibmqx2 backend_list['london'] = london backend_list['essex'] = essex backend_list['burlington'] = burlington backend_list['ourense'] = ourense backend_list['melbourne'] = melbourne backend_list['vigo'] = vigo #backend14q_list['melbourne'] = melbourne ## DO NOT USE ITERATION FORMULA JUST HERE FOR REF # Iterations = # of backends tested # iteration formula = floor(log2(num_backends * num_shots)) = 14 here # 2-bit period strings ranJobs = list() backname = "local_sim" #2bit = 12 = 36 random functions , min = 35 #3bit = 54 = 37+ random functions, min = 372 #4bit = 26 = 390, min = 384 #5bit = 13 = 403, min = 385 #6bit = 7 = 441, min = 385 #7bit = 4 = 508, min = 385 iterations = 12 #o Jobs total = # of strings * iterations total_jobs = iterations * len(period_strings_2bit) job_start_idx = 1 circs = list() dup_count = 0 # Idea here is we have are feeding hidden bitstrings and getting back results from the QC # Create circuits for period in period_strings_2bit: #print(str(period)) n = len(period) # Seed random number print("=== Creating Circuit ===") #logging.info("=== Creating Circuit: " + str(period) + " ===") # This allows us to get consistent random functions generated for f(x) np.random.seed(2) ## returns 0 duplicates for 2bit stings, 36 iterations #np.random.seed(384) ## returns 21 duplicates for 3bit stings, 54 iterations #np.random.seed(227) for k in range(iterations): # Generate circuit qr = QuantumRegister(2*n) cr = ClassicalRegister(n) simonCircuit = QuantumCircuit(qr,cr) # Hadamards prior to oracle for i in range(n): simonCircuit.h(qr[i]) simonCircuit.barrier() # Oracle query simonCircuit = blackbox(period) # Apply hadamards again for i in range(n): simonCircuit.h(qr[i]) simonCircuit.barrier() # Measure qubits, maybe change to just first qubit to measure simonCircuit.measure(qr[0:n],cr) circs.append(simonCircuit) #### end iterations loop for debugging # Check for duplicates # We compare count_ops() to get the actual operations and order they're in # count_ops returns OrderedDict k = 0 while k < len(circs)-1: if circs[k].count_ops() == circs[k+1].count_ops(): #print("\n=== Duplicates Found! ===") #print("Index:" + str(k)) #print("Index:" + str(k+1)) dup_count = dup_count + 1 #print(circs[k].count_ops()) #print(circs[k+1].count_ops()) #print("=== End Duplcates ===") k = k+2 else: k = k+1 print("Total Circuits:" + str(len(circs))) #logging.info("Total Circuits:" + str(len(circs))) print("Total Duplicates:" + str(dup_count)) #logging.info("Total Duplicates:" + str(dup_count)) for circ in circs: print(circ) exit(1) # Run Circuits logging.info("\n=== Sending data to IBMQ Backend:" + melbourne.name() + " ===\n") for circ in circs: #print("Job: " + str(job_start_idx) + "/" + str(total_jobs)) logging.info("Job: " + str(job_start_idx) + "/" + str(total_jobs)) job = execute(circ,backend=melbourne, shots=1024) #job = execute(circ,backend=local_sim, shots=1024) job_start_idx += 1 job_monitor(job,interval=3) # Store result, including period string qj = QJob(job,circ,melbourne.name(), period) ranJobs.append(qj) # Go through and get correct vs incorrect in jobs for qjob in ranJobs: results = qjob.job.result() counts = results.get_counts() equations = guass_elim(results) # Get period string pstr = qjob.getPeriod() obsv_strs = list() str_cnt = 0 sorted_str = sorted(results.get_counts().items(), key=operator.itemgetter(1), reverse=True) #print("==== RAW RESULTS ====") #logging.info("==== RAW RESULTS ====") #logging.info("Period String:" + qjob.getPeriod()) #logging.info(counts) # Get just the observed strings for string in sorted_str: obsv_strs.append(string[0]) # go through and verify strings for o in obsv_strs: # Remember to re-reverse string so it's back to normal due to IBMQ Endianness if verify_string(o,pstr): # Goes through strings and counts for string, count in counts.items(): if string == o: #print("===== SET CORRECT =====") #print("Correct String: " + string) #logging.info("Correct String: " + string) #print("Correct String Counts: " + str(count)) qjob.setCorrect(count) else: # lookup counts based on string # counts is a dict() for string, count in counts.items(): if string == o: # Add value to incorrect holder in object #print("===== SET INCORRECT =====") #print("Incorrect String: " + string) #logging.info("Incorrect String: " + string) #print("Incorrect String Counts: " + str(count)) qjob.setIncorrect(count) total_correct = 0 total_incorrect = 0 total_runs = (1024 * iterations) * len(period_strings_2bit) for qjob in ranJobs: total_correct += qjob.getCorrect() total_incorrect += qjob.getIncorrect() logging.info("\n\nTotal Runs: " + str(total_runs)) logging.info("Total Correct: " + str(total_correct)) logging.info("Prob Correct: " + str(float(total_correct) / float(total_runs))) logging.info("Total Incorrect: " + str(total_incorrect)) logging.info("Prob Incorrect: " + str(float(total_incorrect) / float(total_runs))) logging.info("Total Duplicates:" + str(dup_count)) exit(1) # Least busy backend, for individual testing #backend_list[least_name] = least # Make Circuits for all period strings! #for p in period_strings_5qubit: for p in period_strings_14qubit: # Circuit name = Simon_+ period string #circuitName = "Simon-" + p circuitName = p n = len(p) # For simons, we use the first n registers for control qubits # We use the last n registers for data qubits.. which is why we need 2*n qr = QuantumRegister(2*n) cr = ClassicalRegister(n) simonCircuit = QuantumCircuit(qr,cr,name=circuitName) # Apply hadamards prior to oracle for i in range(n): simonCircuit.h(qr[i]) simonCircuit.barrier() #call oracle for period string simonCircuit = blackbox(p) # Apply hadamards after blackbox for i in range(n): simonCircuit.h(qr[i]) simonCircuit.barrier() # Measure qubits, maybe change to just first qubit to measure simonCircuit.measure(qr[0:n],cr) circuitList.append(simonCircuit) # Run loop to send circuits to IBMQ.. local_sim_ranJobs = list() ibmqx2_ranJobs = list() london_ranJobs = list() essex_ranJobs = list() burlington_ranJobs = list() ourense_ranJobs = list() vigo_ranJobs = list() ibmq_sim_ranJobs = list() melbourne_ranJobs = list() print("\n===== SENDING DATA TO IBMQ BACKENDS... =====\n") ranJobs = list() jcount = 1 jtotal = 500 for name in backend_list: for circuit in circuitList: job = execute(circuit,backend=backend_list[name], shots=1024) # Keep tabs on running jobs print("Running job on backend: " + name) print("Running job: " + str(jcount) + "/" + str(jtotal)) jcount += 1 job_monitor(job,interval=5) # Custom object to hold the job, circuit, and backend qj = QJob(job,circuit,name) #print(qj.backend()) # Append finished / ran job to list of jobs ranJobs.append(qj) for qjob in ranJobs: # Results from each job results = qjob.job.result() # total counts from job counts = results.get_counts() # equations from each job equations = guass_elim(results) #period string encoded into name pstr = qjob.circuit.name #list of observed strings obs_strings = list() str_counts = 0 # Sorted strings from each job sorted_str = sorted(results.get_counts().items(), key=operator.itemgetter(1), reverse=True) # Get just the observed strings for string in sorted_str: obs_strings.append(string[0]) # go through and verify strings for o in obs_strings: # Remember to re-reverse string so it's back to normal due to IBMQ Endianness if verify_string(o,pstr): for string, count in counts.items(): if string == o: #print("===== SET CORRECT =====") qjob.setCorrect(count) else: # lookup counts based on string # counts is a dict() for string, count in counts.items(): if string == o: # Add value to incorrect holder in object #print("===== SET INCORRECT =====") qjob.setIncorrect(count) # Now we haev the stats finished, let's store them in a list based on their backend name if qjob.backend() == "ibmqx2": ibmqx2_ranJobs.append(qjob) elif qjob.backend() == "london": london_ranJobs.append(qjob) elif qjob.backend() == "burlington": burlington_ranJobs.append(qjob) elif qjob.backend() == "essex": essex_ranJobs.append(qjob) elif qjob.backend() == "ourense": ourense_ranJobs.append(qjob) elif qjob.backend() == "vigo": vigo_ranJobs.append(qjob) elif qjob.backend() == "ibmq_sim": ibmq_sim_ranJobs.append(qjob) elif qjob.backend() == "melbourne": melbourne_ranJobs.append(qjob) elif qjob.backend() == "local_sim": local_sim_ranJobs.append(qjob) else: continue backends_5qubit_ranJobs = dict() backends_14qubit_ranJobs = dict() backends_sims_ranJobs = dict() #q5b = ["ibmqx2", "vigo", "ourense", "london", "essex", "burlington"] #q5b = ["ibmqx2"] #q5b = ["vigo"] #q5b = ["ourense"] #q5b = ["london"] q5b = ["essex"] #q5b = ["burlington"] q14b = ["melbourne"] sims = ["local_sim"] #sims = ["local_sim", "ibmq_sim"] backends_5qubit_ranJobs['ibmqx2'] = ibmqx2_ranJobs backends_5qubit_ranJobs['vigo'] = vigo_ranJobs backends_5qubit_ranJobs['ourense'] = ourense_ranJobs backends_5qubit_ranJobs['london'] = london_ranJobs backends_5qubit_ranJobs['essex'] = essex_ranJobs backends_5qubit_ranJobs['burlington'] = burlington_ranJobs backends_14qubit_ranJobs['melbourne'] = melbourne_ranJobs backends_sims_ranJobs['local_sim'] = local_sim_ranJobs #backends_sims['ibmq_sim'] = ibmq_sim_ranJobs # The idea here is to loop through the dictionary by using a name in the list of names above # as such then, we can call dictionaries in a loop with that name, which contain the list of # ran jobs def printStats(backend, job_list): ''' backend: backend name job_list: list of ran jobs from backend ''' total_correct = 0 total_incorrect = 0 # Total = shots = repeitions of circuit # 1024 x 4 period strings we can use with 2-qubit = 4096 # Probably make this dynamic for 14-qubit # 2 - 7 qubits = 142336 total runs total = 142336 pcorrect = 0.00 pincorrect = 0.00 # Go through each job/period string's data for job in job_list: total_correct += job.getCorrect() #print("Total Correct inc: " + str(total_correct)) total_incorrect += job.getIncorrect() #print("Total INCorrect inc: " + str(total_incorrect)) # This is to handle when we use a simiulator, nothing should be incorrect to avoid dividing by 0 if total_incorrect == 0: pincorrect = 0.00 else: pincorrect = 100*(total_incorrect / total) pcorrect = 100*(total_correct / total) print("\n===== RESULTS - " + backend + " =====\n") print("Total Results: " + str(total)) print("Total Correct Results: " + str(total_correct) + " -- " + str(pcorrect) + "%") print("Total Inorrect Results: " + str(total_incorrect) + " -- " + str(pincorrect) + "%") print("\n===================\n") ''' for backend in sims: printStats(backend, backends_sims_ranJobs[backend]) ''' #printStats(least_name, backends_5qubit_ranJobs[least_name]) # for each backend name in the backend name list... ''' for backend in q5b: printStats(backend, backends_5qubit_ranJobs[backend]) ''' # 14-qubit backend for backend in q14b: printStats(backend, backends_14qubit_ranJobs[backend])
https://github.com/JoelJJoseph/QUANTUM-TRADE
JoelJJoseph
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/esloho/Qrangen
esloho
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Module defining QiskitBackend Class """ from typing import TYPE_CHECKING, Optional, Union from qiskit_ibm_runtime import QiskitRuntimeService from qbraid.programs import load_program from qbraid.runtime.device import QuantumDevice from qbraid.runtime.enums import DeviceStatus, DeviceType from .job import QiskitJob if TYPE_CHECKING: import qiskit import qiskit_ibm_runtime import qbraid.runtime.qiskit class QiskitBackend(QuantumDevice): """Wrapper class for IBM Qiskit ``Backend`` objects.""" def __init__( self, profile: "qbraid.runtime.TargetProfile", service: "Optional[qiskit_ibm_runtime.QiskitRuntimeService]" = None, ): """Create a QiskitBackend.""" super().__init__(profile=profile) self._service = service or QiskitRuntimeService() self._backend = self._service.backend(self.id, instance=self.profile.get("instance")) def __str__(self): """Official string representation of QuantumDevice object.""" return f"{self.__class__.__name__}('{self.id}')" def status(self): """Return the status of this Device. Returns: str: The status of this Device """ if self.device_type == DeviceType.LOCAL_SIMULATOR: return DeviceStatus.ONLINE status = self._backend.status() if status.operational: if status.status_msg == "active": return DeviceStatus.ONLINE return DeviceStatus.UNAVAILABLE return DeviceStatus.OFFLINE def queue_depth(self) -> int: """Return the number of jobs in the queue for the ibm backend""" if self.device_type == DeviceType.LOCAL_SIMULATOR: return 0 return self._backend.status().pending_jobs def transform(self, run_input: "qiskit.QuantumCircuit") -> "qiskit.QuantumCircuit": """Transpile a circuit for the device.""" program = load_program(run_input) program.transform(self) return program.program def submit( self, run_input: "Union[qiskit.QuantumCircuit, list[qiskit.QuantumCircuit]]", *args, **kwargs, ) -> "qbraid.runtime.qiskit.QiskitJob": """Runs circuit(s) on qiskit backend via :meth:`~qiskit.execute` Uses the :meth:`~qiskit.execute` method to create a :class:`~qiskit.providers.QuantumJob` object, applies a :class:`~qbraid.runtime.qiskit.QiskitJob`, and return the result. Args: run_input: A circuit object to run on the IBM device. Keyword Args: shots (int): The number of times to run the task on the device. Default is 1024. Returns: qbraid.runtime.qiskit.QiskitJob: The job like object for the run. """ backend = self._backend shots = kwargs.pop("shots", backend.options.get("shots")) memory = kwargs.pop("memory", True) # Needed to get measurements job = backend.run(run_input, *args, shots=shots, memory=memory, **kwargs) return QiskitJob(job.job_id(), job=job, device=self)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # 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. # TODO: Remove after 0.7 and the deprecated methods are removed # pylint: disable=unused-argument """ Two quantum circuit drawers based on: 0. Ascii art 1. LaTeX 2. Matplotlib """ import errno import logging import os import subprocess import tempfile from PIL import Image from qiskit import user_config from qiskit.visualization import exceptions from qiskit.visualization import latex as _latex from qiskit.visualization import text as _text from qiskit.visualization import utils from qiskit.visualization import matplotlib as _matplotlib logger = logging.getLogger(__name__) def circuit_drawer(circuit, scale=0.7, filename=None, style=None, output=None, interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit to different formats (set by output parameter): 0. text: ASCII art TextDrawing that can be printed in the console. 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Args: circuit (QuantumCircuit): the quantum circuit to draw scale (float): scale of image to draw (shrink if < 1) filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file. This option is only used by the `mpl`, `latex`, and `latex_source` output types. If a str is passed in that is the path to a json file which contains that will be open, parsed, and then used just as the input dict. output (str): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. By default the 'text' drawer is used unless a user config file has an alternative backend set as the default. If the output is passed in that backend will always be used. interactive (bool): when set true show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. line_length (int): Sets the length of the lines generated by `text` output type. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). However, if you're running in jupyter the default line length is set to 80 characters. If you don't want pagination at all, set `line_length=-1`. reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): Options are `left`, `right` or `none`, if anything else is supplied it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. Currently only supported by text drawer. Returns: PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. String: (output `latex_source`). The LaTeX source code. TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requieres non-installed libraries. .. _style-dict-doc: The style dict kwarg contains numerous options that define the style of the output circuit visualization. While the style dict is used by the `mpl`, `latex`, and `latex_source` outputs some options in that are only used by the `mpl` output. These options are defined below, if it is only used by the `mpl` output it is marked as such: textcolor (str): The color code to use for text. Defaults to `'#000000'` (`mpl` only) subtextcolor (str): The color code to use for subtext. Defaults to `'#000000'` (`mpl` only) linecolor (str): The color code to use for lines. Defaults to `'#000000'` (`mpl` only) creglinecolor (str): The color code to use for classical register lines `'#778899'`(`mpl` only) gatetextcolor (str): The color code to use for gate text `'#000000'` (`mpl` only) gatefacecolor (str): The color code to use for gates. Defaults to `'#ffffff'` (`mpl` only) barrierfacecolor (str): The color code to use for barriers. Defaults to `'#bdbdbd'` (`mpl` only) backgroundcolor (str): The color code to use for the background. Defaults to `'#ffffff'` (`mpl` only) fontsize (int): The font size to use for text. Defaults to 13 (`mpl` only) subfontsize (int): The font size to use for subtext. Defaults to 8 (`mpl` only) displaytext (dict): A dictionary of the text to use for each element type in the output visualization. The default values are: { 'id': 'id', 'u0': 'U_0', 'u1': 'U_1', 'u2': 'U_2', 'u3': 'U_3', 'x': 'X', 'y': 'Y', 'z': 'Z', 'h': 'H', 's': 'S', 'sdg': 'S^\\dagger', 't': 'T', 'tdg': 'T^\\dagger', 'rx': 'R_x', 'ry': 'R_y', 'rz': 'R_z', 'reset': '\\left|0\\right\\rangle' } You must specify all the necessary values if using this. There is no provision for passing an incomplete dict in. (`mpl` only) displaycolor (dict): The color codes to use for each circuit element. By default all values default to the value of `gatefacecolor` and the keys are the same as `displaytext`. Also, just like `displaytext` there is no provision for an incomplete dict passed in. (`mpl` only) latexdrawerstyle (bool): When set to True enable latex mode which will draw gates like the `latex` output modes. (`mpl` only) usepiformat (bool): When set to True use radians for output (`mpl` only) fold (int): The number of circuit elements to fold the circuit at. Defaults to 20 (`mpl` only) cregbundle (bool): If set True bundle classical registers (`mpl` only) showindex (bool): If set True draw an index. (`mpl` only) compress (bool): If set True draw a compressed circuit (`mpl` only) figwidth (int): The maximum width (in inches) for the output figure. (`mpl` only) dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl` only) margin (list): `mpl` only creglinestyle (str): The style of line to use for classical registers. Choices are `'solid'`, `'doublet'`, or any valid matplotlib `linestyle` kwarg value. Defaults to `doublet`(`mpl` only) """ image = None config = user_config.get_config() # Get default from config file else use text default_output = 'text' if config: default_output = config.get('circuit_drawer', 'text') if output is None: output = default_output if output == 'text': return _text_circuit_drawer(circuit, filename=filename, line_length=line_length, reverse_bits=reverse_bits, plotbarriers=plot_barriers, justify=justify) elif output == 'latex': image = _latex_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'latex_source': return _generate_latex_source(circuit, filename=filename, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'mpl': image = _matplotlib_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) else: raise exceptions.VisualizationError( 'Invalid output type %s selected. The only valid choices ' 'are latex, latex_source, text, and mpl' % output) if image and interactive: image.show() return image # ----------------------------------------------------------------------------- # Plot style sheet option # ----------------------------------------------------------------------------- def qx_color_scheme(): """Return default style for matplotlib_circuit_drawer (IBM QX style).""" return { "comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)", "textcolor": "#000000", "gatetextcolor": "#000000", "subtextcolor": "#000000", "linecolor": "#000000", "creglinecolor": "#b9b9b9", "gatefacecolor": "#ffffff", "barrierfacecolor": "#bdbdbd", "backgroundcolor": "#ffffff", "fold": 20, "fontsize": 13, "subfontsize": 8, "figwidth": -1, "dpi": 150, "displaytext": { "id": "id", "u0": "U_0", "u1": "U_1", "u2": "U_2", "u3": "U_3", "x": "X", "y": "Y", "z": "Z", "h": "H", "s": "S", "sdg": "S^\\dagger", "t": "T", "tdg": "T^\\dagger", "rx": "R_x", "ry": "R_y", "rz": "R_z", "reset": "\\left|0\\right\\rangle" }, "displaycolor": { "id": "#ffca64", "u0": "#f69458", "u1": "#f69458", "u2": "#f69458", "u3": "#f69458", "x": "#a6ce38", "y": "#a6ce38", "z": "#a6ce38", "h": "#00bff2", "s": "#00bff2", "sdg": "#00bff2", "t": "#ff6666", "tdg": "#ff6666", "rx": "#ffca64", "ry": "#ffca64", "rz": "#ffca64", "reset": "#d7ddda", "target": "#00bff2", "meas": "#f070aa" }, "latexdrawerstyle": True, "usepiformat": False, "cregbundle": False, "plotbarrier": False, "showindex": False, "compress": True, "margin": [2.0, 0.0, 0.0, 0.3], "creglinestyle": "solid", "reversebits": False } # ----------------------------------------------------------------------------- # _text_circuit_drawer # ----------------------------------------------------------------------------- def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False, plotbarriers=True, justify=None, vertically_compressed=True): """ Draws a circuit using ascii art. Args: circuit (QuantumCircuit): Input circuit filename (str): optional filename to write the result line_length (int): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). If you don't want pagination at all, set line_length=-1. reverse_bits (bool): Rearrange the bits in reverse order. plotbarriers (bool): Draws the barriers when they are there. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. vertically_compressed (bool): Default is `True`. It merges the lines so the drawing will take less vertical room. Returns: TextDrawing: An instances that, when printed, draws the circuit in ascii art. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) text_drawing = _text.TextDrawing(qregs, cregs, ops) text_drawing.plotbarriers = plotbarriers text_drawing.line_length = line_length text_drawing.vertically_compressed = vertically_compressed if filename: text_drawing.dump(filename) return text_drawing # ----------------------------------------------------------------------------- # latex_circuit_drawer # ----------------------------------------------------------------------------- def _latex_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on latex (Qcircuit package) Requires version >=2.6.0 of the qcircuit LaTeX package. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: PIL.Image: an in-memory representation of the circuit diagram Raises: OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is missing. CalledProcessError: usually points errors during diagram creation. """ tmpfilename = 'circuit' with tempfile.TemporaryDirectory() as tmpdirname: tmppath = os.path.join(tmpdirname, tmpfilename + '.tex') _generate_latex_source(circuit, filename=tmppath, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) image = None try: subprocess.run(["pdflatex", "-halt-on-error", "-output-directory={}".format(tmpdirname), "{}".format(tmpfilename + '.tex')], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True) except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to compile latex. ' 'Is `pdflatex` installed? ' 'Skipping latex circuit drawing...') raise except subprocess.CalledProcessError as ex: with open('latex_error.log', 'wb') as error_file: error_file.write(ex.stdout) logger.warning('WARNING Unable to compile latex. ' 'The output from the pdflatex command can ' 'be found in latex_error.log') raise else: try: base = os.path.join(tmpdirname, tmpfilename) subprocess.run(["pdftocairo", "-singlefile", "-png", "-q", base + '.pdf', base]) image = Image.open(base + '.png') image = utils._trim(image) os.remove(base + '.png') if filename: image.save(filename, 'PNG') except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to convert pdf to image. ' 'Is `poppler` installed? ' 'Skipping circuit drawing...') raise return image def _generate_latex_source(circuit, filename=None, scale=0.7, style=None, reverse_bits=False, plot_barriers=True, justify=None): """Convert QuantumCircuit to LaTeX string. Args: circuit (QuantumCircuit): input circuit scale (float): image scaling filename (str): optional filename to write latex style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: str: Latex string appropriate for writing to file. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) latex = qcimg.latex() if filename: with open(filename, 'w') as latex_file: latex_file.write(latex) return latex # ----------------------------------------------------------------------------- # matplotlib_circuit_drawer # ----------------------------------------------------------------------------- def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on matplotlib. If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline. We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: matplotlib.figure: a matplotlib figure object for the circuit diagram """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) return qcd.draw(filename)
https://github.com/RyosukeNORO/Shor-s-algorithm
RyosukeNORO
from qiskit import * import numpy as np import math from qiskit.tools.visualization import plot_histogram %matplotlib inline N = 15 a = 13 math.gcd(a, N) if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") n = 4 # number of qubits needed to represent number that will be done prime factorization qr = QuantumRegister(2*n) # Prepare 2*n quantum registers as |x>|w> = |x3 x2 x1 x0>|w3 w2 w1 w0> cr = ClassicalRegister(2*n) qc = QuantumCircuit(qr, cr) # Hadamard gates for i in range(n): qc.h(i) # |w> -> |1> qc.x(n) # Implement U_f (f(x) = a^x (mod N)) U_f|x>|w> = |x>|w+f(x)> ("+" represents "XOR") for i in range(n): for j in range(2**i): if a in [2,13]: qc.cswap(i, n+2, n+3) qc.cswap(i, n+1, n+2) qc.cswap(i, n+0, n+1) if a in [7,8]: qc.cswap(i, n+0, n+1) qc.cswap(i, n+1, n+2) qc.cswap(i, n+2, n+3) if a in [11]: qc.cswap(i, n+0, n+2) qc.cswap(i, n+1, n+3) if a in [7,11,13,14]: for k in range(n): qc.cx(i, n+k) qc.barrier() # Implement QFTdagger for i in range(n//2): # Swap the qubits qc.swap(i, n-i-1) for i in range(n): for j in range(i): qc.cu1(-np.pi/(2**(i-j)), j, i) qc.h(i) qc.barrier() # Measure qc.measure(range(n), range(n)) # Show quantum circuit qc.draw(output='mpl', initial_state=True) simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator, shots=1024).result() plot_histogram(result.get_counts())
https://github.com/joemoorhouse/quantum-mc
joemoorhouse
import sys sys.path.append("..") # see os.getcwd() import time from quantum_mc.arithmetic.piecewise_linear_transform import PiecewiseLinearTransform3 import numpy as np from qiskit.test.base import QiskitTestCase import quantum_mc.calibration.fitting as ft import quantum_mc.calibration.time_series as ts from scipy.stats import multivariate_normal, norm from qiskit.test.base import QiskitTestCase from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.quantum_info import Statevector #from qiskit_finance.circuit.library import NormalDistribution from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, IntegerComparator from qiskit.utils import QuantumInstance from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem import matplotlib.pyplot as plt cm = 1 / 2.54 correl = ft.get_correl("AAPL", "MSFT") nbits = 3 bounds_std = 3. num_qubits = [nbits, nbits] sigma = correl bounds = [(-bounds_std, bounds_std), (-bounds_std, bounds_std)] mu = [0, 0] # starting point is a multi-variate normal distribution normal = NormalDistribution(num_qubits, mu=mu, sigma=sigma, bounds=bounds) coeff_set = [] xs = [] ys = [] pl_set = [] for ticker in ["MSFT", "AAPL"]: ((cdf_x, cdf_y), sigma) = ft.get_cdf_data(ticker) (x, y) = ft.get_fit_data(ticker, norm_to_rel = False) (pl, coeffs) = ft.fit_piecewise_linear(x, y) # scale, to apply an arbitrary delta (we happen to use the same value here, but could be different) coeffs = ft.scaled_coeffs(coeffs, 1.0 if ticker == "MSFT" else 1.0) coeff_set.append(coeffs) xs.append(x) ys.append(y) # calculate the max and min P&Ls pl_set.append(lambda z : ft.piecewise_linear(z, *coeff_set[0])) pl_set.append(lambda z : ft.piecewise_linear(z, *coeff_set[1])) p_max = max(pl_set[0](bounds_std), pl_set[1](bounds_std)) p_min = min(pl_set[0](-bounds_std), pl_set[1](-bounds_std)) # we discretise the transforms and create the circuits transforms = [] i_to_js = [] i_to_xs = [] j_to_ys = [] for i, ticker in enumerate(["MSFT", "AAPL"]): (i_0, i_1, a0, a1, a2, b0, b1, b2, i_to_j, i_to_x, j_to_y) = ft.integer_piecewise_linear_coeffs(coeff_set[i], x_min = -bounds_std, x_max = bounds_std, y_min = p_min, y_max = p_max, nbits_norm=nbits, nbits_extra = 1 if nbits == 2 else 2) transforms.append(PiecewiseLinearTransform3(i_0, i_1, a0, a1, a2, b0, b1, b2, nbits = nbits)) i_to_js.append(np.vectorize(i_to_j)) i_to_xs.append(np.vectorize(i_to_x)) j_to_ys.append(np.vectorize(j_to_y)) p_min, p_max i = np.arange(0, 2**nbits) index = 0 cm = 1 / 2.54 fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(xs[index], ys[index], "o", markersize = 2, label = "Observed") ax.plot(xs[index], np.vectorize(pl_set[index])(xs[index]), label = "Fitted") ax.plot(i_to_xs[index](i), j_to_ys[index](i_to_js[index](i)), '--', label = "Fitted, discretised") ax.set_xlabel('Normal return ($\sigma$)') ax.set_ylabel('Empirical return ($\sigma$)') ax.legend() fig.savefig('piecewise_fit.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.plot(i, i_to_js[index](i)) ax.set_xlabel('Normal return integer') ax.set_ylabel('Empirical return integer') fig.savefig('piecewise_fit_ints.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) # starting point is a multi-variate normal distribution single_normal = NormalDistribution(3, mu=0, sigma=1, bounds=(-3, 3) ) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.bar(np.arange(0, 2**3), single_normal._probabilities) ax.set_yscale("log") ax.set_xlabel('Register integer value pre-transform') ax.set_ylabel('Probability') fig.savefig('piecewise_transform_before.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') ax.bar(i_to_js[0](np.arange(0, 2**3)), single_normal._probabilities) ax.set_yscale("log") ax.set_xlabel('Register integer value post-transform') ax.set_ylabel('Probability') fig.savefig('piecewise_transform_after.pdf', formt='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.plot(xf2, pdf_fn(xf2), label = "Fitted") ax.hist(rets, density = True, bins = 100, label = "Empirical") ax.set_xlim(-6, 4) ax.set_xlabel('Return ($\sigma$)') ax.set_ylabel('Probability density') ax.legend() fig.savefig('hist_pdf_spline_fitted.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) num_ancillas = transforms[0].num_ancilla_qubits qr_input = QuantumRegister(nbits * 2, 'input') # 2 times 3 registers qr_objective = QuantumRegister(1, 'objective') qr_result = QuantumRegister(nbits * 2, 'result') qr_ancilla = QuantumRegister(num_ancillas, 'ancilla') output = ClassicalRegister(nbits * 2, 'output') state_preparation = QuantumCircuit(qr_input, qr_objective, qr_result, qr_ancilla, output) state_preparation.append(normal, qr_input) for i in range(2): offset = i * nbits state_preparation.append(transforms[i], qr_input[offset:offset + nbits] + qr_result[:] + qr_ancilla[:]) # to calculate the cdf, we use an additional comparator x_eval = 5 comparator = IntegerComparator(len(qr_result), x_eval + 1, geq=False) state_preparation.append(comparator, qr_result[:] + qr_objective[:] + qr_ancilla[0:comparator.num_ancillas]) state_preparation.measure(qr_result, output) # now check check = False if check: job = execute(state_preparation, backend=Aer.get_backend('statevector_simulator')) var_prob = 0 for i, a in enumerate(job.result().get_statevector()): b = ('{0:0%sb}' % (len(qr_input) + 1)).format(i)[-(len(qr_input) + 1):] prob = np.abs(a)**2 if prob > 1e-6 and b[0] == '1': var_prob += prob print('Operator CDF(%s)' % x_eval + ' = %.4f' % var_prob) state_preparation.draw() #state_preparation.draw() fig = state_preparation.draw(output='mpl') fig.savefig('../../../outputs/trans_circuit_detail.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True, bbox_inches='tight') counts = execute(state_preparation, Aer.get_backend('qasm_simulator'), shots = 100000).result().get_counts() from qiskit.visualization import plot_histogram plot_histogram(counts, title = "transform of normal") vals = [int(i, 2) for i,j in counts.items()] cnts = np.array([j for i,j in counts.items()]) plt.bar(vals, cnts) vals2 = p_min * 2 + np.array(vals) * 2 * (p_max - p_min) / (2**(nbits * 2) - 1) cnts = np.array([j for i,j in counts.items()]) cnts2 = cnts / np.sum(cnts) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.bar(vals2, cnts2, width = 0.2) ax.set_xlabel('Normalised P&L') ax.set_ylabel('Probability') ax.legend() fig.savefig('pnl_quantum.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) # based on Sascha's noise model import qiskit.providers.aer.noise as noise from qiskit.utils import QuantumInstance # Noise settings use_noise = True #False error_scaling_factor = 2 ** 0 # Reference point: 1.0 (= no scaling) error_prob_1_gate = 0.001 * error_scaling_factor error_prob_2_gates = 0.001 * error_scaling_factor error_prob_measure = 0.001 * error_scaling_factor error_1 = noise.depolarizing_error(error_prob_1_gate, 1) error_2 = noise.depolarizing_error(error_prob_2_gates, 2) # Measurement errors error_m = noise.pauli_error([('X', error_prob_measure), ('I', 1 - error_prob_measure)]) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) noise_model.add_all_qubit_quantum_error(error_m, "measure") # Prepare IQAE backend = Aer.get_backend(simulator) qinstance = QuantumInstance(backend=backend, seed_simulator=2, seed_transpiler=2, shots=shots, noise_model=noise_model) problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=obj_qubit_ID) iqae = IterativeAmplitudeEstimation(epsilon_target=epsilon, alpha=alpha, quantum_instance=qinstance) result = iqae.estimate(problem) IBMQ.save_account("543dce4ab356df3a024dfcf606c9d74a31277e39232f0429dacdb0e00daa3622d02865023f613afd659783251eb5bde6f06e9d0f5f1a95b03fdf8a0d34449bef") provider = IBMQ.load_account() provider.backends() backend = provider.get_backend('ibmq_montreal') from qiskit import IBMQ, transpile from qiskit import QuantumCircuit from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeMontreal device_backend = FakeMontreal() sim_be = AerSimulator.from_backend(device_backend) #sim_ideal = AerSimulator() #result = sim_ideal.run(transpile(state_preparation, sim_ideal)).result() #counts = result.get_counts(0) tcirc = transpile(state_preparation, sim_be) result_noise = sim_be.run(tcirc).result() counts_noise = result_noise.get_counts(0) from qiskit.visualization import plot_histogram plot_histogram(counts, title = "transform of normal") vals = [int(i, 2) for i,j in counts.items()] cnts = [j for i,j in counts.items()] plt.bar(vals, cnts) from qiskit import QuantumCircuit, execute from qiskit import IBMQ, Aer from qiskit.visualization import plot_histogram from qiskit.providers.aer.noise import NoiseModel # Build noise model from backend properties #provider = IBMQ.load_account() from qiskit.test.mock import FakeMontreal backend = FakeMontreal() #backend = provider.get_backend('ibmq_montreal') noise_model = NoiseModel.from_backend(backend) # Get coupling map from backend coupling_map = backend.configuration().coupling_map # Get basis gates from noise model basis_gates = noise_model.basis_gates counts = execute(state_preparation, Aer.get_backend('qasm_simulator'), #shots = 500000, coupling_map=coupling_map, basis_gates=basis_gates, noise_model=noise_model ).result().get_counts() from qiskit.visualization import plot_histogram plot_histogram(counts, title = "transform of normal") vals = [int(i, 2) for i,j in counts.items()] cnts = [j for i,j in counts.items()] plt.bar(vals, cnts) import qiskit.providers.aer.noise as noise from qiskit.utils import QuantumInstance print(time.strftime("%H:%M:%S", time.localtime())) error_scaling_factor = 2 ** 0 # Reference point: 1.0 (= no scaling) error_prob_1_gate = 0.001 * error_scaling_factor error_prob_2_gates = 0.001 * error_scaling_factor error_prob_measure = 0.001 * error_scaling_factor error_1 = noise.depolarizing_error(error_prob_1_gate, 1) error_2 = noise.depolarizing_error(error_prob_2_gates, 2) # Measurement errors error_m = noise.pauli_error([('X', error_prob_measure), ('I', 1 - error_prob_measure)]) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) noise_model.add_all_qubit_quantum_error(error_m, "measure") # now do AE problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_input)]) # target precision and confidence level epsilon = 0.01 alpha = 0.05 qi = QuantumInstance(Aer.get_backend('aer_simulator'), noise_model=noise_model) ae_cdf = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=qi) result_cdf = ae_cdf.estimate(problem) conf_int = np.array(result_cdf.confidence_interval) print('Estimated value:\t%.4f' % result_cdf.estimation) print('Confidence interval: \t[%.4f, %.4f]' % tuple(conf_int)) #state_preparation.draw() print(time.strftime("%H:%M:%S", time.localtime())) def get_sims(normal_distribution): import numpy as np values = normal_distribution._values probs = normal_distribution._probabilities # we generate a bunch of realisation of values, based upper_bounds = [0.0] stop = 0.0 for val, prob in zip(values, probs): stop += prob upper_bounds.append(stop) np.random.seed = 101 r = np.random.uniform(low=0.0, high=1.0, size=1000000) indices = np.searchsorted(upper_bounds, r, side='left', sorter=None) - 1 g1, g2 = np.meshgrid(range(2**nbits), range(2**nbits), indexing="ij",) i1 = g1.flatten()[indices] i2 = g2.flatten()[indices] #x = list(zip(*(grid.flatten() for grid in meshgrid))) return i1, i2 i1, i2 = get_sims(normal) j1 = i_to_js[0](i1) j2 = i_to_js[1](i2) j_tot = j1 + j2 import collections counts = {} for item in j_tot: if item in counts: counts[item] += 1 else: counts[item] = 1 counts = collections.OrderedDict(sorted(counts.items())) vals = [i for i,j in counts.items()] cnts = [j for i,j in counts.items()] plt.bar(vals, cnts) vals2 = p_min * 2 + np.array(vals) * 2 * (p_max - p_min) / (2**(nbits * 2) - 1) cnts = np.array([j for i,j in counts.items()]) cnts2 = cnts / np.sum(cnts) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.bar(vals2, cnts2, width = 0.2) ax.set_xlabel('Normalised P&L') ax.set_ylabel('Probability') ax.legend() fig.savefig('pnl_classical.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) sum = 0 for v,c in zip(vals, cnts): if v <= 8: sum += c print(float(sum) / 1000000) print(p_min * 2 + 14 * 2 * (p_max - p_min) / (2**(nbits * 2) - 1) ) correl = ft.get_correl("AAPL", "MSFT") c = np.linalg.cholesky(correl) r = np.random.normal(0, 1, size = (2, 1000000)) v = c@r v1 = np.vectorize(pl_set[0])(v[0, :]) v2 = np.vectorize(pl_set[1])(v[1, :]) vt = v1 + v2 cm = 1 / 2.54 fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') _ = plt.hist(vt, bins = 200, density = True) ax.set_xlabel('Normalised P&L') ax.set_ylabel('Probability density') ax.set_xlim(-10, 10) fig.savefig('pnl_classical_continuous.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) np.percentile(vt, 1.0) import quantum_mc.calibration.time_series as ts (cdf_c_x, cdf_c_y) = ts.ecdf(vt) #(cdf_d_x, cdf_d_y) = ts.ecdf(vt) sum = 0 cum_sum = [] for v,c in zip(vals, cnts): sum += c cum_sum.append(sum) cum_sum = np.array(cum_sum) cum_sum = cum_sum / np.max(cum_sum) vals2 = p_min * 2 + np.array(vals) * 2 * (p_max - p_min) / (2**(nbits * 2) - 1) vals_2bits = np.array([-10.70188609, -7.39985348, -6.29917595, -5.19849841, -2.99714334, -1.8964658, -0.79578826, 1.40556681, 2.50624435, 4.70759942]) cum_prob_2bits = np.array([0.003903, 0.007387, 0.010792, 0.010795, 0.462747, 0.537787, 0.98928, 0.992701, 0.996142, 1.]) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.plot(cdf_c_x, cdf_c_y, label = "Continuous", ) plt.plot(vals2, cum_sum, '--', label = "3 qubit") plt.plot(vals_2bits, cum_prob_2bits, ':', label = "2 qubit") ax.set_yscale("log") ax.set_xlabel('Normalised P&L') ax.set_ylabel('Cumulative probability') ax.set_xlim(-8, 5) #ax.set_ylim(0.001, 0.02) ax.set_ylim(0.001, 0.999) ax.legend() fig.savefig('cdf_class_quant_log.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) fig = plt.figure(figsize=(8*cm,6*cm)) ax = fig.add_axes([0.2, 0.19, 0.77, 0.77]) fig.set_facecolor('w') plt.plot(cdf_c_x, cdf_c_y, label = "Continuous") plt.plot(vals2, cum_sum, '--', label = "3 qubit") plt.plot(vals_2bits, cum_prob_2bits, ':', label = "2 qubit") #ax.set_yscale("log") ax.set_xlabel('Normalised P&L') ax.set_ylabel('Cumulative probability') ax.set_xlim(-8, 5) #ax.set_ylim(0.001, 0.02) ax.set_ylim(0.001, 0.999) ax.legend() fig.savefig('cdf_class_quant_lin.pdf', format='pdf', facecolor=fig.get_facecolor(), transparent=True) cont = np.interp([0.01, 0.025, 0.05], cdf_c_y, cdf_c_x) quant3 = np.interp([0.01, 0.025, 0.05], cum_sum, vals2) quant2 = np.interp([0.01, 0.025, 0.05], cum_prob_2bits, vals_2bits) np.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)}) print('Continuous') print(cont) print('3 qubits') print(quant3) print(abs(quant3/cont - 1) * 100) print('2 qubits') print(quant2) print(abs(quant2/cont - 1) * 100) print("Check")
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools 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.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # 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) # Number of trotter steps trotter_steps = 15 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) 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>) qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # 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) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = [] for job in jobs: mit_results.append( meas_fitter.filter.apply(job.result()) ) # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits def state_tomo(result, st_qcs): # The expected final state; necessary to determine state tomography fidelity target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Fit state tomography results tomo_fitter = StateTomographyFitter(result, st_qcs) rho_fit = tomo_fitter.fit(method='lstsq') # Compute fidelity fid = state_fidelity(rho_fit, target_state) return fid # Compute tomography fidelities for each repetition fids = [] for result in mit_results: fid = state_tomo(result, st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
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. """Test the RZXCalibrationBuilderNoEcho.""" from math import pi, erf import numpy as np from ddt import data, ddt from qiskit.converters import circuit_to_dag from qiskit import circuit, schedule, QiskitError from qiskit.circuit.library.standard_gates import SXGate, RZGate from qiskit.providers.fake_provider import FakeHanoi # TODO - include FakeHanoiV2, FakeSherbrooke from qiskit.providers.fake_provider import FakeArmonk from qiskit.pulse import ( ControlChannel, DriveChannel, GaussianSquare, Waveform, Play, InstructionScheduleMap, Schedule, ) from qiskit.pulse import builder from qiskit.pulse.transforms import target_qobj_transform from qiskit.test import QiskitTestCase from qiskit.transpiler import PassManager from qiskit.transpiler.passes.calibration.builders import ( RZXCalibrationBuilder, RZXCalibrationBuilderNoEcho, ) class TestCalibrationBuilder(QiskitTestCase): """Test the Calibration Builder.""" # CR parameters __risefall = 4 __angle = np.pi / 2 __granularity = 16 @staticmethod def get_cr_play(cr_schedule, name): """A helper function to filter CR pulses.""" def _filter_func(time_inst): return isinstance(time_inst[1], Play) and time_inst[1].pulse.name.startswith(name) return cr_schedule.filter(_filter_func).instructions[0][1] def compute_stretch_duration(self, play_gaussian_square_pulse, theta): """Compute duration of stretched Gaussian Square pulse.""" pulse = play_gaussian_square_pulse.pulse sigma = pulse.sigma width = self.compute_stretch_width(play_gaussian_square_pulse, theta) duration = width + sigma * self.__risefall return round(duration / self.__granularity) * self.__granularity def compute_stretch_width(self, play_gaussian_square_pulse, theta): """Compute width of stretched Gaussian Square pulse.""" pulse = play_gaussian_square_pulse.pulse sigma = pulse.sigma width = pulse.width risefall_area = sigma * np.sqrt(2 * np.pi) * erf(self.__risefall) full_area = risefall_area + width target_area = abs(theta) / self.__angle * full_area return max(0, target_area - risefall_area) def u0p_play(self, cr_schedule): """Returns the positive CR pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90p_u") def u0m_play(self, cr_schedule): """Returns the negative CR pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90m_u") def d1p_play(self, cr_schedule): """Returns the positive rotary echo pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90p_d") def d1m_play(self, cr_schedule): """Returns the negative rotary echo pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90m_d") @ddt class TestRZXCalibrationBuilder(TestCalibrationBuilder): """Test RZXCalibrationBuilder.""" def build_forward( self, backend, theta, u0p_play, d1p_play, u0m_play, d1m_play, ): """A helper function to generate reference pulse schedule for forward direction.""" duration = self.compute_stretch_duration(u0p_play, theta) width = self.compute_stretch_width(u0p_play, theta) with builder.build( backend, default_alignment="sequential", default_transpiler_settings={"optimization_level": 0}, ) as ref_sched: with builder.align_left(): # Positive CRs u0p_params = u0p_play.pulse.parameters u0p_params["duration"] = duration u0p_params["width"] = width builder.play( GaussianSquare(**u0p_params), ControlChannel(0), ) d1p_params = d1p_play.pulse.parameters d1p_params["duration"] = duration d1p_params["width"] = width builder.play( GaussianSquare(**d1p_params), DriveChannel(1), ) builder.x(0) with builder.align_left(): # Negative CRs u0m_params = u0m_play.pulse.parameters u0m_params["duration"] = duration u0m_params["width"] = width builder.play( GaussianSquare(**u0m_params), ControlChannel(0), ) d1m_params = d1m_play.pulse.parameters d1m_params["duration"] = duration d1m_params["width"] = width builder.play( GaussianSquare(**d1m_params), DriveChannel(1), ) builder.x(0) return ref_sched def build_reverse( self, backend, theta, u0p_play, d1p_play, u0m_play, d1m_play, ): """A helper function to generate reference pulse schedule for backward direction.""" duration = self.compute_stretch_duration(u0p_play, theta) width = self.compute_stretch_width(u0p_play, theta) with builder.build( backend, default_alignment="sequential", default_transpiler_settings={"optimization_level": 0}, ) as ref_sched: # Hadamard gates builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(SXGate(), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) builder.call_gate(SXGate(), qubits=(1,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) with builder.align_left(): # Positive CRs u0p_params = u0p_play.pulse.parameters u0p_params["duration"] = duration u0p_params["width"] = width builder.play( GaussianSquare(**u0p_params), ControlChannel(0), ) d1p_params = d1p_play.pulse.parameters d1p_params["duration"] = duration d1p_params["width"] = width builder.play( GaussianSquare(**d1p_params), DriveChannel(1), ) builder.x(0) with builder.align_left(): # Negative CRs u0m_params = u0m_play.pulse.parameters u0m_params["duration"] = duration u0m_params["width"] = width builder.play( GaussianSquare(**u0m_params), ControlChannel(0), ) d1m_params = d1m_play.pulse.parameters d1m_params["duration"] = duration d1m_params["width"] = width builder.play( GaussianSquare(**d1m_params), DriveChannel(1), ) builder.x(0) # Hadamard gates builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(SXGate(), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) builder.call_gate(SXGate(), qubits=(1,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) return ref_sched @data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi) def test_rzx_calibration_cr_pulse_stretch(self, theta: float): """Test that cross resonance pulse durations are computed correctly.""" backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map cr_schedule = inst_map.get("cx", (0, 1)) with builder.build() as test_sched: RZXCalibrationBuilder.rescale_cr_inst(self.u0p_play(cr_schedule), theta) self.assertEqual( test_sched.duration, self.compute_stretch_duration(self.u0p_play(cr_schedule), theta) ) @data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi) def test_rzx_calibration_rotary_pulse_stretch(self, theta: float): """Test that rotary pulse durations are computed correctly.""" backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map cr_schedule = inst_map.get("cx", (0, 1)) with builder.build() as test_sched: RZXCalibrationBuilder.rescale_cr_inst(self.d1p_play(cr_schedule), theta) self.assertEqual( test_sched.duration, self.compute_stretch_duration(self.d1p_play(cr_schedule), theta) ) def test_raise(self): """Test that the correct error is raised.""" theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) dag = circuit_to_dag(qc) backend = FakeArmonk() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) qubit_map = {qubit: i for i, qubit in enumerate(dag.qubits)} with self.assertRaises(QiskitError): for node in dag.gate_nodes(): qubits = [qubit_map[q] for q in node.qargs] _pass.get_calibration(node.op, qubits) def test_ecr_cx_forward(self): """Test that correct pulse sequence is generated for native CR pair.""" # Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) test_qc = PassManager(_pass).run(qc) cr_schedule = inst_map.get("cx", (0, 1)) ref_sched = self.build_forward( backend, theta, self.u0p_play(cr_schedule), self.d1p_play(cr_schedule), self.u0m_play(cr_schedule), self.d1m_play(cr_schedule), ) self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched)) def test_ecr_cx_reverse(self): """Test that correct pulse sequence is generated for non-native CR pair.""" # Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 1, 0) backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) test_qc = PassManager(_pass).run(qc) cr_schedule = inst_map.get("cx", (0, 1)) ref_sched = self.build_reverse( backend, theta, self.u0p_play(cr_schedule), self.d1p_play(cr_schedule), self.u0m_play(cr_schedule), self.d1m_play(cr_schedule), ) self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched)) def test_pass_alive_with_dcx_ish(self): """Test if the pass is not terminated by error with direct CX input.""" cx_sched = Schedule() # Fake direct cr cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True) # Fake direct compensation tone # Compensation tone doesn't have dedicated pulse class. # So it's reported as a waveform now. compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex)) cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add("cx", (1, 0), schedule=cx_sched) theta = pi / 3 rzx_qc = circuit.QuantumCircuit(2) rzx_qc.rzx(theta, 1, 0) pass_ = RZXCalibrationBuilder(instruction_schedule_map=inst_map) with self.assertWarns(UserWarning): # User warning that says q0 q1 is invalid cal_qc = PassManager(pass_).run(rzx_qc) self.assertEqual(cal_qc, rzx_qc) class TestRZXCalibrationBuilderNoEcho(TestCalibrationBuilder): """Test RZXCalibrationBuilderNoEcho.""" def build_forward( self, theta, u0p_play, d1p_play, ): """A helper function to generate reference pulse schedule for forward direction.""" duration = self.compute_stretch_duration(u0p_play, 2.0 * theta) width = self.compute_stretch_width(u0p_play, 2.0 * theta) with builder.build() as ref_sched: # Positive CRs u0p_params = u0p_play.pulse.parameters u0p_params["duration"] = duration u0p_params["width"] = width builder.play( GaussianSquare(**u0p_params), ControlChannel(0), ) d1p_params = d1p_play.pulse.parameters d1p_params["duration"] = duration d1p_params["width"] = width builder.play( GaussianSquare(**d1p_params), DriveChannel(1), ) builder.delay(duration, DriveChannel(0)) return ref_sched def test_ecr_cx_forward(self): """Test that correct pulse sequence is generated for native CR pair. .. notes:: No echo builder only supports native direction. """ # Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilderNoEcho(inst_map) test_qc = PassManager(_pass).run(qc) cr_schedule = inst_map.get("cx", (0, 1)) ref_sched = self.build_forward( theta, self.u0p_play(cr_schedule), self.d1p_play(cr_schedule), ) self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched)) # # TODO - write test for forward ECR native pulse # def test_ecr_forward(self): def test_pass_alive_with_dcx_ish(self): """Test if the pass is not terminated by error with direct CX input.""" cx_sched = Schedule() # Fake direct cr cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True) # Fake direct compensation tone # Compensation tone doesn't have dedicated pulse class. # So it's reported as a waveform now. compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex)) cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add("cx", (1, 0), schedule=cx_sched) theta = pi / 3 rzx_qc = circuit.QuantumCircuit(2) rzx_qc.rzx(theta, 1, 0) pass_ = RZXCalibrationBuilderNoEcho(instruction_schedule_map=inst_map) with self.assertWarns(UserWarning): # User warning that says q0 q1 is invalid cal_qc = PassManager(pass_).run(rzx_qc) self.assertEqual(cal_qc, rzx_qc)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# 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. """ Test circuits and reference outputs for snapshot state instructions. """ from numpy import array, sqrt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer.extensions.snapshot import Snapshot from qiskit.providers.aer.extensions.snapshot_statevector import * def snapshot_state_circuits_deterministic(snapshot_label='snap', snapshot_type='statevector', post_measure=False): """Snapshot Statevector test circuits""" circuits = [] num_qubits = 3 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) regs = (qr, cr) # State snapshot instruction acting on all qubits snapshot = Snapshot(snapshot_label, snapshot_type, num_qubits) # Snapshot |000> circuit = QuantumCircuit(*regs) if not post_measure: circuit.append(snapshot, qr) circuit.barrier(qr) circuit.measure(qr, cr) if post_measure: circuit.append(snapshot, qr) circuits.append(circuit) # Snapshot |111> circuit = QuantumCircuit(*regs) circuit.x(qr) if not post_measure: circuit.append(snapshot, qr) circuit.barrier(qr) circuit.measure(qr, cr) if post_measure: circuit.append(snapshot, qr) circuits.append(circuit) return circuits def snapshot_state_counts_deterministic(shots): """Snapshot Statevector test circuits reference counts.""" targets = [] # Snapshot |000> targets.append({'0x0': shots}) # Snapshot |111> targets.append({'0x7': shots}) return targets def snapshot_state_pre_measure_statevector_deterministic(): """Snapshot Statevector test circuits reference final statevector""" targets = [] # Snapshot |000> targets.append(array([1, 0, 0, 0, 0, 0, 0, 0], dtype=complex)) # Snapshot |111> targets.append(array([0, 0, 0, 0, 0, 0, 0, 1], dtype=complex)) return targets def snapshot_state_post_measure_statevector_deterministic(): """Snapshot Statevector test circuits reference final statevector""" targets = [] # Snapshot |000> targets.append({'0x0': array([1, 0, 0, 0, 0, 0, 0, 0], dtype=complex)}) # Snapshot |111> targets.append({'0x7': array([0, 0, 0, 0, 0, 0, 0, 1], dtype=complex)}) return targets def snapshot_state_circuits_nondeterministic(snapshot_label='snap', snapshot_type='statevector', post_measure=False): """Snapshot Statevector test circuits""" circuits = [] num_qubits = 3 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) regs = (qr, cr) # State snapshot instruction acting on all qubits snapshot = Snapshot(snapshot_label, snapshot_type, num_qubits) # Snapshot |000> + i|111> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.s(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) if not post_measure: circuit.append(snapshot, qr) circuit.barrier(qr) circuit.measure(qr, cr) if post_measure: circuit.append(snapshot, qr) circuits.append(circuit) # Snapshot |+++> circuit = QuantumCircuit(*regs) circuit.h(qr) if not post_measure: circuit.append(snapshot, qr) circuit.barrier(qr) circuit.measure(qr, cr) if post_measure: circuit.append(snapshot, qr) circuits.append(circuit) return circuits def snapshot_state_counts_nondeterministic(shots): """Snapshot Statevector test circuits reference counts.""" targets = [] # Snapshot |000> + i|111> targets.append({'0x0': shots/2, '0x7': shots/2}) # Snapshot |+++> targets.append({'0x0': shots/8, '0x1': shots/8, '0x2': shots/8, '0x3': shots/8, '0x4': shots/8, '0x5': shots/8, '0x6': shots/8, '0x7': shots/8}) return targets def snapshot_state_pre_measure_statevector_nondeterministic(): """Snapshot Statevector test circuits reference final statevector""" targets = [] # Snapshot |000> + i|111> targets.append(array([1, 0, 0, 0, 0, 0, 0, 1j], dtype=complex) / sqrt(2)) # Snapshot |+++> targets.append(array([1, 1, 1, 1, 1, 1, 1, 1], dtype=complex) / sqrt(8)) return targets def snapshot_state_post_measure_statevector_nondeterministic(): """Snapshot Statevector test circuits reference final statevector""" targets = [] # Snapshot |000> + i|111> targets.append({'0x0': array([1, 0, 0, 0, 0, 0, 0, 0], dtype=complex), '0x7': array([0, 0, 0, 0, 0, 0, 0, 1j], dtype=complex)}) # Snapshot |+++> targets.append({'0x0': array([1, 0, 0, 0, 0, 0, 0, 0], dtype=complex), '0x1': array([0, 1, 0, 0, 0, 0, 0, 0], dtype=complex), '0x2': array([0, 0, 1, 0, 0, 0, 0, 0], dtype=complex), '0x3': array([0, 0, 0, 1, 0, 0, 0, 0], dtype=complex), '0x4': array([0, 0, 0, 0, 1, 0, 0, 0], dtype=complex), '0x5': array([0, 0, 0, 0, 0, 1, 0, 0], dtype=complex), '0x6': array([0, 0, 0, 0, 0, 0, 1, 0], dtype=complex), '0x7': array([0, 0, 0, 0, 0, 0, 0, 1], dtype=complex)}) return targets
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import qiskit as qsk import numpy as np from qiskit.circuit.add_control import add_control def _qft(circuit, qregister): """ QFT on a circuit. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. qregister(qiskit.QuantumRegister): Quantum register for the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ def qft_rotations(circuit, qregister): """ Defines the rotations necessary for the QFT in a recursive manner. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. qregister(qiskit.QuantumRegister): Quantum register for the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ for i in reversed(qregister): circuit.h(i) for qubit in range(i.index): circuit.cu1(np.pi/float(2**(i.index-qubit)), qregister[qubit], qregister[i.index]) return circuit def qft_swap(circuit, qregister): """Swap registers for the QFT. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. n(int): qubit to do the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ n = len(qregister) for qubit in range(n//2): circuit.swap(qregister[qubit], qregister[n-qubit-1]) return circuit qft_rotations(circuit,qregister) qft_swap(circuit, qregister) return circuit def qft(circuit,qregister): """QFT. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. qregister(qiskit.QuantumRegister): Quantum register for the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ qft_circuit= _qft(qsk.QuantumCircuit(qregister, name='QFT'), qregister) circuit.append(qft_circuit, qregister) return circuit def inverse_QFT(circuit,qregister): """ Inverse QFT. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. qregister(qiskit.QuantumRegister): Quantum register for the rotation. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ qft_circuit= _qft(qsk.QuantumCircuit(qregister, name='QFT'), qregister) inverseqft = qft_circuit.inverse() circuit.append(inverseqft, qregister) return circuit def qpe(circuit, unitary, precision, ancilla, init_state=None): """Applies the quantum phase estimation for a given unitary. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. unitary(np.array): Unitary. precision(QuantumRegister): Quantum register for the precision of the QPE. ancilla(QuantumRegister): Quantum register for the ancilla, must be len(unitary)//2 = n_ancilla. init_state(list): Initial state for the ancilla qubit. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ #n_precision = len(precision) n_ancilla = len(ancilla) assert len(unitary)//2 == n_ancilla, "Ancilla qubits does't match the number needed to expand the eigenstate." #Ancilla (need to add a way to initialize states) if init_state is not None: assert len(init_state) == 2**n_ancilla , "Initial state not valid." circuit.initialize(init_state, ancilla) #Precision circuit.h(precision) #Build unitary U = qsk.extensions.UnitaryGate(unitary, label='U') U_ctrl = add_control(U, num_ctrl_qubits=1, label='Controlled_U',ctrl_state=1) repetitions = 1 for counting_qubit in precision: for _ in range(repetitions): circuit.append(U_ctrl, [counting_qubit,ancilla]) repetitions *= 2 inverse_QFT(circuit, precision) return circuit def QPE(circuit, unitary, precision, ancilla, init_state=None): """ Inverse QPE. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. unitary(np.array): Unitary. precision(QuantumRegister): Quantum register for the precision of the QPE. ancilla(QuantumRegister): Quantum register for the ancilla, must be len(unitary)//2 = n_ancilla. init_state(list): Initial state for the ancilla qubit. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ qpe_circuit = qsk.QuantumCircuit(precision, name='QPE') qpe_circuit.add_register(ancilla) qpe_circuit= qpe(qpe_circuit, unitary, precision, ancilla, init_state=init_state) append_qbits = [i for i in precision] for i in ancilla: append_qbits.append(i) circuit.append(qpe_circuit, append_qbits) return circuit def inverse_QPE(circuit, unitary, precision, ancilla, init_state=None): """ Inverse QPE. Parameters ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit. unitary(np.array): Unitary. precision(QuantumRegister): Quantum register for the precision of the QPE. ancilla(QuantumRegister): Quantum register for the ancilla, must be len(unitary)//2 = n_ancilla. init_state(list): Initial state for the ancilla qubit. Output ------------------------------------------------ circuit(qiskit.QuantumCircuit): Quantum Circuit with qft. """ qpe_circuit = qsk.QuantumCircuit(precision, name='QPE') qpe_circuit.add_register(ancilla) qpe_circuit= qpe(qpe_circuit, unitary, precision, ancilla, init_state=init_state) inverseqpe = qpe_circuit.inverse() append_qbits = [i for i in precision] for i in ancilla: append_qbits.append(i) circuit.append(inverseqpe, append_qbits) return circuit
https://github.com/hugoecarl/TSP-Problem-Study
hugoecarl
import math import matplotlib.pyplot as plt %matplotlib inline class TSP: def __init__(self): self.flat_mat = flat_mat self.n = 0 self.melhor_dist = 1e11 self.pontos = [] self.melhores_pontos = [] def busca_exaustiva(self, flat_mat, n, ite): if ite == n: dist = 0 for j in range(1, n): dist += flat_mat[self.pontos[j-1] * n + self.pontos[j]] dist += flat_mat[self.pontos[n-1] * n + self.pontos[0]] if dist < self.melhor_dist: self.melhor_dist = dist self.melhores_pontos = self.pontos[:] return for i in range(n): if self.pontos[i] == -1: self.pontos[i] = ite self.busca_exaustiva(flat_mat, n, ite + 1) self.pontos[i] = -1 def dist_mat(self): x = [] y = [] flat_mat = [] #matriz 1 dimensao contendo todas as distancias possiveis entre os pontos para facilitar cálculo. while True: try: temp = input("Digite a coordenada x y: ").split() x.append(float(temp[0])) y.append(float(temp[1])) except: break for i in range(len(x)): for j in range(len(y)): flat_mat.append(math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2)) return flat_mat, x, y def get_results(self): self.flat_mat, x, _ = self.dist_mat() self.n = len(x) self.pontos = [-1]*self.n self.pontos[0] = 0 self.busca_exaustiva(self.flat_mat, self.n, 1) return self.melhor_dist, self.melhores_pontos Tsp = TSP() distancia, pontos = Tsp.get_results() print("Melhor distancia encontrada: ", distancia) print("Melhor caminho encontrado: ", pontos) #plota gráfico def connectpoints(x,y,p1,p2): x1, x2 = x[p1], x[p2] y1, y2 = y[p1], y[p2] plt.plot([x1,x2],[y1,y2],'ro-') for i in range(1, len(pontos)): connectpoints(x,y,pontos[i-1],pontos[i]) connectpoints(x,y,pontos[len(x)-1],pontos[0]) plt.title("Percurso") plt.show() %%time %%cmd python TSP.py < in-1.txt type out-1.txt python TSP.py < in-2.txt type out-2.txt python TSP.py < in-3.txt type out-3.txt python TSP.py < in-4.txt type out-4.txt from qiskit import IBMQ import numpy as np #IBMQ.save_account('seu-tokenIBMQ-para-rodar-localmente') IBMQ.load_account() from qiskit import Aer from qiskit.tools.visualization import plot_histogram from qiskit.circuit.library import TwoLocal from qiskit.optimization.applications.ising import max_cut, tsp from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua import aqua_globals from qiskit.aqua import QuantumInstance from qiskit.optimization.applications.ising.common import sample_most_likely from qiskit.optimization.algorithms import MinimumEigenOptimizer from qiskit.optimization.problems import QuadraticProgram import logging from qiskit.aqua import set_qiskit_aqua_logging #Preparando os dados segundo os imputs do usuario para serem resolvidos pelo qiskit max 4 pontos por limitação de qubits coord = [] flat_mat, x, y = TSP().dist_mat() dist_mat = np.array(flat_mat).reshape(len(x),len(x)) for i, j in zip(x, y): coord.append([i,j]) ins = tsp.TspData('TSP_Q', dim=len(x), coord=np.array(coord), w=dist_mat) qubitOp, offset = tsp.get_operator(ins) print('Offset:', offset) print('Ising Hamiltonian:') print(qubitOp.print_details()) #Usando o numpyMinimumEigensolver como o solver do problema para resolver de forma quantica ee = NumPyMinimumEigensolver(qubitOp) result = ee.run() print('energy:', result.eigenvalue.real) print('tsp objective:', result.eigenvalue.real + offset) x_Q = sample_most_likely(result.eigenstate) print('feasible:', tsp.tsp_feasible(x_Q)) z = tsp.get_tsp_solution(x_Q) print('solution:', z) print('solution objective:', tsp.tsp_value(z, ins.w)) for i in range(1, len(z)): connectpoints(x,y,z[i-1],z[i]) connectpoints(x,y,z[len(x)-1],z[0]) plt.title("Percurso") plt.show() #instanciando o simulador ou o computador real importante lembrar que nao ira funcionar para mais de 4 pontos pelo numero de qubits disponibilizados pela IBM que sao apenas 16 para o simulador qasm e 15 para a maquina quantica provider = IBMQ.get_provider(hub = 'ibm-q') device = provider.get_backend('ibmq_16_melbourne') aqua_globals.random_seed = np.random.default_rng(123) seed = 10598 backend = Aer.get_backend('qasm_simulator') #descomentar essa linha caso queira rodar na maquina real #backend = device quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) #rodando no simulador quantico spsa = SPSA(maxiter=10) ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa, quantum_instance=quantum_instance) result = vqe.run(quantum_instance) print('energy:', result.eigenvalue.real) print('time:', result.optimizer_time) x = sample_most_likely(result.eigenstate) print('feasible:', tsp.tsp_feasible(x_Q)) z = tsp.get_tsp_solution(x_Q) print('solution:', z) print('solution objective:', tsp.tsp_value(z, ins.w))
https://github.com/Juan-Varela11/BNL_2020_Summer_Internship
Juan-Varela11
import numpy as np import matplotlib.pyplot as plt from qiskit import IBMQ import qiskit.pulse as pulse import qiskit.pulse.pulse_lib as pulse_lib from qiskit.compiler import assemble from qiskit.qobj.utils import MeasLevel, MeasReturnType from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-internal', group='deployed', project='default') backend = provider.get_backend('ibmq_johannesburg') backend_config = backend.configuration() config = backend.configuration() defaults = backend.defaults() # qubit to use for exeperiment control_qubit = 1 target_qubit = 0 control_channel_index = 1 # exp configuration exps = 30 shots = 512 # Rabi pulse cr_amps = np.linspace(0, 0.2, exps) cr_samples = 200 cr_sigma = 4 cr_rise_fall = 16 # scaling factor for data returned by backend # note: You may have to adjust this for the backend you use scale_factor= 1e-14 [control_qubit, target_qubit] in config.coupling_map defaults.qubit_freq_est[control_qubit] > defaults.qubit_freq_est[target_qubit] config.u_channel_lo[control_channel_index] # Create schedule schedules = [] for ii, cr_amp in enumerate(cr_amps): # drive pulse cr_rabi_pulse_p = pulse_lib.gaussian_square(duration=cr_samples, amp=cr_amp, sigma=cr_sigma, risefall=cr_rise_fall, name='cr_rabi_pulse_p%d' % ii) cr_rabi_pulse_m = pulse_lib.gaussian_square(duration=cr_samples, amp=-cr_amp, sigma=cr_sigma, risefall=cr_rise_fall, name='cr_rabi_pulse_m%d' % ii) control_channel = pulse.ControlChannel(control_channel_index) # We get the state preparation and measurement pulses we need from the # defaults `circuit_instruction_map` pi_pulse_q0 = defaults.circuit_instruction_map.get('u3', (control_qubit,), np.pi, 0, np.pi) measure = defaults.circuit_instruction_map.get('measure', config.meas_map[0]) # add commands to schedule schedule = pulse.Schedule(name='CR Rabi Experiment at drive amp = %s' % cr_amp) schedule |= cr_rabi_pulse_p(control_channel) schedule |= pi_pulse_q0 << schedule.duration schedule |= cr_rabi_pulse_m(control_channel) << schedule.duration schedule |= measure << schedule.duration schedules.append(schedule) schedules[1].draw(channels_to_plot=[pulse.DriveChannel(control_qubit), pulse.DriveChannel(target_qubit), control_channel, pulse.MeasureChannel(control_qubit), pulse.MeasureChannel(target_qubit)], scaling=10.0, label=False, plot_range=(0, 700)) cr_rabi_qobj = assemble(schedules, backend, meas_level=MeasLevel.KERNELED, meas_return=MeasReturnType.AVERAGE, shots=shots) job = backend.run(cr_rabi_qobj) job.job_id() job.status() cr_rabi_result = job.result(timeout=3600) job = backend.retrieve_job('5e31bf8e0520030011cbdb08') cr_rabi_results = job.result(timeout=120) target_qubit_rabi_data = np.ones(exps, dtype=np.complex_) control_qubit_rabi_data = np.ones(exps, dtype=np.complex_) for i in range(exps): target_qubit_rabi_data[i] = cr_rabi_result.get_memory(i)[target_qubit] control_qubit_rabi_data[i] = cr_rabi_result.get_memory(i)[control_qubit] # auto-phase the output measurement signal def get_amplitude(vec): i_signal = np.imag(vec) r_signal = np.real(vec) mvec = [np.mean(r_signal), np.mean(i_signal)] src_mat = np.vstack((r_signal - mvec[0], i_signal - mvec[1])).T (_, _, v_mat) = np.linalg.svd(src_mat) dvec = v_mat[0, 0:2] if dvec.dot(mvec) < 0: dvec = -dvec return src_mat.dot(dvec) target_rabi_amp_data = get_amplitude(target_qubit_rabi_data)*scale_factor control_rabi_amp_data = get_amplitude(control_qubit_rabi_data)*scale_factor fit_func = lambda x,A,B,T,phi: (A*np.cos(2*np.pi*x/T+phi)+B) #Fit the data fitparams, conv = curve_fit(fit_func, cr_amps, target_rabi_amp_data, [3.0,0.0,0.1,0]) #get the pi amplitude cr_pi_2_amp = (np.pi-fitparams[3])*fitparams[2]/4/np.pi plt.plot(cr_amps, fit_func(cr_amps, *fitparams), color='red') plt.axvline(cr_pi_2_amp, color='black', linestyle='dashed') plt.scatter(cr_amps, target_rabi_amp_data, label='target qubit') plt.scatter(cr_amps, control_rabi_amp_data, label='control qubit') plt.xlim(0, 0.2) plt.ylim(-5, 5) plt.legend() plt.xlabel('CR pulse amplitude, a.u.', fontsize=20) plt.ylabel('Signal, a.u.', fontsize=20) plt.title('CR Rabi oscillation', fontsize=20) print(cr_pi_2_amp) defaults.circuit_instruction_map.get('cx', (control_qubit, target_qubit)).draw(show_framechange_channels=False) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/DarkStarQuantumLab/Qauntum-trading-a-disturbance-in-the-force-of-supply-and-demand
DarkStarQuantumLab
!python3 -m pip install -q qiskit !python3 -m pip install -q qiskit_ibm_runtime from qiskit import IBMQ from qiskit_ibm_runtime import QiskitRuntimeService, Session, Options, Sampler, Estimator from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.quantum_info.operators import Operator from qiskit.extensions.unitary import UnitaryGate from qiskit.providers.aer import AerSimulator, Aer from qiskit.execute_function import execute import numpy as np from typing import Dict, Optional # ==================================== # pass IBM API Token # ==================================== QiskitRuntimeService.save_account(channel='ibm_quantum', token="", overwrite=True) num_players = 2 # define the payoff matrices. Assume, the 1st matrix is Alice's payoff, the secomd matrix is Bob's payoff payoff_matrix =[[[3, 0], [5, 1]], [[3, 5], [0, 1]]] # players' matrices # |C> strategy # bob = [ # [1, 0], # [0, 1]] # |D> strategy # bob = [ # [0, 1], # [1, 0], # ] def alice_plays_quantum(theta:float, phi:float): """ Set up a quantum game for Alice playing quantum, and Bob playing classically. Arg: theta: the value of the theta parameter. phi: the value of the phi parameter. Returns: qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit', a constructed quantum circuit for the quantum game set up. """ alice = np.array([[np.exp(1.0j*phi)*np.cos(theta/2), np.sin(theta/2)], [-np.sin(theta/2), np.exp(-1.0j*phi)*np.cos(theta/2)]]) bob = np.array([ [1, 0], [0, 1]]).astype(complex) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) return qc # test run # define the simulator simulator = Aer.get_backend('statevector_simulator') theta = np.pi phi = 0.0 qc = alice_plays_quantum(theta, phi) results = execute(qc, simulator, shots=1024).result().get_counts() results # calculating payoffs def get_payoff(counts): """ Calculate the reward for the players after the game ends. """ payoff_bob = [] payoff_alice = [] for strategy, prob in counts.items(): strategy_bob = int(strategy[1]) strategy_alice = int(strategy[0]) payoff_bob.append(prob * payoff_matrix[0][strategy_alice][strategy_bob]) payoff_alice.append(prob * payoff_matrix[0][strategy_bob][strategy_alice]) return sum(payoff_alice), sum(payoff_bob) # change the size on the quantum space to explore more quantum strategies space_size = 4 for phi in np.linspace(0, np.pi/2, space_size): for theta in np.linspace(0, np.pi, space_size): qc = alice_plays_quantum(theta, phi) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) print("theta = {}, phi = {}, results = {}, Alice's payoff {}, Bob's payoff {}".format(theta, phi, results, payoff_alice, payoff_bob)) print("Next Game") qc = alice_plays_quantum(theta = np.pi/2, phi = np.pi/4) job = simulator.run(qc, shots=2048) result = job.result() outputstate = result.get_statevector(qc, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) from qiskit.visualization import plot_histogram counts = result.get_counts() plot_histogram(counts) # probabilities of a certain outcome counts num_players = 2 def alice_bob_play_quantum(theta_a:float, phi_a:float, theta_b:float, phi_b:float, measure=False): """ Set up a quantum game. Both players have access to quantum strategies. Args: theta_a: Theta parameter for Alice's unitary. phi_a: Phi parameter for Alice's unitary. theta_b: Theta parameter for Bob's unitary. phi_b: Phi parameter for Bob's unitary. Returns: qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit', a constructed quantum circuit for the quantum game set up. """ alice = np.array([ [np.exp(1.0j*phi_a)*np.cos(theta_a/ 2), np.sin(theta_a / 2)], [-np.sin(theta_a / 2), np.exp(-1.0j*phi_a)*np.cos(theta_a / 2)]]) bob = np.array([ [np.exp(1.0j*phi_b)*np.cos(theta_b / 2), np.sin(theta_b / 2)], [-np.sin(theta_b / 2), np.exp(-1.0j*phi_b)*np.cos(theta_b / 2)]]) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) if measure: qc.measure_all() return qc alice_reward = 0 bob_reward = 0 draw = 0 space_size = 2 for phi1 in np.linspace(0, 2*np.pi, space_size): for theta1 in np.linspace(0, np.pi, space_size): for phi2 in np.linspace(0, 2*np.pi, space_size): for theta2 in np.linspace(0, np.pi, space_size): qc = alice_bob_play_quantum(theta1, phi1, theta2, phi2) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) # count winning if payoff_alice > payoff_bob: alice_reward += 1 elif payoff_bob > payoff_alice: bob_reward += 1 else: draw += 1 # print results print("theta_alice = {}, phi_alice = {}, theta_bob = {}, phi_bob = {}".format(theta1, phi1, theta2, phi2 )) print("results = {}, Alice's raward {}, Bob's reward {}".format(results, payoff_alice, payoff_bob)) print("Next Game") print("===================================================") print("In {} games Alice gets a higher reward than Bob.". format(alice_reward)) print("In {} games, Bob gets a higher reward than Alice.".format(bob_reward)) print("In {} games Alice and Bob get equal reward.".format(draw)) matrix = np.array([[1.0j, 0], [0, -1.0j]]) qc = QuantumCircuit(2) gate = UnitaryGate(Operator(matrix)) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() qc.append(gate, [0]) qc.append(gate, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) results = execute(qc, simulator, shots=1024).result().get_counts() alice_payoff, bob_payoff = get_payoff(results) print("Strategy: {}".format(results)) print("Alice's payoff is {}, Bob's payoff is {}".format(alice_payoff, bob_payoff)) import matplotlib.pyplot as plt space_size = 40 def payoff_plot(): """ Plot expected payoff distribution for Alice. """ x = np.linspace(1, -1, space_size) y = np.linspace(-1, 1, space_size) X, Y = np.meshgrid(x, y) Z = np.zeros(X.shape) for i in range(0,space_size): for inner in range(0, space_size): if X[inner][i] < 0 and Y[inner][i] < 0: qc = alice_bob_play_quantum(0, X[inner][i]*np.pi/2, 0, Y[inner][i]*np.pi/2) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice elif X[inner][i] >= 0 and Y[inner][i] >= 0: qc = alice_bob_play_quantum(X[inner][i]*np.pi, 0, Y[inner][i]*np.pi, 0) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice elif X[inner][i] >= 0 and Y[inner][i] < 0: qc = alice_bob_play_quantum(X[inner][i]*np.pi, 0, 0, Y[inner][i]*np.pi/2) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice elif X[inner][i] < 0 and Y[inner][i] >= 0: qc = alice_bob_play_quantum(0, X[inner][i]*np.pi/2, Y[inner][i]*np.pi, 0) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm, antialiased=True) ax.set(xlim=(-1, 1), ylim=(1, -1), xlabel="Bob strategy", ylabel='Alice strategy', zlabel="Alice's expected payoff") plt.show() payoff_plot() def build_qcir_three_parameters(theta1, phi1, lmbda, theta2, phi2): """ Set up a quantum game. Both players have access to quantum strategies space """ alice = np.array([ [np.exp(1.0j*phi1)*np.cos(theta1/2), 1.0j*np.exp(1.0j * lmbda) * np.sin(theta1/2)], [1.0j*np.exp(-1.0j * lmbda) * np.sin(theta1/2), np.exp(-1.0j*phi1)*np.cos(theta1/2)]]) bob = np.array([ [np.exp(1.0j*phi2)*np.cos(theta2/2), np.sin(theta2/2)], [-np.sin(theta2/2), np.exp(-1.0j*phi2)*np.cos(theta2/2)]]) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) return qc alice_reward = 0 bob_reward = 0 draw = 0 space_size = 4 for phi1 in np.linspace(-np.pi, np.pi, space_size): for theta1 in np.linspace(0, np.pi, space_size): for phi2 in np.linspace(-np.pi, np.pi, space_size): for theta2 in np.linspace(0, np.pi, space_size): for lmbda in np.linspace(-np.pi, np.pi, 2*space_size): qc = build_qcir_three_parameters(theta1, phi1, lmbda, theta2, phi2) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) # count winning if payoff_alice > payoff_bob: alice_reward += 1 elif payoff_bob > payoff_alice: bob_reward += 1 else: draw += 1 # print results print("theta_alice = {}, phi_alice = {}, theta_bob = {}, phi_bob = {}".format(theta1, phi1, theta2, phi2 )) print("results = {}, Alice's payoff {}, Bob's payoff {}".format(results, payoff_alice, payoff_bob)) print("Next Game") print("===================================================") print("In {} games Alice gets a higher reward than Bob.". format(alice_reward)) print("In {} games, Bob gets a higher reward than Alice.".format(bob_reward)) print("In {} games Alice and Bob get equal reward.".format(draw)) !python3 -m pip install -q qiskit-ibm-provider from qiskit.providers.ibmq import least_busy from qiskit_ibm_provider import IBMProvider provider = IBMProvider() # ==================================== # pass IBM API Token # ==================================== provider.save_account(token=, overwrite=True) small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator) least_busy(small_devices) backend = least_busy(small_devices) qc = alice_bob_play_quantum(theta_a = 0, phi_a = 0, theta_b = np.pi/2, phi_b = 0, measure=True) job = execute(qc, backend, optimization_level=2) result = job.result() counts = result.get_counts() counts plot_histogram(counts) job = execute(qc, backend=Aer.get_backend('statevector_simulator'), shots=1024) result = job.result() counts = result.get_counts() print(counts) plot_histogram(counts) from functools import reduce from operator import add from qiskit import quantum_info as qi def mixed_strategy(alpha_a:float, alpha_b:float): """ Set up a quantum game. Both players have access to quantum strategies. Args: theta_a: Theta parameter for Alice's unitary. phi_a: Phi parameter for Alice's unitary. theta_b: Theta parameter for Bob's unitary. phi_b: Phi parameter for Bob's unitary. Returns: qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit', a constructed quantum circuit for the quantum game set up. """ qc = QuantumCircuit(2) # Alice strategies unitary1_a = np.eye(2).astype(complex) unitary2_a = np.array([[-1.0j, 0], [0, 1.0j]]) # Bob's strategies unitary1_b = np.array([[0, 1], [-1, 0]]).astype(complex) unitary2_b = np.array([[0, -1.0j], [-1.0j, 0]]).astype(complex) # define probabilities for Alice p1_a = np.cos(alpha_a / 2) ** 2 p2_a = np.sin(alpha_a/ 2) ** 2 # define probabilities for Bob p1_b = np.cos(alpha_b / 2) ** 2 p2_b = np.sin(alpha_b/ 2) ** 2 # define the set of actions and their probability distribution. mixed_strategy = [[(p1_a, unitary1_a), (p2_a, unitary2_a)], [(p1_b, unitary1_b), (p2_b, unitary2_b)]] identity = np.eye(2) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0, 1]) rho = qi.DensityMatrix.from_instruction(qc) for index, strategy in enumerate(mixed_strategy): rho = reduce(add, (prob * rho.evolve(np.kron(*[strat if index == player else identity for player in range(num_players)])) for prob, strat in strategy)) rho = rho.evolve(Operator(J.conj().T)) return rho.probabilities() payoff_matrix =[[[3, 0], [5, 1]], [[3, 5], [0, 1]]] for alpha_a in np.linspace(0, np.pi, 4): for alpha_b in np.linspace(0, np.pi, 2): print("alpha_a = ", alpha_a) print("alpha_b = ", alpha_b) prob = mixed_strategy(alpha_a, alpha_b) print("prob = ", prob) alice_matrix = np.reshape(payoff_matrix[0], (1,4)) bob_matrix = np.reshape(payoff_matrix[1], (1,4)) print("Alice's Payoff = ", np.round(np.dot(prob, alice_matrix[0]), 3)) print("Bob's Payoff = ", np.round(np.dot(prob, bob_matrix[0]),3)) print("=======================") # probability of 1/2 and 1/2 yeilds the payoffs of 2.5 for each player. prob = mixed_strategy(np.pi/2, np.pi/2) print("prob = ", prob) alice_matrix = np.reshape(payoff_matrix[0], (1,4)) bob_matrix = np.reshape(payoff_matrix[1], (1,4)) print("Alice's Payoff = ", np.round(np.dot(prob, alice_matrix[0]), 3)) print("Bob's Payoff = ", np.round(np.dot(prob, bob_matrix[0]),3))
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
!pip install qiskit[visualization] # Imports for Qiskit from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit import * from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.visualization import plot_histogram import numpy as np # Various imports import numpy as np from copy import deepcopy from matplotlib import pyplot as plt # IBMQ.save_account('Put your token') # provider = IBMQ.load_account() # IBMQ.get_provider(hub='ibm-q', group='open', project = 'main') # Create the various registers needed clock = QuantumRegister(2, name='clock') input = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') measurement = ClassicalRegister(2, name='c') # Create an empty circuit with the specified registers circuit = QuantumCircuit(ancilla, clock, input, measurement) circuit.barrier() circuit.draw(output='mpl') def qft_dagger(circ, q, n): circ.h(clock[1]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): circ.cu1(-np.pi/float(2**(k-j)), q[k], q[j]); circ.h(clock[0]); circ.swap(clock[0], clock[1]); def qft(circ, q, n): circ.swap(clock[0], clock[1]); circ.h(clock[0]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): circ.cu1(np.pi/float(2**(k-j)), q[k], q[j]); circ.h(clock[1]); def qpe(circ, clock, target): circuit.barrier() # e^{i*A*t} circuit.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input, label='U'); # e^{i*A*t*2} circuit.cu(np.pi, np.pi, 0, 0, clock[1], input, label='U2'); circuit.barrier(); # Perform an inverse QFT on the register holding the eigenvalues qft_dagger(circuit, clock, 2) def inv_qpe(circ, clock, target): # Perform a QFT on the register holding the eigenvalues qft(circuit, clock, 2) circuit.barrier() # e^{i*A*t*2} circuit.cu(np.pi, np.pi, 0, 0, clock[1], input, label='U2'); #circuit.barrier(); # e^{i*A*t} circuit.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], input, label='U'); circuit.barrier() def hhl(circ, ancilla, clock, input, measurement): qpe(circ, clock, input) circuit.barrier() # This section is to test and implement C = 1 circuit.cry(np.pi, clock[0], ancilla) circuit.cry(np.pi/3, clock[1], ancilla) circuit.barrier() circuit.measure(ancilla, measurement[0]) circuit.barrier() inv_qpe(circ, clock, input) # State preparation. (various initial values) # (restart from the second cell if changed) intial_state = [0,1] # intial_state = [1,0] # intial_state = [1/np.sqrt(2),1/np.sqrt(2)] # intial_state = [np.sqrt(0.9),np.sqrt(0.1)] circuit.initialize(intial_state, 3) circuit.barrier() # Perform a Hadamard Transform circuit.h(clock) hhl(circuit, ancilla, clock, input, measurement) # Perform a Hadamard Transform circuit.h(clock) circuit.barrier() circuit.measure(input, measurement[1]) circuit.draw('mpl',scale=1) #print(circuit) # Execute the circuit using the simulator simulator = qiskit.BasicAer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator, shots=1000) #Get the result of the execution result = job.result() # Get the counts, the frequency of each answer counts = result.get_counts(circuit) # Display the results plot_histogram(counts) bcknd = Aer.get_backend('statevector_simulator') job_sim = execute(circuit, bcknd) result = job_sim.result() o_state_result = result.get_statevector(circuit, decimals=3) print(o_state_result) provider.backends() # Choose the backend on which to run the circuit backend = provider.get_backend('ibmq_santiago') from qiskit.tools.monitor import job_monitor # Execute the job job_exp = execute(circuit, backend=backend, shots=8192) # Monitor the job to know where we are in the queue job_monitor(job_exp, interval = 2) # Get the results from the computation results = job_exp.result() # Get the statistics answer = results.get_counts(circuit) # Plot the results plot_histogram(answer) # Auto generated circuit (almost) matching the form from the Wong paper (using cu gates) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister beta = 0 cycle_time = 0.5 qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr, name="main") intial_state = [0,1] qc.initialize(intial_state, qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t} qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, qr[1], qr[3], label='U'); # e^{i*A*t*2} qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[2]) qc.cu1(-3.14159/2, qr[1], qr[2]) qc.h(qr[1]) qc.swap(qr[2], qr[1]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.cry(3.14159, qr[1], qr[0]) qc.cry(3.14159/3, qr[2], qr[0]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.swap(qr[2], qr[1]) qc.h(qr[1]) qc.cu1(3.14159/2, qr[1], qr[2]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t*2} qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); # e^{i*A*t} qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, qr[1], qr[3], label='U'); qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.measure(qr[0], cr[0]) qc.measure(qr[3], cr[3]) from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") # Use Aer qasm_simulator job = execute(qc, backend, shots=1000) result = job.result() counts = result.get_counts(qc) print("Total counts are:", counts) # Draw the circuit print(qc) #qc.draw('mpl',scale=1) # Plot a histogram from qiskit.visualization import plot_histogram plot_histogram(counts) qc.draw('mpl',scale=1) # Same example as above but using the U3 and U1 gates instead of U1 # Initialize with RY instead of "initialize()" from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister beta = 1 qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr, name="main") # intial_state = [0,1] # qc.initialize(intial_state, qr[3]) qc.ry(3.14159*beta, qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t} # qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, qr[1], qr[3], label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(3*3.14159/4, qr[1]) qc.cu3(3.14159/2, -3.14159/2, 3.14159/2, qr[1], qr[3]) # e^{i*A*t*2} # qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); qc.cu3(3.14159, 3.14159, 0, qr[2], qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[2]) qc.cu1(-3.14159/2, qr[1], qr[2]) qc.h(qr[1]) qc.swap(qr[2], qr[1]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.cry(3.14159, qr[1], qr[0]) qc.cry(3.14159/3, qr[2], qr[0]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.swap(qr[2], qr[1]) qc.h(qr[1]) qc.cu1(3.14159/2, qr[1], qr[2]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t*2} # qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); qc.cu3(3.14159, 3.14159, 0, qr[2], qr[3]) # e^{i*A*t} # qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, qr[1], qr[3], label='U'); # The CU gate is equivalent to a CU1 on the control bit follwed by a CU3 qc.u1(-3*3.14159/4, qr[1]) qc.cu3(3.14159/2, 3.14159/2, -3.14159/2, qr[1], qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.measure(qr[0], cr[0]) qc.measure(qr[3], cr[3]) # qc.measure(qr, cr) from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") # Use Aer qasm_simulator job = execute(qc, backend, shots=1000) result = job.result() counts = result.get_counts(qc) print("Total counts are:", counts) # Draw the circuit print(qc) # Plot a histogram from qiskit.visualization import plot_histogram plot_histogram(counts) qc.draw('mpl',scale=1)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver() problem = driver.run() print(problem) from qiskit_nature.second_q.problems import ElectronicBasis driver.run_pyscf() problem = driver.to_problem(basis=ElectronicBasis.MO, include_dipole=True) print(problem.basis) ao_problem = driver.to_problem(basis=ElectronicBasis.AO) print(ao_problem.basis) from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem qcschema = driver.to_qcschema() ao_problem = qcschema_to_problem(qcschema, basis=ElectronicBasis.AO) from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema basis_transformer = get_ao_to_mo_from_qcschema(qcschema) mo_problem = basis_transformer.transform(ao_problem) print(mo_problem.basis) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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/AllenGabrielMarchen/HHL_implementation
AllenGabrielMarchen
#run.py ''' 참고 논문 :Low Complexity Quantum Matrix Inversion A기gorithm for non-Hermitian Matrices 해당 논문에서, non-Hermitian인 경우에 Hermitian으로 바꾸기 위해서 2*2의 행렬을 4*4 행렬로 바꾸었다. 밑의 주어진 코드를 통해 이해해보도록하자. A = np.array([[2,-1],[1,4]])의 꼴로 주어진 A는 non-Hermitian의 꼴이다. 그러므로, 이를 def main - #Check if Hermitian 파트에서 다음과 같은 코드로 아래와 같은 Hermitian으로 바꾸게 된다. (코드) A = np.vstack((np.hstack((np.zeros_like(A),A)),np.hstack((A.T, np.zeros_like(A))))) 이에 맞게 나머지 x와 b의 행렬의 형태도 4*1의 형태로 바꾸어주어야 한다. 즉, x = [ 0, 0, x1, x2]의 꼴로, 그리고 b는 [1 1 0 0]의 꼴로 바꾸어야 한다. (결과) [[ 0 0 2 -1] [ 0 0 1 4] [ 2 1 0 0] [-1 4 0 0]] ''' import numpy as np from scipy.linalg import expm from qiskit.extensions import UnitaryGate from qiskit.circuit.add_control import add_control from qiskit import Aer import circuit import hhl import tools def main(A,b,backend,shots,t,n_l,delta): #Check if Hermitian #위에서 언급한 바대로 non-Hermitian matrice인 A에 대해서 Hermitian으로 바꿔주는 과정 if np.allclose(A,A.T) == False: print("Given A matrice is not Hermitian.") print("Given Matrices will be transformed into Hermitian formation.") A = np.vstack((np.hstack((np.zeros_like(A),A)),np.hstack((A.T, np.zeros_like(A))))) # Hermitian의 꼴로 바꿈 #A의 shape와 동일한 zero array를 생성하고, A의 왼쪽에 배치, horizontal 방향도 마찬가지. b = np.hstack((b,np.zeros_like((np.shape(A)[0]-np.shape(b)[0],1)))) i = complex(0,1) #complex(real part, imaginary part) U = expm(i*A*t) #여기서 A가 행렬로 주어졌기 때문에, 행렬을 exp에 올리기 위해서는 expm이라는 scipy 패키지가 필요함. U_gate = UnitaryGate(U) #위에서 구성한 U라는 행렬로써 Unitary gate를 구성할 수 있음. (4*4) 행렬 CU = add_control(U_gate,1,ctrl_state=None, label="CU") #CU라는 게이트 이름을 label에 저장 #control 되는 경우의 state를 지정 -> 해당사항 없음 #두번째 인자는 컨트롤 큐빗의 개수를 지정함. n_b = int(np.log2(U.shape[0])) #Ax =b의 꼴이고, b는 4*1의 shape이므로, A의 행의 개수와 동일함. 따라서, U의 행렬의 행의 개수와 동일함. #행의 개수에 log2를 취하면 필요한 n_b의 값을 구할 수 있음. #각각 HHL 알고리즘이 구현된 방식으로 결과를 얻는다 My_HHL_result = hhl.My_HHL(CU,b,n_l,n_b,backend,delta,shots,A,details = True,chevyshev = False) print("\n") qiskit_result = hhl.qiskit_HHL(A,b) print("\n") classical_result = hhl.classical_HHL(A,b) print("\n") #For normalized answer print("<Un - normalized Case Comparision>") print('Qiskit Error : {0}'.format(np.linalg.norm(qiskit_result[1]-classical_result[1]))) print('My HHL Error : {0}'.format(np.linalg.norm(My_HHL_result[1]-classical_result[1]))) print("\n") print("<Normalized Case Comparision>") print('Qiskit Error : {0}'.format(np.linalg.norm(qiskit_result[0]-classical_result[0]))) print('My HHL Error : {0}'.format(np.linalg.norm(My_HHL_result[0]-classical_result[0]))) if __name__ == "__main__": #setups A = np.array([[2,-1],[1,4]]) #non-Hermitian인 경우의 행렬에 대한 저장 b = np.array([1,1]) backend = Aer.get_backend('aer_simulator') shots = 8192 t = np.pi*2/16 n_l = 3 #QPE 상에서 n_ㅣ는 하다마드로 초기화 되는 부분 delta = 1/16*(2**(n_l-1)) main(A,b,backend,shots,t,n_l,delta) #my_hhl.py from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import numpy as np import circuit as circ import tools def My_HHL(CU,b,n_l,n_b,backend,delta,shots,A,details = True,chevyshev = False): #circuit initialization #qubit의 개수들을 정의한다. n_f = 1 nb = int(np.log2(b.shape)) #정의된 qubit의 개수들을 기반으로 양자 레지스터들을 생성한다. nl_rg = QuantumRegister(n_l, "l") nb_rg = QuantumRegister(n_b, "b") na_rg = QuantumRegister(n_l, "a") nf_rg = QuantumRegister(n_f, "f") #고전 레지스터들을 생성한다. cf = ClassicalRegister(n_f, "classical_f") cb = ClassicalRegister(n_b, "classical_b") #생성된 레지스터들을 기반으로 비어있는 양자회로를 설치한다. qc = QuantumCircuit(nf_rg,nl_rg, nb_rg, na_rg, cf, cb) #isometry 패키지를 이용해서 normalized 된 b 행렬을 양자회로에 인코딩한다. #즉. isometry라는 메서드는 어떤 행렬을 양자회로에 업로드 해주는 역할을 한다. qc.isometry(b/np.linalg.norm(b), list(range(nb)), None) qc.barrier(nf_rg,nl_rg,nb_rg) #details는 양자 회로의 어떠한 instruction들을 세부적으로 표현할 것인지 아닌지에 대한 설정이다. if details == True: #compose를 이용해서 위에서 생성한 레지스터에 붙이는 경우, instruction 내의 모든 회로가 다 보임. #또한, 더 많은 register들이 있는 회로에 적은 register들이 있는 회로를 가져다 붙이기 위해서는 compose에 인자로써 register가 적용될 순서를 명시해주어야함. #구성한 circ 패키지 내에 있는 회로들을 compose를 이용해 가져다 붙이는 과정 #QPE -> Eigenvalue_inversion -> QPE_dagger 순으로 회로를 가져다 붙임 qc = qc.compose(circ.QPE(n_l,n_b,CU),nl_rg[:]+nb_rg[:]) qc = qc.compose(circ.Eigenvalue_inversion(n_l,delta,chevyshev),[nl_rg[2]]+[nl_rg[1]]+[nl_rg[0]]+nf_rg[:]) qc = qc.compose(circ.QPE_dagger(n_l,n_b,CU),nl_rg[:]+nb_rg[:]) else: qc.append(circ.QPE(n_l,n_b,CU),nl_rg[:]+nb_rg[:]) qc.append(circ.Eigenvalue_inversion(n_l),[nl_rg[2]]+[nl_rg[1]]+[nl_rg[0]]+nf_rg[:]) qc.append(circ.QPE_dagger(n_l,n_b,CU),nl_rg[:]+nb_rg[:]) qc.barrier(nf_rg[:]+nl_rg[:]+nb_rg[:]) #레지스터의 이름과 그 안에 있는 큐비트들의 순서들을 조합하여 한번에 barrier를 세울 수 있음. #측정 실시 파트 qc.measure(nf_rg,cf) qc.measure(nb_rg,cb) answer = circ.measurement(qc,n_l,n_b,CU,backend,shots) qc.draw(output = 'mpl').savefig('./outputs/qc_HHL') #Obtaining Normalized answer normalized_result = tools.normalize_vector(answer, n_b) #Obtaining Real Answer ''' 즉, normalized된 x값을 집어넣고, Ax = b 꼴에서 좌변을 계산한 후에 b와 몇배 차이인가를 알아내는 과정 여기서 몇배 차이를 나타내는게 constant임. constant는 b와 같은 shape를 갖게 되고, ensemble로 얻어지는 양자회로의 특성상 explicit한 결과가 주어지지 않는다. 따라서, constant 벡터의 모든 요소들의 평균으로서 몇배 차이인지를 나타낸다. ''' constant = b/(A @ normalized_result) constant = (constant[0]+constant[1])/2 constant = np.mean(constant) #결과 출력 파트 print('<My_HHL>') print('Normalized Answer : {0}'.format(normalized_result)) print('Un-normalized Answer : {0}'.format(normalized_result * constant)) print('Normalize Constant: ' ,constant) return [normalized_result,normalized_result * constant] #classical_hhl.py from qiskit.algorithms.linear_solvers.numpy_linear_solver import NumPyLinearSolver import numpy as np def classical_HHL(A,b): #NumpyLinearSolver를 이용해서 주어진 행렬방정식을 풀어낸다. ''' 참고로, 여기선 un-normalized된 해로써 결과값이 나온다는 사실은 자명하다. 하지만 여기서 나온 해를 normalize를 통해서 my_hhl과 qiskit_hhl에서 내놓은 normalized된 해와의 차이를 분석하기 위해서 normalized Answer 또한 작성했다. ''' sol = NumPyLinearSolver().solve(A, b) sol_state = sol.state norm_state = sol_state/np.linalg.norm(sol_state) print('<Classical case using Numpy>') if np.shape(b)[0] == 2: sol_state = np.pad(sol_state,(2,0)) norm_state = np.pad(norm_state,(2,0)) print('Un-normalized Classical Numpy answer : {0}'.format(sol_state,(2,0))) print('Normalized Classical Numpy answer : {0}'.format(norm_state,(2,0))) return [norm_state,sol_state] #qiskit_hhl.py from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer from qiskit.quantum_info import Statevector from qiskit.algorithms.linear_solvers.hhl import HHL import numpy as np def qiskit_HHL(A,b): #해당 내용은 https://qiskit.org/textbook/ch-applications/hhl_tutorial.html의 solving 과정을 참고하였음 backend = Aer.get_backend('aer_simulator') #qiskit HHL 코드를 불러옴 hhl = HHL(quantum_instance=backend) #A, b에 대해서 HHL 회로를 구성 solution = hhl.solve(A, b) #만들어진 회로를 그림으로 저장 solution.state.draw("mpl").savefig("./outputs/HHL_circuit_qiskit.png") #연산된 상태를 상태 벡터의 형태로 결과를 얻음 naive_sv = Statevector(solution.state).data #qubit수를 확인 num_qubit = solution.state.num_qubits #상태 벡터에서 필요한 상태만을 골라서 저장함 naive_full_vector = np.array([naive_sv[2**(num_qubit-1)+i] for i in range(len(b))]) #실수 부분만 취함 naive_full_vector = np.real(naive_full_vector) #얻어진 벡터를 normalize하여 반환 normalized_result = naive_full_vector/np.linalg.norm(naive_full_vector) #마찬가지로 주어진 해를 통해 constant를 구함. constant = b/(A @ normalized_result) constant = (constant[0]+constant[1])/2 constant = np.mean(constant) print('<Qiskit_HHL>') print('Normalized Qiskit Answer : {0}'.format(normalized_result)) print('Un-normalized Qiskit Answer : {0}'.format(normalized_result * constant)) print('Normalize Constant: ' ,constant) return [normalized_result,normalized_result * constant] #circuit_parts.py from qiskit.circuit.library.arithmetic.exact_reciprocal import ExactReciprocal from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev from qiskit import QuantumCircuit, QuantumRegister,Aer import numpy as np def qft_dagger(n_l): # <qft를 구현하는 과정에 있어서 SWAP gate에 대한 참고사항> - issue 해결에 대한 report 2022-09-02 # SWAP 게이트를 걸어주는 목적은 qiskit은 qubit을 반대방향으로 읽기 때문임. # 하지만, SWAP 게이트를 위와 같은 이유로 걸어주게 된다고 하면, # HHL 알고리즘 상에서 Eigeninversion 단계에서 문제가 생기게 됨. # 즉, Eigeninversion에서는 SWAP이 된 상태를 인지하지 못하고 연산을 실시하여 잘못된 연산이 나오게 됨. """n-qubit QFTdagger the first n qubits in circ""" nl_rg = QuantumRegister(n_l, "l") qc = QuantumCircuit(nl_rg) # Don't forget the Swaps! #QFT의 역연산은 곧 QFT_dagger임을 기억하자. for j in reversed(range(n_l)): qc.h(j) for m in reversed(range(j)): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.name = "QFT†" #display(qc.draw(output = 'mpl')) return qc def QPE(n_l,n_b,CU): #circuit initialization for HHL nl_rg = QuantumRegister(n_l, "l") nb_rg = QuantumRegister(n_b, "b") #QuantumRegister(size=None, name=None, bits=None) qc = QuantumCircuit(nl_rg,nb_rg) #display(qc.draw(output = 'mpl')) qc.h(nl_rg) qc.barrier(nl_rg[:]+nb_rg[:]) for l in range(n_l): for power in range(2**(l)): qc.append(CU, [nl_rg[l],nb_rg[0],nb_rg[1]]) #첫번째 큐비트는 2^0번, 이후 2^n꼴로 돌아가게 설계됨. #https://qiskit.org/documentation/stubs/qiskit.circuit.ControlledGate.html append의 예제. #즉, append의 첫번째 인자는 gate, 두번쨰 인자의 첫번째 요소는 control qubit, 이후 인자의 요소는 target qubit. qc.barrier(nl_rg[:]+nb_rg[:]) qc.append(qft_dagger(n_l),nl_rg[:]) qc.barrier(nl_rg[:]+nb_rg[:]) qc.name = "QPE" #display(qc.draw(output = 'mpl')) return qc def QPE_dagger(n_l,n_b,CU): qc = QPE(n_l,n_b,CU) qc = qc.inverse() #여기서 inverse함수는 모든 rotation 각도까지도 반대로 입력해줌을 확인하였음. #QPE dagger는 그저, QPE의 역과정이라고 생각하면 된다. 단, 각도는 반대방향이어야 함. #따라서 여기서 inverse함수를 이용하여 QPE의 역과정, 즉, QPE dagger를 실시하였음 qc.name = 'QPE†' return qc def Eigenvalue_inversion(n_l,delta,chevyshev = False): #Chevyshev 근사를 이용한 풀이방법. #Qiskit에서 제공한 HHL 알고리즘 상에서는 Chevyshev 근사를 이용한 부분이 있었다. #일단 Chevyshev 근사를 이용하는 경우, 기존 Taylor 근사보다 훨씬 빠르게 급수에 수렴한다는 장점이 있다. #참고 문헌 : https://freshrimpsushi.github.io/posts/chebyshev-expansion/ #여기서는 위의 표현한 cos(theta)에 대한 표현을 Chevyshev근사를 이용해 theta값을 알아내겠다는 접근방법이다. #하지만, 근사결과가 좋지 못하다는 점 때문에 Chevyshev 근사를 이용하는 대신에 직접 exact한 theta값을 알아내는 ExactReciprocal을 이용하였다. if chevyshev == True: print("Maybe using Chevyshev approximation is not accurate.") #Using Chebychev Approx. (not recommended!) nl_rg = QuantumRegister(n_l, "l") na_rg = QuantumRegister(n_l, "a") nf_rg = QuantumRegister(1, "f") qc = QuantumCircuit(nl_rg, na_rg, nf_rg) f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [1,2,3,4], n_l #degree : 함수를 polynomial로 근사할 떄, 최고차항 정의 #breakpoints는 구간을 나누는 느낌. : 근사를 할 떄, 다항식을 어떤 구간에서 나눠서 사용할 지 #l : eigenvalue를 표현 #f : rotation #a : ancila pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc.append(pw_approximation,nl_rg[:]+[nf_rg[0]]+na_rg[:]) #range(nl*2+1)) qc.name = 'Chevyshev_inversion' return qc else: qc = ExactReciprocal(n_l, delta, neg_vals = True) qc.name = 'Reciprocal_inversion' return qc #measurement.py ''' 주어진 회로에 대해 backend를 가지고서 시뮬레이션을 하기 위한 모듈 ''' from qiskit import QuantumCircuit, transpile, assemble from qiskit.visualization import plot_histogram def measurement(qc,n_l,n_b,CU,backend,shots): t = transpile(qc, backend) qobj = assemble(t, shots=shots) results = backend.run(qobj).result() answer = results.get_counts() plot_histogram(answer, title="Output Histogram").savefig('./outputs/output_histogram.png',facecolor='#eeeeee') return answer #normalization.py import numpy as np #양자 회로를 통해서 얻어진 결과(dictionary)를 통해서 normalize된 결과 벡터 x를 구하는 함수 def normalize_vector(answer, nb): #nb register에서 얻어질 수 있는 상태들을 dictionary의 key의 형태로 만들어 저장한다. possible_states = [] #가능한 모든 상태들을 저장하기 위한 list for s in range(2**(nb)): possible_states.append(format(s, "b").zfill(nb)) #nb만큼의 자릿수에 대해서 binary의 형태로 모든 경우의 수를 생성. #print(answer) #flag register를 측정한 결과가 1이 나온 경우에 대해서 nb register의 결과를 순서대로 추가한다. available_result = [] for i in possible_states: for key in answer.keys(): #정답의 key 즉, 상태들을 받아옴. if key[0:2] == i: #얻은 상태들이 가능한 상태에 존재한다면, if int(key[-1]) == 1: #그리고 마지막 자릿수, f_register가 1의 값을 갖는다면, available_result.append(answer[key]) #avaliable_result에 f가 1인 상태들이 나온 횟수를 append 하자. else: pass else: pass #확률 분포를 상태 벡터의 형식으로 바꾸기 위해서 제곱근을 취한다. available_result = np.sqrt(np.array(available_result)) #확률 진폭은 계수의 제곱의 형태로 나오기 때문. #벡터의 크기가 1이 되도록 normalize해준다. normalized_result = available_result/np.linalg.norm(available_result) return normalized_result
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np import json import csv # Array of JSON Objects # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) # genera las distancias index = -1 for sample in UNIFORM_CONVERGENCE_SAMPLE: mean = sample["mean"] index += 1 distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"])) UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state header = ['instance', 'iteration', 'distance'] length_instances = 2 with open('qaoa_multiple_distance.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) for i in range(length_instances): job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution() iteration = 0 for sample in UNIFORM_CONVERGENCE_SAMPLE: iteration += 1 mean = sample["mean"] distance = sample["distance_pgs"] state = 0 for probability in sample["probabilities"]: state += 1 # write the data data = [iteration, state, probability, mean] writer.writerow(data) writer_q.writerow([iteration, distance])
https://github.com/BOBO1997/osp_solutions
BOBO1997
# -*- 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. import numpy as np from qiskit import compiler, BasicAer, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller def convert_to_basis_gates(circuit): # unroll the circuit using the basis u1, u2, u3, cx, and id gates unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id']) pm = PassManager(passes=[unroller]) qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm) return qc def is_qubit(qb): # check if the input is a qubit, which is in the form (QuantumRegister, int) return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int) def is_qubit_list(qbs): # check if the input is a list of qubits for qb in qbs: if not is_qubit(qb): return False return True def summarize_circuits(circuits): """Summarize circuits based on QuantumCircuit, and four metrics are summarized. Number of qubits and classical bits, and number of operations and depth of circuits. The average statistic is provided if multiple circuits are inputed. Args: circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits """ if not isinstance(circuits, list): circuits = [circuits] ret = "" ret += "Submitting {} circuits.\n".format(len(circuits)) ret += "============================================================================\n" stats = np.zeros(4) for i, circuit in enumerate(circuits): dag = circuit_to_dag(circuit) depth = dag.depth() width = dag.width() size = dag.size() classical_bits = dag.num_cbits() op_counts = dag.count_ops() stats[0] += width stats[1] += classical_bits stats[2] += size stats[3] += depth ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format( i, width, classical_bits, size, depth, op_counts)]) if len(circuits) > 1: stats /= len(circuits) ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format( stats[0], stats[1], stats[2], stats[3])]) ret += "============================================================================\n" return ret
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
import weylchamber from qiskit.converters import circuit_to_dag from qiskit import transpile from qiskit.transpiler import PassManager from qiskit.transpiler.passes import ConsolidateBlocks, Collect2qBlocks from qiskit.quantum_info import Operator from qiskit.circuit.library import SwapGate, CXGate from tqdm import tqdm from slam.utils.circuit_suite import benchmark_lambdas, benchmark_lambdas_no_qv # benchmark_lambdas[9](6).draw(output="mpl") from qiskit.transpiler import CouplingMap map_option = ["a2a", "lattice"][1] if map_option == "a2a": coupling_map = CouplingMap.from_full(16) elif map_option == "lattice": coupling_map = CouplingMap.from_grid(4, 4) coordinate_list = [] for lambda_item in tqdm(benchmark_lambdas[0:1]): # load qiskit transpiler with pass for coupling map induce_swaps = lambda qc: transpile( qc, coupling_map=coupling_map, optimization_level=3 ) circuit = lambda_item(16) circuit = induce_swaps(circuit) # Proceed pm = PassManager() pm.append(Collect2qBlocks()) pm.append(ConsolidateBlocks(force_consolidate=True)) transp_circuit = pm.run(circuit) dag = circuit_to_dag(transp_circuit) for gate in dag.collect_2q_runs(): assert len(gate) == 1 # should be 1 bc of consolidation d = Operator(gate[0].op).data try: coordinate_list.append(weylchamber.c1c2c3(d)) except ValueError: # seems like some SWAPs were getting a rounding error and couldn't be converted to a Weyl chamber coordinate # XXX manually add a SWAP - it only happens two or three times total anyway coordinate_list.append(weylchamber.c1c2c3(SwapGate().to_matrix())) coordinate_freq = {i: coordinate_list.count(i) for i in set(coordinate_list)} # print(coordinate_freq[weylchamber.c1c2c3(SwapGate().to_matrix())]) # print(coordinate_freq[weylchamber.c1c2c3(CXGate().to_matrix())]) 679 / (679 + 717) import matplotlib.pyplot as plt from slam.utils.visualize import fpath_images plt.close() fig = plt.figure() ax = fig.add_subplot(111, projection="3d") from weylchamber import WeylChamber w = WeylChamber() ## for k, v in coordinate_freq.items(): ax.scatter3D(*k, s=0.75 * v, c="k") ## w.labels = {} w.render(ax) # save as pdf and svg plt.savefig(f"{fpath_images}/shot_chart_{map_option}.pdf", format="pdf") plt.savefig(f"{fpath_images}/shot_chart_{map_option}.svg", format="svg") fig.show()
https://github.com/mballarin97/mps_qnn
mballarin97
# This code is part of qcircha. # # 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. """ Uses the simulation results from `entanglement_characterization.py` to evaluate the expressibility of a QNN, using the definition in [Sim et al. 2019](https://arxiv.org/abs/1905.10876). Such measure requires to construct a histogram of fidelities of states generated by the QNN, to be compared with random states sampled from the uniform Haar distribution. The default number of bins of the histogram is 100, the number of fidelities used to build the histogram is 4950 ( = (100**2 - 100) / 2), obtained by all possible different combinations of the 100 states generated by `entanglement_characterization.py` """ import time import json import os import sys import numpy as np import scipy as sp from qiskit import Aer import matplotlib.pyplot as plt import seaborn as sns sns.set_theme() from qcircha.circuits import * from qcircha.circuit_selector import pick_circuit from qcircha.entanglement_characterization import entanglement_characterization from qcircha.entanglement.haar_entanglement import haar_discrete from qcircha.utils import removekey def kl_divergence(p, q, eps = 1e-20) : """ Compute the KL divergence between two probability distributions Parameters ---------- p : array-like of floats First probability distribution q : array-like of floats Second probability distribution Returns ------- float KL divergence of p and q """ # Eliminate divergences (check if safe to do) q = np.array([max(eps, q_j) for q_j in q]) p = np.array([max(eps, p_j) for p_j in p]) #return np.sum(p * np.log(p/q)) return sp.stats.entropy(p, q, base=np.e) def eval_kl(fidelities, n_bins=20, num_qubits=4): """ Evaluate KL divergence Parameters ---------- fidelities : _type_ _description_ n_bins : int, optional _description_, by default 20 num_qubits : int, optional _description_, by default 4 Returns ------- _type_ _description_ """ discrete_haar = np.array([haar_discrete(x, 1/n_bins, 2 ** num_qubits) for x in np.linspace(0, 1, n_bins + 1)[:-1]]) y, _ = np.histogram(fidelities, range=(0, 1), bins=n_bins) y = y / np.sum(y) return kl_divergence(y, discrete_haar), y, discrete_haar def inner_products(state_list, rep): """ """ inner_p = [] num_tests = len(state_list[0, :, 0]) for i in range(num_tests): for j in range(i): tmp = np.abs(state_list[rep, i, :] @ np.conjugate(state_list[rep, j, :])) ** 2 inner_p.append(tmp) return np.array(inner_p) def compute_espressivity(num_qubits, repetitions, feature_map = None, var_ansatz=None, alternate = True, backend='Aer', path='./data/expr/', plot=False, save=False, max_bond_dim=None): if isinstance(repetitions, int): reps = range(1, repetitions + 1) else: reps = repetitions # Generate random states from QNN st_list = [] for num_reps in reps: ansatz = pick_circuit(num_qubits, num_reps, feature_map=feature_map, var_ansatz=var_ansatz, alternate=alternate) _, _, _, statevectors = entanglement_characterization(ansatz, backend=backend, get_statevector=True, max_bond_dim = max_bond_dim) statevectors = np.array(statevectors) st_list.append(statevectors) print("") st_list = np.array(st_list) # Evaluate inner products res = [] for idx, rep in enumerate(reps): res.append(inner_products(st_list, idx)) res = np.array(res) # Build histogram of distribution and evaluate KL divergence with Haar n_bins = 100 num_qubits = ansatz.metadata['num_qubits'] expressibility = [eval_kl(data, n_bins=n_bins, num_qubits = num_qubits)[0] for data in res] if save == True: # Save data if not os.path.isdir(path): os.makedirs(path) timestamp = time.localtime() save_as = time.strftime("%Y-%m-%d_%H-%M-%S", timestamp) + '_' + str(np.random.randint(0, 1000)) name = os.path.join(path, save_as) # Save details of the ansatz meta = dict({"n_bins": n_bins, "backend": backend}) circ_data = removekey(ansatz.metadata, ["num_reps", "params"]) meta.update(circ_data) # add metadata from the ansatz with open(name+'.json', 'w') as file: json.dump(meta, file, indent=4) expressibility = np.array(expressibility, dtype=object) np.save(name, expressibility, allow_pickle=True) if plot == True: fig = plt.figure(figsize=(9.6, 6)) plt.ylim([1e-3, 1]) plt.ylabel(r"$Expr. D_{KL}$") plt.xlabel("Repetitions") plt.yscale('log') plt.plot(reps, expressibility, marker='o', ls='--') plt.tight_layout() plt.show() return expressibility if __name__ == '__main__': # Fixing seed for reproducibility # seed = 120 # np.random.seed(seed) num_qubits = 6 feature_map = 'ZZFeatureMap' var_ansatz = 'TwoLocal' alternate = True backend = 'Aer' repetitions = num_qubits path = './data/expr/' compute_espressivity(num_qubits, repetitions, feature_map = feature_map, var_ansatz=var_ansatz, backend=backend, path=path, plot = True, save = True)
https://github.com/RohanGautam/storeQ
RohanGautam
import qiskit as qk from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from sklearn.preprocessing import LabelBinarizer from math import sqrt, pi import numpy as np import cv2 import math from tqdm import tqdm # custom : from customLabelBinarizer import CustomLabelBinarizer import imutils info = "rohan" org = cv2.imread('/home/rohan/Desktop/Python_files/quantumExploring/img/puppy.png') img = cv2.cvtColor(org, cv2.COLOR_BGR2GRAY) img = imutils.resize(img, width=100) row1 = img[0] # cv2.imshow("image", img) # cv2.waitKey(0) def closestPowerOfTwo(n): return 2**math.ceil(math.log(n)/math.log(2)) def highestPowerOfTwo(img): '''highest power of two amongst all rows''' maxVal = max([closestPowerOfTwo(len(list(set(row)))) for row in img]) return (maxVal, int(math.log(maxVal,2))) def removePadding(matrix): '''remove padded zeroes from the matrix to give the original LabelBinarizer binary vectors''' # calculate index of the '1' that has the furthest/max index. # This will be the boundary, beyond which we will discard the columns (zeroes) boundary = max([list(l).index(1) for l in matrix]) # index, begins from 0 print(boundary) return matrix[:, :boundary+1] # return sliced matrix powerVal, exponent = highestPowerOfTwo(img) lb_binarizers = [] rows_circuits = [] def startUpload (): print('[INFO] One-Hot encoding matrix rows') for row in tqdm(img) : # one-hot encode them -> convert them to binary vectors # why? because sum of amplitudes we pass should be = 1 lb = CustomLabelBinarizer() r_oneHot = lb.fit_transform(row) lb_binarizers.append(lb) # pad extra with zeroes, so that row length is the max power of 2 padNum = powerVal-r_oneHot.shape[1] r_padded = np.hstack((r_oneHot, np.zeros((r_oneHot.shape[0], padNum), dtype=r_oneHot.dtype))) # qbits = [] # # create qbits circuits = [] for vector in r_padded: qBitNum = exponent qc = QuantumCircuit(qBitNum) initial_state = vector # Define initial_state as |1>. sum of amplitudes = 1, has to be power of 2 qc.initialize(initial_state, list(range(qBitNum))) # Apply initialisation operation to the 0th qubit # qc.draw() circuits.append(qc) rows_circuits.append(circuits) backend = Aer.get_backend('statevector_simulator') def getOneHotVector(qc): result = execute(qc,backend).result() out_state = result.get_statevector() # print(out_state) vector = [int(x.real) for x in out_state] return vector def startDownload(): finalImage = [] for i in tqdm(range(len(rows_circuits))): row_circuit = rows_circuits[i] retrievedVectors=[] for circuit in row_circuit: retrievedVectors.append(getOneHotVector(circuit)) retrievedVectors = np.array(retrievedVectors) # convert to numpy array retrievedVectors = removePadding(retrievedVectors) # set the lb_binarizer to lb_binarizers[-1] to make it seem like it was hazy(error before) row = lb_binarizers[i].inverse_transform(retrievedVectors)# the final vector print(row.shape) finalImage.append(row) finalImage = np.array(finalImage) ## show it : cv2.imshow("Reconstructed image", finalImage) cv2.waitKey(0) # startUpload() # startDownload()
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.draw("mpl")
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 200000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts THE ONLY TASK qc1 = QuantumCircuit(2,2) # preparing 'a' bell pair which is |beta_00> here qc1.h(0) qc1.cx(0,1) qc1.barrier([0,1]) # Apply any pauli gate here a = input("BE SKYLER. APPLY ANY OF THE FOUR PAULI GATES:") if a == 'X': qc1.x(1) if a == 'Y': qc1.y(1) if a == 'Z': qc1.z(1) # if it's not any of them, it's I. So we don't need to do anything. qc1.barrier([0,1]) # Change the state into standard states: |00>, |01>, |10>, |11> depending on the gate applied qc1.cx(0,1) qc1.h(0) #Measure qc1.measure([0,1],[0,1]) backend = Aer.get_backend('qasm_simulator') result = execute(qc1, backend, shots = 1024).result() counts = result.get_counts() plot_histogram(counts) # On observation we get this mapping print('Skyler applied this gate: ') if '00' in counts.keys(): print('I') # She bluffed. # Don't worry if you haven't considered this case. Happens. elif '10' in counts.keys(): print('X') elif '11' in counts.keys(): print('Y') else: print('Z') plot_histogram(counts)
https://github.com/benkoehlL/Qiskit_Playground
benkoehlL
from argparse import ArgumentParser, Namespace, BooleanOptionalAction from qiskit import QuantumCircuit as qc from qiskit import QuantumRegister as qr from qiskit import transpile from qiskit_aer import AerSimulator from qiskit.result import Counts from matplotlib.pyplot import show, subplots, xticks, yticks from math import pi, sqrt from heapq import nlargest class GroversAlgorithm: def __init__(self, title: str = "Grover's Algorithm", n_qubits: int = 5, search: set[int] = { 11, 9, 0, 3 }, shots: int = 1000, fontsize: int = 10, print: bool = False, combine_states: bool = False) -> None: """ _summary_ Args: title (str, optional): Window title. Defaults to "Grover's Algorithm". n_qubits (int, optional): Number of qubits. Defaults to 5. search (set[int], optional): Set of nonnegative integers to search for using Grover's algorithm. Defaults to { 11, 9, 0, 3 }. shots (int, optional): Amount of times the algorithm is simulated. Defaults to 10000. fontsize (int, optional): Histogram's font size. Defaults to 10. print (bool, optional): Whether or not to print quantum circuit(s). Defaults to False. combine_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to False. """ # Parsing command line arguments self._parser: ArgumentParser = ArgumentParser(description = "Run grover's algorithm via command line", add_help = False) self._init_parser(title, n_qubits, search, shots, fontsize, print, combine_states) self._args: Namespace = self._parser.parse_args() # Set of nonnegative ints to search for self.search: set[int] = set(self._args.search) # Set of m N-qubit binary strings representing target state(s) (i.e. self.search in base 2) self._targets: set[str] = { f"{s:0{self._args.n_qubits}b}" for s in self.search } # N-qubit quantum register self._qubits: qr = qr(self._args.n_qubits, "qubit") def _print_circuit(self, circuit: qc, name: str) -> None: """Print quantum circuit. Args: circuit (qc): Quantum circuit to print. name (str): Quantum circuit's name. """ print(f"\n{name}:\n{circuit}") def _oracle(self, targets: set[str]) -> qc: """Mark target state(s) with negative phase. Args: targets (set[str]): N-qubit binary string(s) representing target state(s). Returns: qc: Quantum circuit representation of oracle. """ # Create N-qubit quantum circuit for oracle oracle = qc(self._qubits, name = "Oracle") for target in targets: # Reverse target state since Qiskit uses little-endian for qubit ordering target = target[::-1] # Flip zero qubits in target for i in range(self._args.n_qubits): if target[i] == "0": # Pauli-X gate oracle.x(i) # Simulate (N - 1)-control Z gate # 1. Hadamard gate oracle.h(self._args.n_qubits - 1) # 2. (N - 1)-control Toffoli gate oracle.mcx(list(range(self._args.n_qubits - 1)), self._args.n_qubits - 1) # 3. Hadamard gate oracle.h(self._args.n_qubits - 1) # Flip back to original state for i in range(self._args.n_qubits): if target[i] == "0": # Pauli-X gate oracle.x(i) # Display oracle, if applicable if self._args.print: self._print_circuit(oracle, "ORACLE") return oracle def _diffuser(self) -> qc: """Amplify target state(s) amplitude, which decreases the amplitudes of other states and increases the probability of getting the correct solution (i.e. target state(s)). Returns: qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator). """ # Create N-qubit quantum circuit for diffuser diffuser = qc(self._qubits, name = "Diffuser") # Hadamard gate diffuser.h(self._qubits) # Oracle with all zero target state diffuser.append(self._oracle({"0" * self._args.n_qubits}), list(range(self._args.n_qubits))) # Hadamard gate diffuser.h(self._qubits) # Display diffuser, if applicable if self._args.print: self._print_circuit(diffuser, "DIFFUSER") return diffuser def _grover(self) -> qc: """Create quantum circuit representation of Grover's algorithm, which consists of 4 parts: (1) state preparation/initialization, (2) oracle, (3) diffuser, and (4) measurement of resulting state. Steps 2-3 are repeated an optimal number of times (i.e. Grover's iterate) in order to maximize probability of success of Grover's algorithm. Returns: qc: Quantum circuit representation of Grover's algorithm. """ # Create N-qubit quantum circuit for Grover's algorithm grover = qc(self._qubits, name = "Grover Circuit") # Intialize qubits with Hadamard gate (i.e. uniform superposition) grover.h(self._qubits) # # Apply barrier to separate steps grover.barrier() # Apply oracle and diffuser (i.e. Grover operator) optimal number of times for _ in range(int((pi / 4) * sqrt((2 ** self._args.n_qubits) / len(self._targets)))): grover.append(self._oracle(self._targets), list(range(self._args.n_qubits))) grover.append(self._diffuser(), list(range(self._args.n_qubits))) # Measure all qubits once finished grover.measure_all() # Display grover circuit, if applicable if self._args.print: self._print_circuit(grover, "GROVER CIRCUIT") return grover def _outcome(self, winners: list[str], counts: Counts) -> None: """Print top measurement(s) (state(s) with highest frequency) and target state(s) in binary and decimal form, determine if top measurement(s) equals target state(s), then print result. Args: winners (list[str]): State(s) (N-qubit binary string(s)) with highest probability of being measured. counts (Counts): Each state and its respective frequency. """ print("WINNER(S):") print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n") print("TARGET(S):") print(f"Binary = {self._targets}\nDecimal = {self.search}\n") if not all(key in self._targets for key in winners): print("Target(s) not found...") else: winners_frequency, total = 0, 0 for value, frequency in counts.items(): if value in winners: winners_frequency += frequency total += frequency print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!") def _show_histogram(self, histogram_data) -> None: """Print outcome and display histogram of simulation results. Args: data: Each state and its respective frequency. """ # State(s) with highest count and their frequencies winners = { winner : histogram_data.get(winner) for winner in nlargest(len(self._targets), histogram_data, key = histogram_data.get) } # Print outcome self._outcome(list(winners.keys()), histogram_data) # X-axis and y-axis value(s) for winners, respectively winners_x_axis = [ str(winner) for winner in [*winners] ] winners_y_axis = [ *winners.values() ] # All other states (i.e. non-winners) and their frequencies others = { state : frequency for state, frequency in histogram_data.items() if state not in winners } # X-axis and y-axis value(s) for all other states, respectively other_states_x_axis = "Others" if self._args.combine else [*others] other_states_y_axis = [ sum([*others.values()]) ] if self._args.combine else [ *others.values() ] # Create histogram for simulation results figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained") axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target") axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target") axes.legend(fontsize = self._args.fontsize) axes.grid(axis = "y", ls = "dashed") axes.set_axisbelow(True) # Set histogram title, x-axis title, and y-axis title respectively axes.set_title(f"Outcome of {self._args.shots} Simulations", fontsize = int(self._args.fontsize * 1.45)) axes.set_xlabel("States (Qubits)", fontsize = int(self._args.fontsize * 1.3)) axes.set_ylabel("Frequency", fontsize = int(self._args.fontsize * 1.3)) # Set font properties for x-axis and y-axis labels respectively xticks(fontsize = self._args.fontsize, family = "monospace", rotation = 0 if self._args.combine else 70) yticks(fontsize = self._args.fontsize, family = "monospace") # Set properties for annotations displaying frequency above each bar annotation = axes.annotate("", xy = (0, 0), xytext = (5, 5), xycoords = "data", textcoords = "offset pixels", ha = "center", va = "bottom", family = "monospace", weight = "bold", fontsize = self._args.fontsize, bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0) ) def _hover(event) -> None: """Display frequency above each bar upon hovering over it. Args: event: Matplotlib event. """ visibility = annotation.get_visible() if event.inaxes == axes: for bars in axes.containers: for bar in bars: cont, _ = bar.contains(event) if cont: x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height() annotation.xy = (x, y) annotation.set_text(y) annotation.set_visible(True) figure.canvas.draw_idle() return if visibility: annotation.set_visible(False) figure.canvas.draw_idle() # Display histogram id = figure.canvas.mpl_connect("motion_notify_event", _hover) show() figure.canvas.mpl_disconnect(id) def run(self) -> None: """ Run Grover's algorithm simulation. """ # Simulate Grover's algorithm locally backend = AerSimulator(method = "density_matrix") # Generate optimized grover circuit for simulation transpiled_circuit = transpile(self._grover(), backend, optimization_level = 2) # Run Grover's algorithm simulation job = backend.run(transpiled_circuit, shots = self._args.shots) # Get simulation results results = job.result() # Get each state's histogram data (including frequency) from simulation results data = results.get_counts() # Display simulation results self._show_histogram(data) def _init_parser(self, title: str, n_qubits: int, search: set[int], shots: int, fontsize: int, print: bool, combine_states: bool) -> None: """ Helper method to initialize command line argument parser. Args: title (str): Window title. n_qubits (int): Number of qubits. search (set[int]): Set of nonnegative integers to search for using Grover's algorithm. shots (int): Amount of times the algorithm is simulated. fontsize (int): Histogram's font size. print (bool): Whether or not to print quantum circuit(s). combine_states (bool): Whether to combine all non-winning states into 1 bar labeled "Others" or not. """ self._parser.add_argument("-H, --help", action = "help", help = "show this help message and exit") self._parser.add_argument("-T, --title", type = str, default = title, dest = "title", metavar = "<title>", help = f"window title (default: \"{title}\")") self._parser.add_argument("-n, --n-qubits", type = int, default = n_qubits, dest = "n_qubits", metavar = "<n_qubits>", help = f"number of qubits (default: {n_qubits})") self._parser.add_argument("-s, --search", default = search, type = int, nargs = "+", dest = "search", metavar = "<search>", help = f"nonnegative integers to search for with Grover's algorithm (default: {search})") self._parser.add_argument("-S, --shots", type = int, default = shots, dest = "shots", metavar = "<shots>", help = f"amount of times the algorithm is simulated (default: {shots})") self._parser.add_argument("-f, --font-size", type = int, default = fontsize, dest = "fontsize", metavar = "<font_size>", help = f"histogram's font size (default: {fontsize})") self._parser.add_argument("-p, --print", action = BooleanOptionalAction, type = bool, default = print, dest = "print", help = f"whether or not to print quantum circuit(s) (default: {print})") self._parser.add_argument("-c, --combine", action = BooleanOptionalAction, type = bool, default = combine_states, dest = "combine", help = f"whether to combine all non-winning states into 1 bar labeled \"Others\" or not (default: {combine_states})") if __name__ == "__main__": GroversAlgorithm().run()
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/dkp-quantum/Tutorials
dkp-quantum
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.visualization import * import numpy as np # Exercise 1. # Create the measurement circuit ZZI = QuantumCircuit(4,1) ZZI.h(3) ZZI.cz(3,0) ZZI.cz(3,1) ZZI.h(3) ZZI.barrier() ZZI.measure(3,0) ZZI.draw(output='mpl') # Create the first test state, i.e. a|000> + b|111> ztest1 = QuantumCircuit(4) theta = np.random.random()*np.pi phi = np.random.random()*2*np.pi ztest1.ry(theta,0) ztest1.rz(phi,0) ztest1.cx(0,1) ztest1.cx(0,2) ztest1.barrier() # Now add the measurement circuit ztest1 = ztest1 + ZZI ztest1.draw(output='mpl') # Use Aer's qasm_simulator backend_q = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. job_ztest1 = execute(ztest1, backend_q, shots=4096) # Grab the results from the job. result_ztest1 = job_ztest1.result() plot_histogram(result_ztest1.get_counts(ztest1)) # Create the second test state, i.e. a|010> + b|101> ztest2 = QuantumCircuit(4) theta = np.random.random()*np.pi phi = np.random.random()*2*np.pi ztest2.ry(theta,0) ztest2.rz(phi,0) # Flip the second qubit ztest2.x(1) ztest2.cx(0,1) ztest2.cx(0,2) ztest2.barrier() # Now add the measurement circuit ztest2 = ztest2 + ZZI ztest2.draw(output='mpl') # Execute the circuit on the qasm simulator. job_ztest2 = execute(ztest2, backend_q, shots=4096) # Grab the results from the job. result_ztest2 = job_ztest2.result() plot_histogram(result_ztest2.get_counts(ztest2)) # Exercise 2. # Create the measurement circuit XXI = QuantumCircuit(4,1) XXI.h(3) XXI.cx(3,0) XXI.cx(3,1) XXI.h(3) XXI.barrier() XXI.measure(3,0) XXI.draw(output='mpl') # Create the first test state, i.e. a|+++> + b|---> xtest1 = QuantumCircuit(4) theta = np.random.random()*np.pi phi = np.random.random()*2*np.pi xtest1.ry(theta,0) xtest1.rz(phi,0) xtest1.cx(0,1) xtest1.cx(0,2) for i in range(3): xtest1.h(i) xtest1.barrier() # Now add the measurement circuit xtest1 = xtest1 + XXI xtest1.draw(output='mpl') # Execute the circuit on the qasm simulator. job_xtest1 = execute(xtest1, backend_q, shots=4096) # Grab the results from the job. result_xtest1 = job_xtest1.result() plot_histogram(result_xtest1.get_counts(xtest1)) # Create the first test state, i.e. a|+-+> + b|-+-> xtest2 = QuantumCircuit(4) theta = np.random.random()*np.pi phi = np.random.random()*2*np.pi xtest2.ry(theta,0) xtest2.rz(phi,0) # Flip the second qubit xtest2.x(1) xtest2.cx(0,1) xtest2.cx(0,2) for i in range(3): xtest2.h(i) xtest2.barrier() # Now add the measurement circuit xtest2 = xtest2 + XXI xtest2.draw(output='mpl') # Execute the circuit on the qasm simulator. job_xtest2 = execute(xtest2, backend_q, shots=4096) # Grab the results from the job. result_xtest2 = job_xtest2.result() plot_histogram(result_xtest2.get_counts(xtest2)) %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.visualization import * import numpy as np def encoding_x(qc): qc.cx(0,1) qc.cx(0,2) qc.barrier() def measure_error(qc,error): if error == 'x': qc.h(3) qc.h(4) qc.cz(3,0) qc.cz(3,1) qc.cz(4,0) qc.cz(4,2) qc.h(3) qc.h(4) elif error == 'z': qc.h(3) qc.h(4) qc.cx(3,0) qc.cx(3,1) qc.cx(4,0) qc.cx(4,2) qc.h(3) qc.h(4) qc.barrier() # We don't need decoding for QEC, # but we will use it for checking the answer def decoding_x(qc): qc.cx(0,2) qc.cx(0,1) qc.barrier() def random_init(qc,theta,phi,index): ## Prepare a random single-qubit state qc.ry(theta,index) qc.rz(phi,index) qc.barrier() def random_init_inv(qc,theta,phi,index): ## Inverse of the random single-qubit state preparation qc.rz(-phi,index) qc.ry(-theta,index) qc.barrier() qec2x = QuantumCircuit(5,3) # Initialize the first qubit in a random state theta = np.random.random()*np.pi qec2x.ry(theta,0) # QEC encoding for correcting a bit-flip error encoding_x(qec2x) # Measurement measure_error(qec2x,'x') # Correction # Correct the first qubit qec2x.ccx(3,4,0) # Correct the second qubit qec2x.x(4) qec2x.ccx(3,4,1) qec2x.x(4) # Correct the third qubit qec2x.x(3) qec2x.ccx(3,4,2) qec2x.x(3) qec2x.barrier() # QEC decoding for correcting a bit-flip error decoding_x(qec2x) # Insert inverse of the random initial state preparation # to check that the QEC has worked. qec2x.ry(-theta,0) qec2x.measure(0,0) # Let's check the error syndrome qec2x.measure(3,1) qec2x.measure(4,2) qec2x.draw(output='mpl') # Execute the circuit on the qasm simulator. job_qec2x_ref = execute(qec2x, backend_q, shots=4096) # Grab the results from the job. result_qec2x_ref = job_qec2x_ref.result() plot_histogram(result_qec2x_ref.get_counts(qec2x)) # IBMQ.disable_account() provider = IBMQ.enable_account('TOKEN') from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor from qiskit.tools.visualization import plot_gate_map, plot_error_map # Retrieve IBM Quantum device information backend_overview() # Let's also try the same experiment on the 15-qubit device. job_exp_qec2x = execute(qec2x, backend=provider.get_backend('ibmq_valencia'), shots=8192) job_monitor(job_exp_qec2x) # Grab experimental results result_exp_qec2x = job_exp_qec2x.result() plot_histogram(result_exp_qec2x.get_counts(qec2x)) # Define bit-flip errors with probability p def bitflip(qc,qubit,p): if np.random.binomial(1,p) == 1: qc.x(qubit) qec2x = QuantumCircuit(5,3) # Initialize the first qubit in a random state theta = np.random.random()*np.pi qec2x.ry(theta,0) # QEC encoding for correcting a bit-flip error encoding_x(qec2x) # Insert error p=1 # bitflip(qec2x,0,p) # bitflip(qec2x,1,p) bitflip(qec2x,2,p) qec2x.barrier() # Measurement measure_error(qec2x,'x') # Correction # Correct the first qubit qec2x.ccx(3,4,0) # Correct the second qubit qec2x.x(4) qec2x.ccx(3,4,1) qec2x.x(4) # Correct the third qubit qec2x.x(3) qec2x.ccx(3,4,2) qec2x.x(3) qec2x.barrier() # QEC decoding for correcting a bit-flip error decoding_x(qec2x) # Insert inverse of the random initial state preparation # to check that the QEC has worked. qec2x.ry(-theta,0) qec2x.measure(0,0) # Let's check the error syndrome qec2x.measure(3,1) qec2x.measure(4,2) qec2x.draw(output='mpl') # Execute the circuit on the qasm simulator. job_qec2x = execute(qec2x, backend_q, shots=4096) # Grab the results from the job. result_qec2x = job_qec2x.result() plot_histogram(result_qec2x.get_counts(qec2x)) from qiskit.compiler import transpile from qiskit.transpiler import PassManager, Layout display(plot_error_map(provider.get_backend('ibmqx2'))) display(plot_error_map(provider.get_backend('ibmq_burlington'))) # Create a dummy circuit for default transpiler demonstration qc = QuantumCircuit(4) qc.h(0) qc.swap(0,1) qc.cx(1,0) qc.s(3) qc.x(3) qc.h(3) qc.h(0) qc.cx(0,2) qc.ccx(0,1,2) qc.h(0) print('Original circuit') display(qc.draw(output='mpl')) # Transpile the circuit to run on ibmqx2 qt_qx2 = transpile(qc,provider.get_backend('ibmqx2')) print('Transpiled circuit for ibmqx2') display(qt_qx2.draw(output='mpl')) # Transpile the circuit to run on ibmq_burlington qt_bu = transpile(qc,provider.get_backend('ibmq_burlington')) print('Transpiled circuit for ibmqx_Burlington') display(qt_bu.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations for ibmqx2 = %s" % qt_qx2.size()) print("Number of operations for ibmq_burlington = %s \n" % qt_bu.size()) # Circuit depth print("Circuit depth for ibmqx2 = %s" % qt_qx2.depth()) print("Circuit depth for ibmq_burlington = %s \n" % qt_bu.depth()) # Number of qubits print("Number of qubits for ibmqx2 = %s" % qt_qx2.width()) print("Number of qubits for ibmq_burlington = %s \n" % qt_bu.width()) # Breakdown of operations by type print("Operations for ibmqx2: %s" % qt_qx2.count_ops()) print("Operations for ibmq_burlington: %s \n" % qt_bu.count_ops()) # Number of unentangled subcircuits in this circuit. # In principle, each subcircuit can be executed on a different quantum device. print("Number of unentangled subcircuits for ibmqx2 = %s" % qt_qx2.num_tensor_factors()) print("Number of unentangled subcircuits for ibmq_burlington = %s" % qt_bu.num_tensor_factors()) qr = QuantumRegister(4,'q') cr = ClassicalRegister(4,'c') qc_test = QuantumCircuit(qr,cr) qc_test.h(0) for i in range(3): qc_test.cx(i,i+1) qc_test.barrier() qc_test.measure(qr,cr) qc_test.draw(output='mpl') qc_t = transpile(qc_test, backend = provider.get_backend('ibmq_london')) # Display transpiled circuit display(qc_t.draw(output='mpl')) # Display the qubit layout display(plot_error_map(provider.get_backend('ibmq_london'))) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_t.size()) # Circuit depth print("Circuit depth = %s" % qc_t.depth()) # Execute the circuit on the qasm simulator. job_test = execute(qc_test, provider.get_backend('ibmq_london'), shots=8192) job_monitor(job_test) # Customize the layout layout = Layout({qr[0]: 4, qr[1]: 3, qr[2]: 1, qr[3]:0}) # Map it onto 5 qubit backend ibmqx2 qc_test_new = transpile(qc_test, backend = provider.get_backend('ibmq_london'), initial_layout=layout, basis_gates=['u1','u2','u3','cx']) display(qc_test_new.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_test_new.size()) # Circuit depth print("Circuit depth = %s" % qc_test_new.depth()) # Execute the circuit on the qasm simulator. job_test_new = execute(qc_test_new, provider.get_backend('ibmq_london'), shots=8192) job_monitor(job_test_new) # Now, compare the two result_test = job_test.result() result_test_new = job_test_new.result() # Plot both experimental and ideal results plot_histogram([result_test.get_counts(qc_test),result_test_new.get_counts(qc_test_new)], color=['green','blue'],legend=['default','custom'],figsize = [20,8]) # Apply 4-qubit controlled x gate qr = QuantumRegister(5,'q') qc = QuantumCircuit(qr) qc.h(0) qc.h(1) qc.h(3) qc.ccx(0,1,2) qc.ccx(2,3,4) qc.ccx(0,1,2) display(qc.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s \n" % qc.size()) # Count different types of operations print("Operation counts = %s \n" % qc.count_ops()) # Circuit depth print("Circuit depth = %s" % qc.depth()) qc_t = transpile(qc, provider.get_backend('ibmq_valencia')) display(qc_t.draw(output='mpl')) # Print out some circuit properties # Total nunmber of operations print("Number of operations = %s" % qc_t.size()) # Circuit depth print("Circuit depth = %s" % qc_t.depth()) # Transpile many times (20 times in this example) and pick the best one trial = 20 # Use ibmq_valencia for example backend_exp = provider.get_backend('ibmq_valencia') tcircs0 = transpile([qc]*trial, backend_exp, optimization_level=0) tcircs1 = transpile([qc]*trial, backend_exp, optimization_level=1) tcircs2 = transpile([qc]*trial, backend_exp, optimization_level=2) tcircs3 = transpile([qc]*trial, backend_exp, optimization_level=3) import matplotlib.pyplot as plt num_cx0 = [c.count_ops()['cx'] for c in tcircs0] num_cx1 = [c.count_ops()['cx'] for c in tcircs1] num_cx2 = [c.count_ops()['cx'] for c in tcircs2] num_cx3 = [c.count_ops()['cx'] for c in tcircs3] num_tot0 = [c.size() for c in tcircs0] num_tot1 = [c.size() for c in tcircs1] num_tot2 = [c.size() for c in tcircs2] num_tot3 = [c.size() for c in tcircs3] num_depth0 = [c.depth() for c in tcircs0] num_depth1 = [c.depth() for c in tcircs1] num_depth2 = [c.depth() for c in tcircs2] num_depth3 = [c.depth() for c in tcircs3] plt.rcParams.update({'font.size': 16}) # Plot the number of CNOT gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_cx0)),num_cx0,'r',label='level 0') plt.plot(range(len(num_cx1)),num_cx1,'b',label='level 1') plt.plot(range(len(num_cx2)),num_cx2,'g',label='level 2') plt.plot(range(len(num_cx3)),num_cx3,'k',label='level 3') plt.legend(loc='upper left') plt.xlabel('Random trial') plt.ylabel('# of cx gates') plt.show() # Plot total number of gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_tot0)),num_tot0,'r',label='level 0') plt.plot(range(len(num_tot1)),num_tot1,'b',label='level 1') plt.plot(range(len(num_tot2)),num_tot2,'g',label='level 2') plt.plot(range(len(num_tot3)),num_tot3,'k',label='level 3') plt.legend(loc='upper left') plt.xlabel('Random trial') plt.ylabel('# of total gates') plt.show() # Plot the number of CNOT gates plt.figure(figsize=(12,6)) plt.plot(range(len(num_depth0)),num_depth0,'r',label='level 0') plt.plot(range(len(num_depth1)),num_depth1,'b',label='level 1') plt.plot(range(len(num_depth2)),num_depth2,'g',label='level 2') plt.plot(range(len(num_depth3)),num_depth3,'k',label='level 3') plt.legend(loc='upper left') plt.xlabel('Random trial') plt.ylabel('Circuit depth') plt.show() print('Opt0: Minimum # of cx gates = %s' % min(num_cx0)) print('Opt0: The best circuit is the circut %s \n' % num_cx0.index(min(num_cx0))) print('Opt1: Minimum # of cx gates = %s' % min(num_cx1)) print('Opt1: The best circuit is the circut %s \n' % num_cx1.index(min(num_cx1))) print('Opt2: Minimum # of cx gates = %s' % min(num_cx2)) print('Opt2: The best circuit is the circut %s \n' % num_cx2.index(min(num_cx2))) print('Opt3: Minimum # of cx gates = %s' % min(num_cx3)) print('Opt3: The best circuit is the circut %s' % num_cx3.index(min(num_cx3)))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import UnitarySynthesis circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data unitary_circ = QuantumCircuit(1) unitary_circ.unitary(unitary, [0]) synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") out = synth(unitary_circ) out.draw('mpl')
https://github.com/xtophe388/QISKIT
xtophe388
from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram # set up registers and program qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) # rightmost eight (qu)bits have ')' = 00101001 qc.x(qr[0]) qc.x(qr[3]) qc.x(qr[5]) # second eight (qu)bits have superposition of # '8' = 00111000 # ';' = 00111011 # these differ only on the rightmost two bits qc.h(qr[9]) # create superposition on 9 qc.cx(qr[9],qr[8]) # spread it to 8 with a CNOT qc.x(qr[11]) qc.x(qr[12]) qc.x(qr[13]) # measure for j in range(16): qc.measure(qr[j], cr[j]) from qiskit import register, available_backends, get_backend #import Qconfig and set APIToken and API url try: import sys sys.path.append("../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} except Exception as e: print(e) qx_config = { "APItoken":"YOUR_TOKEN_HERE", "url":"https://quantumexperience.ng.bluemix.net/api"} #set api register(qx_config['APItoken'], qx_config['url']) backend = "ibmq_qasm_simulator" shots_sim = 128 job_sim = execute(qc, backend, shots=shots_sim) stats_sim = job_sim.result().get_counts() plot_histogram(stats_sim) import matplotlib.pyplot as plt %matplotlib inline plt.rc('font', family='monospace') def plot_smiley (stats, shots): for bitString in stats: char = chr(int( bitString[0:8] ,2)) # get string of the leftmost 8 bits and convert to an ASCII character char += chr(int( bitString[8:16] ,2)) # do the same for string of rightmost 8 bits, and add it to the previous character prob = stats[bitString] / shots # fraction of shots for which this result occurred # create plot with all characters on top of each other with alpha given by how often it turned up in the output plt.annotate( char, (0.5,0.5), va="center", ha="center", color = (0,0,0, prob ), size = 300) if (prob>0.05): # list prob and char for the dominant results (occurred for more than 5% of shots) print(str(prob)+"\t"+char) plt.axis('off') plt.show() plot_smiley(stats_sim, shots_sim) backends = available_backends() backend = get_backend('ibmqx5') print('Status of ibmqx5:',backend.status) if backend.status["operational"] is True: print("\nThe device is operational, so we'll submit the job.") shots_device = 1000 job_device = execute(qc, backend, shots=shots_device) stats_device = job_device.result().get_counts() else: print("\nThe device is not operational. Try again later.") plot_smiley(stats_device, shots_device)
https://github.com/omarcostahamido/qiskit_app_carbon_design
omarcostahamido
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import Aer, IBMQ, execute from qiskit.providers.aer import noise from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor #IBMQ.enable_account(token, url='https://quantumexperience.ng.bluemix.net/api') #IBMQ.active_accounts() #IBMQ.backends() def setup_noise(circuit,shots): """ This fucntion run a circuit on a simulated ibmq_16_melbourne device with noise """ # Basic device noise model # List of gate times # Note that the None parameter for u1, u2, u3 is because gate # times are the same for all qubits gate_times = [ ('u1', None, 0), ('u2', None, 100), ('u3', None, 200), ('cx', [1, 0], 678), ('cx', [1, 2], 547), ('cx', [2, 3], 721), ('cx', [4, 3], 733), ('cx', [4, 10], 721), ('cx', [5, 4], 800), ('cx', [5, 6], 800), ('cx', [5, 9], 895), ('cx', [6, 8], 895), ('cx', [7, 8], 640), ('cx', [9, 8], 895), ('cx', [9, 10], 800), ('cx', [11, 10], 721), ('cx', [11, 3], 634), ('cx', [12, 2], 773), ('cx', [13, 1], 2286), ('cx', [13, 12], 1504), ('cx', [], 800) ] device = IBMQ.get_backend('ibmq_16_melbourne') properties = device.properties() coupling_map = device.configuration().coupling_map # Construct the noise model from backend properties # and custom gate times noise_model = noise.device.basic_device_noise_model(properties, gate_times=gate_times) # Get the basis gates for the noise model basis_gates = noise_model.basis_gates # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Execute noisy simulation and get counts result_noise = execute(circuit, simulator,shots=shots,noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates).result().get_counts(circuit) # print(result_noise) #counts_noise = result_noise.get_counts(circ) return result_noise def emo_noise(): """ This function simulate the emoticon function with noise, to perform noise we are limited to use just a streactly set of emoticon because of constraints coming from the real device. """ # set up registers and program qr = QuantumRegister(14) cr = ClassicalRegister(14) qc = QuantumCircuit(qr, cr) # rightmost seven (qu)bits have ')' = 0101001 qc.x(qr[0]) qc.x(qr[3]) qc.x(qr[5]) # second seven (qu)bits have superposition of # '8' = 0111000 # ';' = 0111011 # these differ only on the rightmost two bits qc.h(qr[8]) # create superposition on 9 qc.cx(qr[8],qr[7]) # spread it to 8 with a CNOT qc.x(qr[10]) qc.x(qr[11]) qc.x(qr[12]) # measure for j in range(14): qc.measure(qr[j], cr[j]) shots=400 ## RUN THE SIMULATION return synt_chr(setup_noise(qc,shots)) def synt_chr(stats, shots=None): """ This function transforms the binary the string of bits into ascii character """ n_list=[] for bitString in stats: char = chr(int( bitString[0:7] ,2)) # get string of the leftmost 7 bits and convert to an ASCII character char += chr(int( bitString[7:14] ,2)) # do the same for string of rightmost 7 bits, and add it to the previous character #prob = stats[bitString] / shots # fraction of shots for which this result occurred n_list.append({"shots":stats[bitString],"value":char}) return n_list def setup_noise_s(circuit,shots): """ This fucntion run a circuit on a simulated ibmq_16_melbourne device with noise """ # Basic device noise model # List of gate times # Note that the None parameter for u1, u2, u3 is because gate # times are the same for all qubits gate_times = [ ('u1', None, 0), ('u2', None, 100), ('u3', None, 200), ('cx', [1, 0], 678), ('cx', [1, 2], 547), ('cx', [2, 3], 721), ('cx', [4, 3], 733), ('cx', [4, 10], 721), ('cx', [5, 4], 800), ('cx', [5, 6], 800), ('cx', [5, 9], 895), ('cx', [6, 8], 895), ('cx', [7, 8], 640), ('cx', [9, 8], 895), ('cx', [9, 10], 800), ('cx', [11, 10], 721), ('cx', [11, 3], 634), ('cx', [12, 2], 773), ('cx', [13, 1], 2286), ('cx', [13, 12], 1504), ('cx', [], 800) ] device = IBMQ.get_backend('ibmq_16_melbourne') properties = device.properties() coupling_map = device.configuration().coupling_map # Construct the noise model from backend properties # and custom gate times noise_model = noise.device.basic_device_noise_model(properties, gate_times=gate_times) # Get the basis gates for the noise model basis_gates = noise_model.basis_gates # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Execute noisy simulation and get counts result_noise = execute(circuit, simulator,shots=shots,noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates).result() # print(result_noise) #counts_noise = result_noise.get_counts(circ) return result_noise
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a DensityMatrix state = DensityMatrix(qc) plot_state_city(state)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram qp = QuadraticProgram() qp.binary_var("x") qp.binary_var("y") qp.integer_var(lowerbound=0, upperbound=7, name="z") qp.maximize(linear={"x": 2, "y": 1, "z": 1}) qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="LE", rhs=5.5, name="xyz_leq") qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="GE", rhs=2.5, name="xyz_geq") print(qp.prettyprint()) from qiskit_optimization.converters import InequalityToEquality ineq2eq = InequalityToEquality() qp_eq = ineq2eq.convert(qp) print(qp_eq.prettyprint()) print(qp_eq.prettyprint()) from qiskit_optimization.converters import IntegerToBinary int2bin = IntegerToBinary() qp_eq_bin = int2bin.convert(qp_eq) print(qp_eq_bin.prettyprint()) print(qp_eq_bin.prettyprint()) from qiskit_optimization.converters import LinearEqualityToPenalty lineq2penalty = LinearEqualityToPenalty() qubo = lineq2penalty.convert(qp_eq_bin) print(qubo.prettyprint()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ Superoperator representation of a Quantum Channel.""" from __future__ import annotations import copy as _copy import math from typing import TYPE_CHECKING import numpy as np from qiskit import _numpy_compat from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.channel.transformations import _bipartite_tensor, _to_superop from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.operator import Operator if TYPE_CHECKING: from qiskit.quantum_info.states.densitymatrix import DensityMatrix from qiskit.quantum_info.states.statevector import Statevector class SuperOp(QuantumChannel): r"""Superoperator representation of a quantum channel. The Superoperator representation of a quantum channel :math:`\mathcal{E}` is a matrix :math:`S` such that the evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` is given by .. math:: |\mathcal{E}(\rho)\rangle\!\rangle = S |\rho\rangle\!\rangle where the double-ket notation :math:`|A\rangle\!\rangle` denotes a vector formed by stacking the columns of the matrix :math:`A` *(column-vectorization)*. See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | Instruction | BaseOperator | np.ndarray, input_dims: tuple | None = None, output_dims: tuple | None = None, ): """Initialize a quantum channel Superoperator operator. Args: data (QuantumCircuit or Instruction or BaseOperator or matrix): data to initialize superoperator. input_dims (tuple): the input subsystem dimensions. [Default: None] output_dims (tuple): the output subsystem dimensions. [Default: None] Raises: QiskitError: if input data cannot be initialized as a superoperator. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. If the input data is a Numpy array of shape (4**N, 4**N) qubit systems will be used. If the input operator is not an N-qubit operator, it will assign a single subsystem with dimension specified by the shape of the input. """ # If the input is a raw list or matrix we assume that it is # already a superoperator. if isinstance(data, (list, np.ndarray)): # We initialize directly from superoperator matrix super_mat = np.asarray(data, dtype=complex) # Determine total input and output dimensions dout, din = super_mat.shape input_dim = int(math.sqrt(din)) output_dim = int(math.sqrt(dout)) if output_dim**2 != dout or input_dim**2 != din: raise QiskitError("Invalid shape for SuperOp matrix.") op_shape = OpShape.auto( dims_l=output_dims, dims_r=input_dims, shape=(output_dim, input_dim) ) else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # perform a simulation to construct the circuit superoperator. # This will only work if the circuit or instruction can be # defined in terms of instructions which have no classical # register components. The instructions can be gates, reset, # or Kraus instructions. Any conditional gates or measure # will cause an exception to be raised. data = self._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) # Now that the input is an operator we convert it to a # SuperOp object op_shape = data._op_shape input_dim, output_dim = data.dim rep = getattr(data, "_channel_rep", "Operator") super_mat = _to_superop(rep, data._data, input_dim, output_dim) # Initialize QuantumChannel super().__init__(super_mat, op_shape=op_shape) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype if dtype is None else dtype return np.array(self.data, dtype=dtype, copy=copy) @property def _tensor_shape(self): """Return the tensor shape of the superoperator matrix""" return 2 * tuple(reversed(self._op_shape.dims_l())) + 2 * tuple( reversed(self._op_shape.dims_r()) ) @property def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._output_dim, self._output_dim, self._input_dim, self._input_dim) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): ret = _copy.copy(self) ret._data = np.conj(self._data) return ret def transpose(self): ret = _copy.copy(self) ret._data = np.transpose(self._data) ret._op_shape = self._op_shape.transpose() return ret def adjoint(self): ret = _copy.copy(self) ret._data = np.conj(np.transpose(self._data)) ret._op_shape = self._op_shape.transpose() return ret def tensor(self, other: SuperOp) -> SuperOp: if not isinstance(other, SuperOp): other = SuperOp(other) return self._tensor(self, other) def expand(self, other: SuperOp) -> SuperOp: if not isinstance(other, SuperOp): other = SuperOp(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = _copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) ret._data = _bipartite_tensor( a._data, b.data, shape1=a._bipartite_shape, shape2=b._bipartite_shape ) return ret def compose(self, other: SuperOp, qargs: list | None = None, front: bool = False) -> SuperOp: if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, SuperOp): other = SuperOp(other) # Validate dimensions are compatible and return the composed # operator dimensions new_shape = self._op_shape.compose(other._op_shape, qargs, front) input_dims = new_shape.dims_r() output_dims = new_shape.dims_l() # Full composition of superoperators if qargs is None: if front: data = np.dot(self._data, other.data) else: data = np.dot(other.data, self._data) ret = SuperOp(data, input_dims, output_dims) ret._op_shape = new_shape return ret # Compute tensor contraction indices from qargs num_qargs_l, num_qargs_r = self._op_shape.num_qargs if front: num_indices = num_qargs_r shift = 2 * num_qargs_l right_mul = True else: num_indices = num_qargs_l shift = 0 right_mul = False # Reshape current matrix # Note that we must reverse the subsystem dimension order as # qubit 0 corresponds to the right-most position in the tensor # product, which is the last tensor wire index. tensor = np.reshape(self.data, self._tensor_shape) mat = np.reshape(other.data, other._tensor_shape) # Add first set of indices indices = [2 * num_indices - 1 - qubit for qubit in qargs] + [ num_indices - 1 - qubit for qubit in qargs ] final_shape = [np.prod(output_dims) ** 2, np.prod(input_dims) ** 2] data = np.reshape( Operator._einsum_matmul(tensor, mat, indices, shift, right_mul), final_shape ) ret = SuperOp(data, input_dims, output_dims) ret._op_shape = new_shape return ret # --------------------------------------------------------------------- # Additional methods # --------------------------------------------------------------------- def _evolve(self, state, qargs=None): """Evolve a quantum state by the quantum channel. Args: state (DensityMatrix or Statevector): The input state. qargs (list): a list of quantum state subsystem positions to apply the quantum channel on. Returns: DensityMatrix: the output quantum state as a density matrix. Raises: QiskitError: if the quantum channel dimension does not match the specified quantum state subsystem dimensions. """ # Prevent cyclic imports by importing DensityMatrix here # pylint: disable=cyclic-import from qiskit.quantum_info.states.densitymatrix import DensityMatrix if not isinstance(state, DensityMatrix): state = DensityMatrix(state) if qargs is None: # Evolution on full matrix if state._op_shape.shape[0] != self._op_shape.shape[1]: raise QiskitError( "Operator input dimension is not equal to density matrix dimension." ) # We reshape in column-major vectorization (Fortran order in Numpy) # since that is how the SuperOp is defined vec = np.ravel(state.data, order="F") mat = np.reshape( np.dot(self.data, vec), (self._output_dim, self._output_dim), order="F" ) return DensityMatrix(mat, dims=self.output_dims()) # Otherwise we are applying an operator only to subsystems # Check dimensions of subsystems match the operator if state.dims(qargs) != self.input_dims(): raise QiskitError( "Operator input dimensions are not equal to statevector subsystem dimensions." ) # Reshape statevector and operator tensor = np.reshape(state.data, state._op_shape.tensor_shape) mat = np.reshape(self.data, self._tensor_shape) # Construct list of tensor indices of statevector to be contracted num_indices = len(state.dims()) indices = [num_indices - 1 - qubit for qubit in qargs] + [ 2 * num_indices - 1 - qubit for qubit in qargs ] tensor = Operator._einsum_matmul(tensor, mat, indices) # Replace evolved dimensions new_dims = list(state.dims()) output_dims = self.output_dims() for i, qubit in enumerate(qargs): new_dims[qubit] = output_dims[i] new_dim = np.prod(new_dims) # reshape tensor to density matrix tensor = np.reshape(tensor, (new_dim, new_dim)) return DensityMatrix(tensor, dims=new_dims) @classmethod def _init_instruction(cls, instruction): """Convert a QuantumCircuit or Instruction to a SuperOp.""" # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an identity superoperator of the correct size # of the circuit op = SuperOp(np.eye(4**instruction.num_qubits)) op._append_instruction(instruction) return op @classmethod def _instruction_to_superop(cls, obj): """Return superop for instruction if defined or None otherwise.""" if not isinstance(obj, Instruction): raise QiskitError("Input is not an instruction.") chan = None if obj.name == "reset": # For superoperator evolution we can simulate a reset as # a non-unitary superoperator matrix chan = SuperOp(np.array([[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])) if obj.name == "kraus": kraus = obj.params dim = len(kraus[0]) chan = SuperOp(_to_superop("Kraus", (kraus, None), dim, dim)) elif hasattr(obj, "to_matrix"): # If instruction is a gate first we see if it has a # `to_matrix` definition and if so use that. try: kraus = [obj.to_matrix()] dim = len(kraus[0]) chan = SuperOp(_to_superop("Kraus", (kraus, None), dim, dim)) except QiskitError: pass return chan def _append_instruction(self, obj, qargs=None): """Update the current Operator by apply an instruction.""" from qiskit.circuit.barrier import Barrier chan = self._instruction_to_superop(obj) if chan is not None: # Perform the composition and inplace update the current state # of the operator op = self.compose(chan, qargs=qargs) self._data = op.data elif isinstance(obj, Barrier): return else: # If the instruction doesn't have a matrix defined we use its # circuit decomposition definition if it exists, otherwise we # cannot compose this gate and raise an error. if obj.definition is None: raise QiskitError(f"Cannot apply Instruction: {obj.name}") if not isinstance(obj.definition, QuantumCircuit): raise QiskitError( "{} instruction definition is {}; " "expected QuantumCircuit".format(obj.name, type(obj.definition)) ) qubit_indices = {bit: idx for idx, bit in enumerate(obj.definition.qubits)} for instruction in obj.definition.data: if instruction.clbits: raise QiskitError( "Cannot apply instruction with classical bits:" f" {instruction.operation.name}" ) # Get the integer position of the flat register if qargs is None: new_qargs = [qubit_indices[tup] for tup in instruction.qubits] else: new_qargs = [qargs[qubit_indices[tup]] for tup in instruction.qubits] self._append_instruction(instruction.operation, qargs=new_qargs) # Update docstrings for API docs generate_apidocs(SuperOp)
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/Simultonian/hamilutor-qiskit
Simultonian
import pytest from qiskit import QuantumCircuit from ..trotter.simple import trotter from ..utils import circuit_eq from .group_trotter import generic from ..grouping import Bitwise from ..ordering import lexico import itertools def test_single_group_trotter_grouper(): group = {"ix": 1.0, "xi": -1.0} result = generic(Bitwise, lexico, group) expected = QuantumCircuit(2) # Rotation expected.h(0) expected.h(1) # Exponentiate circuit = trotter({"iz": 1.0, "zi": -1.0}) expected = expected.compose(circuit) # Anti-rotation expected.h(0) expected.h(1) assert circuit_eq(result, expected) def test_bitwise_simple_single_group(): group = {"ix": 1.0, "xi": -1.0} # Checking for multiple number of repetitions for reps in range(1, 5): result = generic(Bitwise, lexico, group, t=1.0, reps=reps) expected = QuantumCircuit(2) for _ in range(reps): # Rotation expected.h(0) expected.h(1) # Exponentiate circuit = trotter({"iz": 1.0, "zi": -1.0}, t=1.0 / reps) expected = expected.compose(circuit) # Anti-rotation expected.h(0) expected.h(1) assert circuit_eq(result, expected) two_group_hams = [ {"xx": 1.0, "zz": 2.0}, {"xx": 1.0, "zz": 2.0, "zi": 3.0}, {"xx": 1.0, "zz": 2.0, "zi": 3.0, "xy": 4.0}, ] two_group_groups = [ [ {"xx": 1.0}, {"zz": 2.0}, ], [ {"xx": 1.0}, {"zz": 2.0, "zi": 3.0}, ], [{"xx": 1.0}, {"zz": 2.0, "zi": 3.0}, {"xy": 4.0}], ] two_num_qubits = [2, 2] @pytest.mark.parametrize("reps", range(1, 5)) @pytest.mark.parametrize( "h,groups,qubits", zip(two_group_hams, two_group_groups, two_num_qubits) ) def test_bitwise_simple_multiple_groups(reps, h, groups, qubits): # Checking for multiple number of repetitions. result = generic(Bitwise, lexico, h, t=1.0, reps=reps) check = False # Check for all possible orders of the group for order in itertools.permutations(groups): expected = QuantumCircuit(qubits) # Runs reps loop and trotters individual group. for _ in range(reps): for group in order: circuit = trotter(group, t=1.0 / reps) expected = expected.compose(circuit) check = check or circuit_eq(result, expected) assert check
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from IPython.display import display, clear_output from qiskit.primitives import Estimator from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.observables_evaluator import estimate_observables from qiskit.algorithms.optimizers import COBYLA, SLSQP from qiskit.circuit import QuantumCircuit, Parameter from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit_nature.second_q.operators import FermionicOp from qiskit_nature.second_q.mappers import JordanWignerMapper def kronecker_delta_function(n: int, m: int) -> int: """An implementation of the Kronecker delta function. Args: n (int): The first integer argument. m (int): The second integer argument. Returns: Returns 1 if n = m, else returns 0. """ return int(n == m) def create_deuteron_hamiltonian( N: int, hbar_omega: float = 7.0, V_0: float = -5.68658111 ) -> SparsePauliOp: """Creates a version of the Deuteron Hamiltonian as a qubit operator. Args: N (int): An integer number that represents the dimension of the basis. hbar_omega (float, optional): The value of the product of hbar and omega. Defaults to 7.0. V_0 (float, optional): The value of the potential energy. Defaults to -5.68658111. Returns: SparsePauliOp: The qubit-space Hamiltonian that represents the Deuteron. """ hamiltonian_terms = {} for m in range(N): for n in range(N): label = "+_{} -_{}".format(str(n), str(m)) coefficient_kinect = (hbar_omega / 2) * ( (2 * n + 3 / 2) * kronecker_delta_function(n, m) - np.sqrt(n * (n + (1 / 2))) * kronecker_delta_function(n, m + 1) - np.sqrt((n + 1) * (n + (3 / 2)) * kronecker_delta_function(n, m - 1)) ) hamiltonian_terms[label] = coefficient_kinect coefficient_potential = ( V_0 * kronecker_delta_function(n, 0) * kronecker_delta_function(n, m) ) hamiltonian_terms[label] += coefficient_potential hamiltonian = FermionicOp(hamiltonian_terms, num_spin_orbitals=N) mapper = JordanWignerMapper() qubit_hamiltonian = mapper.map(hamiltonian) if not isinstance(qubit_hamiltonian, SparsePauliOp): qubit_hamiltonian = qubit_hamiltonian.primitive return qubit_hamiltonian deuteron_hamiltonians = [create_deuteron_hamiltonian(i) for i in range(1, 5)] for i, hamiltonian in enumerate(deuteron_hamiltonians): print("Deuteron Hamiltonian: H_{}".format(i + 1)) print(hamiltonian) print("\n") theta = Parameter(r"$\theta$") eta = Parameter(r"$\eta$") wavefunction = QuantumCircuit(1) wavefunction.ry(theta, 0) wavefunction.draw("mpl") wavefunction2 = QuantumCircuit(2) wavefunction2.x(0) wavefunction2.ry(theta, 1) wavefunction2.cx(1, 0) wavefunction2.draw("mpl") wavefunction3 = QuantumCircuit(3) wavefunction3.x(0) wavefunction3.ry(eta, 1) wavefunction3.ry(theta, 2) wavefunction3.cx(2, 0) wavefunction3.cx(0, 1) wavefunction3.ry(-eta, 1) wavefunction3.cx(0, 1) wavefunction3.cx(1, 0) wavefunction3.draw("mpl") ansatz = [wavefunction, wavefunction2, wavefunction3] reference_values = [] print("Exact binding energies calculated through numpy.linalg.eigh \n") for i, hamiltonian in enumerate(deuteron_hamiltonians): eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix()) reference_values.append(eigenvalues[0]) print("Exact binding energy for H_{}: {}".format(i + 1, eigenvalues[0])) print( "Results using Estimator for H_1, H_2 and H_3 with the ansatz given in the reference paper \n" ) for i in range(3): seed = 42 algorithm_globals.random_seed = seed vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=SLSQP()) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) binding_energy = vqe_result.optimal_value print("Binding energy for H_{}: {} MeV".format(i + 1, binding_energy)) def callback(eval_count, parameters, mean, std): # Overwrites the same line when printing display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) plots = [] for i in range(3): counts = [] values = [] params = [] deviation = [] seed = 42 algorithm_globals.random_seed = seed vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=COBYLA(), callback=callback) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) plots.append([counts, values]) fig, ax = plt.subplots(nrows=3, ncols=1) fig.set_size_inches((12, 12)) for i, plot in enumerate(plots): ax[i].plot(plot[0], plot[1], "o-", label="COBYLA") ax[i].axhline( y=reference_values[i], color="k", linestyle="--", label=f"Reference Value: {reference_values[i]}", ) ax[i].legend() ax[i].set_xlabel("Cost Function Evaluations", fontsize=15) ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15) plt.show() twolocal_ansatzes = [] for i in range(1, 5): ansatz = TwoLocal( deuteron_hamiltonians[i - 1].num_qubits, ["rz", "ry"], "cx", entanglement="full", reps=i, initial_state=None, ) twolocal_ansatzes.append(ansatz) print("Results using Estimator for H_1, H_2, H_3 and H_4 with TwoLocal ansatz \n") seed = 42 algorithm_globals.random_seed = seed for i in range(4): vqe = VQE(Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP()) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) binding_energy = vqe_result.optimal_value print("Binding energy for H_{}:".format(i + 1), binding_energy, "MeV") seed = 42 algorithm_globals.random_seed = seed plots_tl = [] for i in range(4): counts = [] values = [] params = [] deviation = [] vqe = VQE( Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP(), callback=callback, ) vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i]) plots_tl.append([counts, values]) fig, ax = plt.subplots(nrows=4, ncols=1) fig.set_size_inches((15, 15)) for i, plot in enumerate(plots_tl): ax[i].plot(plot[0], plot[1], "o-", label="COBYLA") ax[i].axhline( y=reference_values[i], color="k", linestyle="--", label=f"Reference Value: {reference_values[i]}", ) ax[i].legend() ax[i].set_xlabel("Cost Function Evaluations", fontsize=15) ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15) plt.show() def calculate_observables_exp_values( quantum_circuit: QuantumCircuit, observables: list, angles: list ) -> list: """Calculate the expectation value of an observable given the quantum circuit that represents the wavefunction and a list of parameters. Args: quantum_circuit (QuantumCircuit): A parameterized quantum circuit that represents the wavefunction of the system. observables (list): A list containing the observables that we want to know the expectation values. angles (list): A list with the values that will be used in the 'bind_parameters' method. Returns: list_exp_values (list): A list containing the expectation values of the observables given as input. """ list_exp_values = [] for observable in observables: exp_values = [] for angle in angles: qc = quantum_circuit.bind_parameters({theta: angle}) result = estimate_observables( Estimator(), quantum_state=qc, observables=[observable], ) exp_values.append(result[0][0]) list_exp_values.append(exp_values) return list_exp_values angles = list(np.linspace(-np.pi, np.pi, 100)) observables = [ Pauli("IZ"), Pauli("ZI"), Pauli("XX"), Pauli("YY"), deuteron_hamiltonians[1], ] h2_observables_exp_values = calculate_observables_exp_values(wavefunction2, observables, angles) fig, ax = plt.subplots(nrows=2, ncols=1) fig.set_size_inches((12, 12)) ax[0].plot(angles, h2_observables_exp_values[0], "o", label=r"$Z_0$") ax[0].plot(angles, h2_observables_exp_values[1], "o", label=r"$Z_1$") ax[0].plot(angles, h2_observables_exp_values[2], "o", label=r"$X_0X_1$") ax[0].plot(angles, h2_observables_exp_values[3], "o", label=r"$Y_0Y_1$") ax[0].axhline( y=1, color="k", linestyle="--", ) ax[0].axhline(y=-1, color="k", linestyle="--") ax[0].legend() ax[0].set_xlabel(r"Theta - $\theta$", fontsize=15) ax[0].set_ylabel(r"$\langle O \rangle $ - Operator Expectation Value", fontsize=15) ax[0].set_xticks( [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"], ) ax[0].set_title( r"Expectation value of the observables $Z_0$, $Z_1$, $X_0X_1$ and $Y_0Y_1$ when we vary $\theta$ in the ansatz.", fontsize=15, ) ax[1].plot(angles, h2_observables_exp_values[4], "o") ax[1].axhline( y=reference_values[1], color="k", linestyle="--", label="Binding Energy: {} MeV".format(np.round(reference_values[1], 3)), ) ax[1].legend() ax[1].set_xlabel(r"Theta - $\theta$", fontsize=15) ax[1].set_ylabel(r"$\langle H_2 \rangle $ - Energy (MeV)", fontsize=15) ax[1].set_xticks( [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"], ) ax[1].set_title( r"Behavior of the expectation value of $H_2$ when we vary $\theta$ in the ansatz.", fontsize=15 ) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/lmarza/QuantumDeskCalculator
lmarza
import math from qiskit import * from utils import bcolors, executeQFT, evolveQFTStateSum, inverseQFT pie = math.pi def sum(a, b, qc): n = len(a)-1 # Compute the Fourier transform of register a for i in range(n+1): executeQFT(qc, a, n-i, pie) # Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> # to |F(ψ(reg_a+reg_b))> for i in range(n+1): evolveQFTStateSum(qc, a, b, n-i, pie) # Compute the inverse Fourier transform of register a for i in range(n+1): inverseQFT(qc, a, i, pie)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # 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 Backend Sampler V2.""" from __future__ import annotations import unittest from test import QiskitTestCase, combine import numpy as np from ddt import ddt from numpy.typing import NDArray from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, UnitaryGate from qiskit.primitives import PrimitiveResult, PubResult, StatevectorSampler from qiskit.primitives.backend_sampler_v2 import BackendSamplerV2 from qiskit.primitives.containers import BitArray from qiskit.primitives.containers.data_bin import DataBin from qiskit.primitives.containers.sampler_pub import SamplerPub from qiskit.providers import JobStatus from qiskit.providers.backend_compat import BackendV2Converter from qiskit.providers.basic_provider import BasicSimulator from qiskit.providers.fake_provider import Fake7QPulseV1, GenericBackendV2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager BACKENDS = [BasicSimulator(), Fake7QPulseV1(), BackendV2Converter(Fake7QPulseV1())] @ddt class TestBackendSamplerV2(QiskitTestCase): """Test for BackendSamplerV2""" def setUp(self): super().setUp() self._shots = 10000 self._seed = 123 self._options = {"default_shots": self._shots, "seed_simulator": self._seed} self._cases = [] hadamard = QuantumCircuit(1, 1, name="Hadamard") hadamard.h(0) hadamard.measure(0, 0) self._cases.append((hadamard, None, {0: 5000, 1: 5000})) # case 0 bell = QuantumCircuit(2, name="Bell") bell.h(0) bell.cx(0, 1) bell.measure_all() self._cases.append((bell, None, {0: 5000, 3: 5000})) # case 1 pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() self._cases.append((pqc, [0] * 6, {0: 10000})) # case 2 self._cases.append((pqc, [1] * 6, {0: 168, 1: 3389, 2: 470, 3: 5973})) # case 3 self._cases.append((pqc, [0, 1, 1, 2, 3, 5], {0: 1339, 1: 3534, 2: 912, 3: 4215})) # case 4 self._cases.append((pqc, [1, 2, 3, 4, 5, 6], {0: 634, 1: 291, 2: 6039, 3: 3036})) # case 5 pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() self._cases.append( (pqc2, [0, 1, 2, 3, 4, 5, 6, 7], {0: 1898, 1: 6864, 2: 928, 3: 311}) ) # case 6 def _assert_allclose(self, bitarray: BitArray, target: NDArray | BitArray, rtol=1e-1, atol=5e2): self.assertEqual(bitarray.shape, target.shape) for idx in np.ndindex(bitarray.shape): int_counts = bitarray.get_int_counts(idx) target_counts = ( target.get_int_counts(idx) if isinstance(target, BitArray) else target[idx] ) max_key = max(max(int_counts.keys()), max(target_counts.keys())) ary = np.array([int_counts.get(i, 0) for i in range(max_key + 1)]) tgt = np.array([target_counts.get(i, 0) for i in range(max_key + 1)]) np.testing.assert_allclose(ary, tgt, rtol=rtol, atol=atol, err_msg=f"index: {idx}") @combine(backend=BACKENDS) def test_sampler_run(self, backend): """Test run().""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) with self.subTest("single"): bell, _, target = self._cases[1] bell = pm.run(bell) sampler = BackendSamplerV2(backend=backend, options=self._options) job = sampler.run([bell], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("single with param"): pqc, param_vals, target = self._cases[2] sampler = BackendSamplerV2(backend=backend, options=self._options) pqc = pm.run(pqc) params = (param.name for param in pqc.parameters) job = sampler.run([(pqc, {params: param_vals})], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("multiple"): pqc, param_vals, target = self._cases[2] sampler = BackendSamplerV2(backend=backend, options=self._options) pqc = pm.run(pqc) params = (param.name for param in pqc.parameters) job = sampler.run( [(pqc, {params: [param_vals, param_vals, param_vals]})], shots=self._shots ) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array([target, target, target])) @combine(backend=BACKENDS) def test_sampler_run_multiple_times(self, backend): """Test run() returns the same results if the same input is given.""" bell, _, _ = self._cases[1] sampler = BackendSamplerV2(backend=backend, options=self._options) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) result1 = sampler.run([bell], shots=self._shots).result() meas1 = result1[0].data.meas result2 = sampler.run([bell], shots=self._shots).result() meas2 = result2[0].data.meas self._assert_allclose(meas1, meas2, rtol=0) @combine(backend=BACKENDS) def test_sample_run_multiple_circuits(self, backend): """Test run() with multiple circuits.""" bell, _, target = self._cases[1] sampler = BackendSamplerV2(backend=backend, options=self._options) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) result = sampler.run([bell, bell, bell], shots=self._shots).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target)) self._assert_allclose(result[1].data.meas, np.array(target)) self._assert_allclose(result[2].data.meas, np.array(target)) @combine(backend=BACKENDS) def test_sampler_run_with_parameterized_circuits(self, backend): """Test run() with parameterized circuits.""" pqc1, param1, target1 = self._cases[4] pqc2, param2, target2 = self._cases[5] pqc3, param3, target3 = self._cases[6] pm = generate_preset_pass_manager(optimization_level=0, backend=backend) pqc1, pqc2, pqc3 = pm.run([pqc1, pqc2, pqc3]) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run( [(pqc1, param1), (pqc2, param2), (pqc3, param3)], shots=self._shots ).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target1)) self._assert_allclose(result[1].data.meas, np.array(target2)) self._assert_allclose(result[2].data.meas, np.array(target3)) @combine(backend=BACKENDS) def test_run_1qubit(self, backend): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc, qc2 = pm.run([qc, qc2]) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) @combine(backend=BACKENDS) def test_run_2qubit(self, backend): """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() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc0, qc1, qc2, qc3 = pm.run([qc0, qc1, qc2, qc3]) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc0, qc1, qc2, qc3], shots=self._shots).result() self.assertEqual(len(result), 4) for i in range(4): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) @combine(backend=BACKENDS) def test_run_single_circuit(self, backend): """Test for single circuit case.""" sampler = BackendSamplerV2(backend=backend, options=self._options) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) with self.subTest("No parameter"): circuit, _, target = self._cases[1] circuit = pm.run(circuit) param_target = [ (None, np.array(target)), ({}, np.array(target)), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) with self.subTest("One parameter"): circuit = QuantumCircuit(1, 1, name="X gate") param = Parameter("x") circuit.ry(param, 0) circuit.measure(0, 0) circuit = pm.run(circuit) param_target = [ ({"x": np.pi}, np.array({1: self._shots})), ({param: np.pi}, np.array({1: self._shots})), ({"x": np.array(np.pi)}, np.array({1: self._shots})), ({param: np.array(np.pi)}, np.array({1: self._shots})), ({"x": [np.pi]}, np.array({1: self._shots})), ({param: [np.pi]}, np.array({1: self._shots})), ({"x": np.array([np.pi])}, np.array({1: self._shots})), ({param: np.array([np.pi])}, np.array({1: self._shots})), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, target) with self.subTest("More than one parameter"): circuit, param, target = self._cases[3] circuit = pm.run(circuit) param_target = [ (param, np.array(target)), (tuple(param), np.array(target)), (np.array(param), np.array(target)), ((param,), np.array([target])), ([param], np.array([target])), (np.array([param]), np.array([target])), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) @combine(backend=BACKENDS) def test_run_reverse_meas_order(self, backend): """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) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) sampler = BackendSamplerV2(backend=backend) sampler.options.seed_simulator = self._seed result = sampler.run([(qc, [0, 0]), (qc, [np.pi / 2, 0])], shots=self._shots).result() self.assertEqual(len(result), 2) # qc({x: 0, y: 0}) self._assert_allclose(result[0].data.c, np.array({1: self._shots})) # qc({x: pi/2, y: 0}) self._assert_allclose(result[1].data.c, np.array({1: self._shots / 2, 5: self._shots / 2})) @combine(backend=BACKENDS) def test_run_errors(self, backend): """Test for errors with run method""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc1, qc2 = pm.run([qc1, qc2]) sampler = BackendSamplerV2(backend=backend) with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, [1e2])]).result() with self.subTest("missing all parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, [])]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, None)]).result() with self.subTest("missing some parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2])]).result() with self.subTest("too many parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2] * 100)]).result() with self.subTest("negative shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=-1).result() with self.subTest("negative shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, -1)]).result() with self.subTest("negative shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=-1)]).result() with self.subTest("zero shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=0).result() with self.subTest("zero shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, 0)]).result() with self.subTest("zero shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=0)]).result() with self.subTest("missing []"): with self.assertRaisesRegex(ValueError, "An invalid Sampler pub-like was given"): _ = sampler.run(qc1).result() with self.subTest("missing [] for pqc"): with self.assertRaisesRegex(ValueError, "Note that if you want to run a single pub,"): _ = sampler.run((qc2, [0, 1])).result() @combine(backend=BACKENDS) def test_run_empty_parameter(self, backend): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) sampler = BackendSamplerV2(backend=backend, options=self._options) with self.subTest("one circuit"): result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, np.array({0: self._shots})) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.c, np.array({0: self._shots})) @combine(backend=BACKENDS) def test_run_numpy_params(self, backend): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) k = 5 params_array = np.linspace(0, 1, k * qc.num_parameters).reshape((k, qc.num_parameters)) params_list = params_array.tolist() sampler = StatevectorSampler(seed=self._seed) target = sampler.run([(qc, params_list)], shots=self._shots).result() with self.subTest("ndarray"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([(qc, params_array)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target[0].data.meas) with self.subTest("split a list"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run( [(qc, params) for params in params_list], shots=self._shots ).result() self.assertEqual(len(result), k) for i in range(k): self._assert_allclose( result[i].data.meas, np.array(target[0].data.meas.get_int_counts(i)) ) @combine(backend=BACKENDS) def test_run_with_shots_option(self, backend): """test with shots option.""" bell, _, _ = self._cases[1] pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) shots = 100 with self.subTest("run arg"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([bell], shots=shots).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) with self.subTest("default shots"): sampler = BackendSamplerV2(backend=backend, options=self._options) default_shots = sampler.options.default_shots result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) with self.subTest("setting default shots"): default_shots = 100 sampler = BackendSamplerV2(backend=backend, options=self._options) sampler.options.default_shots = default_shots self.assertEqual(sampler.options.default_shots, default_shots) result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) with self.subTest("pub-like"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([(bell, None, shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) with self.subTest("pub"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([SamplerPub(bell, shots=shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) with self.subTest("multiple pubs"): sampler = BackendSamplerV2(backend=backend, options=self._options) shots1 = 100 shots2 = 200 result = sampler.run( [ SamplerPub(bell, shots=shots1), SamplerPub(bell, shots=shots2), ], shots=self._shots, ).result() self.assertEqual(len(result), 2) self.assertEqual(result[0].data.meas.num_shots, shots1) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots1) self.assertEqual(result[1].data.meas.num_shots, shots2) self.assertEqual(sum(result[1].data.meas.get_counts().values()), shots2) @combine(backend=BACKENDS) def test_run_shots_result_size(self, backend): """test with shots option to validate the result size""" n = 7 # should be less than or equal to the number of qubits of backend qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self.assertLessEqual(result[0].data.meas.num_shots, self._shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), self._shots) @combine(backend=BACKENDS) def test_primitive_job_status_done(self, backend): """test primitive job's status""" bell, _, _ = self._cases[1] pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) sampler = BackendSamplerV2(backend=backend, options=self._options) job = sampler.run([bell], shots=self._shots) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) @combine(backend=BACKENDS) def test_circuit_with_unitary(self, backend): """Test for circuit with unitary gate.""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) with self.subTest("identity"): gate = UnitaryGate(np.eye(2)) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() circuit = pm.run(circuit) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) with self.subTest("X"): gate = UnitaryGate([[0, 1], [1, 0]]) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() circuit = pm.run(circuit) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({1: self._shots})) @combine(backend=BACKENDS) def test_circuit_with_multiple_cregs(self, backend): """Test for circuit with multiple classical registers.""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) cases = [] # case 1 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) qc = pm.run(qc) target = {"a": {0: 5000, 1: 5000}, "b": {0: 5000, 2: 5000}, "c": {0: 5000, 6: 5000}} cases.append(("use all cregs", qc, target)) # case 2 a = ClassicalRegister(1, "a") b = ClassicalRegister(5, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) qc = pm.run(qc) target = { "a": {0: 5000, 1: 5000}, "b": {0: 2500, 2: 2500, 24: 2500, 26: 2500}, "c": {0: 10000}, } cases.append(("use only a and b", qc, target)) # case 3 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure(1, 5) qc = pm.run(qc) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c", qc, target)) # case 4 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2], [5, 5, 5]) qc = pm.run(qc) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c multiple qubits", qc, target)) # case 5 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc = pm.run(qc) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 10000}} cases.append(("no measure", qc, target)) for title, qc, target in cases: with self.subTest(title): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg in qc.cregs: self.assertTrue(hasattr(data, creg.name)) self._assert_allclose(getattr(data, creg.name), np.array(target[creg.name])) @combine(backend=BACKENDS) def test_circuit_with_aliased_cregs(self, backend): """Test for circuit with aliased classical registers.""" q = QuantumRegister(3, "q") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c1, c2) qc.ry(np.pi / 4, 2) qc.cx(2, 1) qc.cx(0, 1) qc.h(0) qc.measure(0, c1) qc.measure(1, c2) qc.z(2).c_if(c1, 1) qc.x(2).c_if(c2, 1) qc2 = QuantumCircuit(5, 5) qc2.compose(qc, [0, 2, 3], [2, 4], inplace=True) cregs = [creg.name for creg in qc2.cregs] target = { cregs[0]: {0: 4255, 4: 4297, 16: 720, 20: 726}, cregs[1]: {0: 5000, 1: 5000}, cregs[2]: {0: 8500, 1: 1500}, } sampler = BackendSamplerV2(backend=backend, options=self._options) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc2 = pm.run(qc2) result = sampler.run([qc2], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg_name, creg in target.items(): self.assertTrue(hasattr(data, creg_name)) self._assert_allclose(getattr(data, creg_name), np.array(creg)) @combine(backend=BACKENDS) def test_no_cregs(self, backend): """Test that the sampler works when there are no classical register in the circuit.""" qc = QuantumCircuit(2) sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarns(UserWarning): result = sampler.run([qc]).result() self.assertEqual(len(result), 1) self.assertEqual(len(result[0].data), 0) @combine(backend=BACKENDS) def test_empty_creg(self, backend): """Test that the sampler works if provided a classical register with no bits.""" # Test case for issue #12043 q = QuantumRegister(1, "q") c1 = ClassicalRegister(0, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c1, c2) qc.h(0) qc.measure(0, 0) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(result[0].data.c1.array.shape, (self._shots, 0)) @combine(backend=BACKENDS) def test_diff_shots(self, backend): """Test of pubs with different shots""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell, _, target = self._cases[1] bell = pm.run(bell) sampler = BackendSamplerV2(backend=backend, options=self._options) shots2 = self._shots + 2 target2 = {k: v + 1 for k, v in target.items()} job = sampler.run([(bell, None, self._shots), (bell, None, shots2)]) result = job.result() self.assertEqual(len(result), 2) self.assertEqual(result[0].data.meas.num_shots, self._shots) self._assert_allclose(result[0].data.meas, np.array(target)) self.assertEqual(result[1].data.meas.num_shots, shots2) self._assert_allclose(result[1].data.meas, np.array(target2)) def test_job_size_limit_backend_v2(self): """Test BackendSamplerV2 respects backend's job size limit.""" class FakeBackendLimitedCircuits(GenericBackendV2): """Generic backend V2 with job size limit.""" @property def max_circuits(self): return 1 qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSamplerV2(backend=FakeBackendLimitedCircuits(num_qubits=5)) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertIsInstance(result, PrimitiveResult) self.assertEqual(len(result), 2) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[1], PubResult) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) self._assert_allclose(result[1].data.meas, np.array({1: self._shots})) def test_job_size_limit_backend_v1(self): """Test BackendSamplerV2 respects backend's job size limit.""" backend = Fake7QPulseV1() config = backend.configuration() config.max_experiments = 1 backend._configuration = config qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSamplerV2(backend=backend) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertIsInstance(result, PrimitiveResult) self.assertEqual(len(result), 2) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[1], PubResult) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) self._assert_allclose(result[1].data.meas, np.array({1: self._shots})) def test_iter_pub(self): """Test of an iterable of pubs""" backend = BasicSimulator() qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSamplerV2(backend=backend) result = sampler.run(iter([qc, qc2]), shots=self._shots).result() self.assertIsInstance(result, PrimitiveResult) self.assertEqual(len(result), 2) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[1], PubResult) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) self._assert_allclose(result[1].data.meas, np.array({1: self._shots})) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np # Import Qiskit from qiskit import QuantumCircuit from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_state_city import qiskit.quantum_info as qi Aer.backends() simulator = Aer.get_backend('aer_simulator') # Create circuit circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.measure_all() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) plot_histogram(counts, title='Bell-State counts') # Run and get memory result = simulator.run(circ, shots=10, memory=True).result() memory = result.get_memory(circ) print(memory) # Increase shots to reduce sampling variance shots = 10000 # Stabilizer simulation method sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer') job_stabilizer = sim_stabilizer.run(circ, shots=shots) counts_stabilizer = job_stabilizer.result().get_counts(0) # Statevector simulation method sim_statevector = Aer.get_backend('aer_simulator_statevector') job_statevector = sim_statevector.run(circ, shots=shots) counts_statevector = job_statevector.result().get_counts(0) # Density Matrix simulation method sim_density = Aer.get_backend('aer_simulator_density_matrix') job_density = sim_density.run(circ, shots=shots) counts_density = job_density.result().get_counts(0) # Matrix Product State simulation method sim_mps = Aer.get_backend('aer_simulator_matrix_product_state') job_mps = sim_mps.run(circ, shots=shots) counts_mps = job_mps.result().get_counts(0) plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps], title='Counts for different simulation methods', legend=['stabilizer', 'statevector', 'density_matrix', 'matrix_product_state']) from qiskit_aer import AerError # Initialize a GPU backend # Note that the cloud instance for tutorials does not have a GPU # so this will raise an exception. try: simulator_gpu = Aer.get_backend('aer_simulator') simulator_gpu.set_options(device='GPU') except AerError as e: print(e) # Configure a single-precision statevector simulator backend simulator = Aer.get_backend('aer_simulator_statevector') simulator.set_options(precision='single') # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) print(counts) # Construct quantum circuit without measure circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_statevector() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get statevector result = simulator.run(circ).result() statevector = result.get_statevector(circ) plot_state_city(statevector, title='Bell state') # Construct quantum circuit without measure circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.save_unitary() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get unitary result = simulator.run(circ).result() unitary = result.get_unitary(circ) print("Circuit unitary:\n", np.asarray(unitary).round(5)) # Construct quantum circuit without measure steps = 5 circ = QuantumCircuit(1) for i in range(steps): circ.save_statevector(label=f'psi_{i}') circ.rx(i * np.pi / steps, 0) circ.save_statevector(label=f'psi_{steps}') # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() data = result.data(0) data # Generate a random statevector num_qubits = 2 psi = qi.random_statevector(2 ** num_qubits, seed=100) # Set initial state to generated statevector circ = QuantumCircuit(num_qubits) circ.set_statevector(psi) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) # Use initilize instruction to set initial state circ = QuantumCircuit(num_qubits) circ.initialize(psi, range(num_qubits)) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get result data result = simulator.run(circ).result() result.data(0) num_qubits = 2 rho = qi.random_density_matrix(2 ** num_qubits, seed=100) circ = QuantumCircuit(num_qubits) circ.set_density_matrix(rho) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) # Generate a random Clifford C num_qubits = 2 stab = qi.random_clifford(num_qubits, seed=100) # Set initial state to stabilizer state C|0> circ = QuantumCircuit(num_qubits) circ.set_stabilizer(stab) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) # Generate a random unitary num_qubits = 2 unitary = qi.random_unitary(2 ** num_qubits, seed=100) # Set initial state to unitary circ = QuantumCircuit(num_qubits) circ.set_unitary(unitary) circ.save_state() # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get saved data result = simulator.run(circ).result() result.data(0) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
# Importing standard Qiskit libraries from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import Aer, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city, plot_state_paulivec, plot_state_hinton # Ignore warnings import warnings warnings.filterwarnings('ignore') # Define backend sim = Aer.get_backend('aer_simulator') def createBellStates(inp1, inp2): qc = QuantumCircuit(2) qc.reset(range(2)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() qc.h(0) qc.cx(0,1) qc.save_statevector() qobj = assemble(qc) result = sim.run(qobj).result() state = result.get_statevector() return qc, state, result print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n') inp1 = 0 inp2 = 1 qc, state, result = createBellStates(inp1, inp2) display(plot_bloch_multivector(state)) # Uncomment below code in order to explore other states #for inp2 in ['0', '1']: #for inp1 in ['0', '1']: #qc, state, result = createBellStates(inp1, inp2) #print('For inputs',inp2,inp1,'Representation of Entangled States are:') # Uncomment any of the below functions to visualize the resulting quantum states # Draw the quantum circuit #display(qc.draw()) # Plot states on QSphere #display(plot_state_qsphere(state)) # Plot states on Bloch Multivector #display(plot_bloch_multivector(state)) # Plot histogram #display(plot_histogram(result.get_counts())) # Plot state matrix like a city #display(plot_state_city(state)) # Represent state matix using Pauli operators as the basis #display(plot_state_paulivec(state)) # Plot state matrix as Hinton representation #display(plot_state_hinton(state)) #print('\n')''' from qiskit import IBMQ, execute from qiskit.providers.ibmq import least_busy from qiskit.tools import job_monitor # Loading your IBM Quantum account(s) provider = IBMQ.load_account() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) def createBSRealDevice(inp1, inp2): qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.reset(range(2)) if inp1 == 1: qc.x(0) if inp2 == 1: qc.x(1) qc.barrier() qc.h(0) qc.cx(0,1) qc.measure(qr, cr) job = execute(qc, backend=backend, shots=100) job_monitor(job) result = job.result() return qc, result inp1 = 0 inp2 = 0 print('For inputs',inp2,inp1,'Representation of Entangled States are,') #first results qc, first_result = createBSRealDevice(inp1, inp2) first_counts = first_result.get_counts() # Draw the quantum circuit display(qc.draw()) #second results qc, second_result = createBSRealDevice(inp1, inp2) second_counts = second_result.get_counts() # Plot results on histogram with legend legend = ['First execution', 'Second execution'] plot_histogram([first_counts, second_counts], legend=legend) def ghzCircuit(inp1, inp2, inp3): qc = QuantumCircuit(3) qc.reset(range(3)) if inp1 == 1: qc.x(0) if inp2 == 1: qc.x(1) if inp3 == 1: qc.x(2) qc.barrier() qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.save_statevector() qobj = assemble(qc) result = sim.run(qobj).result() state = result.get_statevector() return qc, state, result print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n') inp1 = 0 inp2 = 1 inp3 = 1 qc, state, result = ghzCircuit(inp1, inp2, inp3) display(plot_bloch_multivector(state)) # Uncomment below code in order to explore other states #for inp3 in ['0','1']: #for inp2 in ['0','1']: #for inp1 in ['0','1']: #qc, state, result = ghzCircuit(inp1, inp2, inp3) #print('For inputs',inp3,inp2,inp1,'Representation of GHZ States are:') # Uncomment any of the below functions to visualize the resulting quantum states # Draw the quantum circuit #display(qc.draw()) # Plot states on QSphere #display(plot_state_qsphere(state)) # Plot states on Bloch Multivector #display(plot_bloch_multivector(state)) # Plot histogram #display(plot_histogram(result.get_counts())) # Plot state matrix like a city #display(plot_state_city(state)) # Represent state matix using Pauli operators as the basis #display(plot_state_paulivec(state)) # Plot state matrix as Hinton representation #display(plot_state_hinton(state)) #print('\n') def ghz5QCircuit(inp1, inp2, inp3, inp4, inp5): qc = QuantumCircuit(5) #qc.reset(range(5)) if inp1 == 1: qc.x(0) if inp2 == 1: qc.x(1) if inp3 == 1: qc.x(2) if inp4 == 1: qc.x(3) if inp5 == 1: qc.x(4) qc.barrier() qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.cx(0,3) qc.cx(0,4) qc.save_statevector() qobj = assemble(qc) result = sim.run(qobj).result() state = result.get_statevector() return qc, state, result # Explore GHZ States for input 00010. Note: the input has been stated in little-endian format. inp1 = 0 inp2 = 1 inp3 = 0 inp4 = 0 inp5 = 0 qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') display(plot_state_qsphere(state)) print('\n') # Explore GHZ States for input 11001. Note: the input has been stated in little-endian format. inp1 = 1 inp2 = 0 inp3 = 0 inp4 = 1 inp5 = 1 qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') display(plot_state_qsphere(state)) print('\n') # Explore GHZ States for input 01010. Note: the input has been stated in little-endian format. inp1 = 0 inp2 = 1 inp3 = 0 inp4 = 1 inp5 = 0 qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') display(plot_state_qsphere(state)) print('\n') # Uncomment below code in order to explore other states #for inp5 in ['0','1']: #for inp4 in ['0','1']: #for inp3 in ['0','1']: #for inp2 in ['0','1']: #for inp1 in ['0','1']: #qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) #print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') # Uncomment any of the below functions to visualize the resulting quantum states # Draw the quantum circuit #display(qc.draw()) # Plot states on QSphere #display(plot_state_qsphere(state)) # Plot states on Bloch Multivector #display(plot_bloch_multivector(state)) # Plot histogram #display(plot_histogram(result.get_counts())) # Plot state matrix like a city #display(plot_state_city(state)) # Represent state matix using Pauli operators as the basis #display(plot_state_paulivec(state)) # Plot state matrix as Hinton representation #display(plot_state_hinton(state)) #print('\n') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 5 and not x.configuration().simulator and x.status().operational==True)) def create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5): qr = QuantumRegister(5) cr = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.reset(range(5)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) if inp3=='1': qc.x(1) if inp4=='1': qc.x(1) if inp5=='1': qc.x(1) qc.barrier() qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.cx(0,3) qc.cx(0,4) qc.measure(qr, cr) job = execute(qc, backend=backend, shots=1000) job_monitor(job) result = job.result() return qc, result inp1 = 0 inp2 = 0 inp3 = 0 inp4 = 0 inp5 = 0 #first results qc, first_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5) first_counts = first_result.get_counts() # Draw the quantum circuit display(qc.draw()) #second results qc, second_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5) second_counts = second_result.get_counts() print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ circuit states are,') # Plot results on histogram with legend legend = ['First execution', 'Second execution'] plot_histogram([first_counts, second_counts], legend=legend) import qiskit qiskit.__qiskit_version__
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qc1 = QuantumCircuit(3,3) # All initialized to '0' by default. qc1.x(0) #This is for the purpose of setting the control qubit to '1' qc1.x(2) #As a result, the second target qubit becomes '1' while the first remains '0'. Now, lets's try swapping them. #Fredkin gate: def fredkin(qc): qc.toffoli(0,1,2) qc.toffoli(0,2,1) qc.toffoli(0,1,2) fredkin(qc1) qc1.draw('mpl') #First let's measure all three qubits. #We're using the classical bits to store the result obtained on measuring each corresponding qubit. qc1.measure(0,0) qc1.measure(1,1) qc1.measure(2,2) #Now we use the same function we defined yesterday to run a quantum circuit def run_circuit(qc2): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc2, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts1=run_circuit(qc1) print(counts1) plot_histogram(counts1) qc2 = QuantumCircuit(3,3) # All initialized to '0' by default. qc2.x(2) #The second target qubit is initialised to '1' fredkin(qc2) qc2.measure(0,0) qc2.measure(1,1) qc2.measure(2,2) qc2.draw(output='mpl') counts2=run_circuit(qc2) print(counts2) plot_histogram(counts2) qc = QuantumCircuit(1) #This is how we apply the rotation operators in Qiskit, mentioning the angle of rotation and qubit no. as parameters qc.rx(np.pi/2, 0) qc.draw('mpl') def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate print(final_vector(qc)) # This prints the vector obtained on applying the above gate to the qubit state '0' # The Pauli-X gate serves this purpose, as demonstrated below: qc3 = QuantumCircuit(1) theta = np.pi/7 qc3.x(0) qc3.ry(theta, 0) qc3.x(0) print(final_vector(qc3)) qc3 = QuantumCircuit(1) qc3.ry(-theta, 0) print(final_vector(qc3)) #Run this code for different values of theta and see if the two vectors printed are equal in each case qc4 = QuantumCircuit(1) alpha = np.pi/2 beta = 0 gamma = np.pi/2 delta = np.pi def A(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) C(qc4, 0, beta, delta) qc4.x(0) B(qc4, 0, beta, gamma, delta) qc4.x(0) A(qc4, 0, beta, gamma) qc4.unitary([[1.j, 0.], [0., 1.j]], [0]) print(final_vector(qc4)) qc4 = QuantumCircuit(1) qc4.h(0) print(final_vector(qc4)) qc5 = QuantumCircuit(3, 3) # Target qubit q1 is initially |1> and target qubit q2 is initially |0>. qc5.x(0) # Control qubit initialized to |1> to see effects of controlled Hadamard. qc5.x(1) # One target qubit initialized to |1>. alpha = np.pi/2 beta = 0 gamma = np.pi/2 delta = np.pi def A(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) C(qc5, [1, 2], beta, delta) qc5.cx(0, [1, 2]) B(qc5, [1, 2], beta, gamma, delta) qc5.cx(0, [1, 2]) A(qc5, [1, 2], beta, gamma) qc5.s(0) # Using S gate because alpha = pi/2 qc5.measure(0, 0) qc5.measure(1, 1) qc5.measure(2, 2) qc5.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 10000).result() counts = result.get_counts() return counts counts = run_circuit(qc5) print(counts) plot_histogram(counts) qc_u3=QuantumCircuit(1) qc_u3.u3(np.pi/6,-np.pi/2,np.pi/2,0) print(final_vector(qc_u3)) qc_rx=QuantumCircuit(1) qc_rx.rx(np.pi/6,0) print(final_vector(qc_rx)) #Getting the same results will verify our observation stated above ######### Defining some constants and functions ########## # Constants for the decomposition of Hadamard gate. H_alpha = np.pi/2 H_beta = 0 H_gamma = np.pi/2 H_delta = np.pi # V^2 = X V = [[0.5+0.5j, 0.5-0.5j], [0.5-0.5j, 0.5+0.5j]] # Constants for the decomposition of V (where V^2 = X). V_alpha = np.pi/4 V_beta = np.pi/2 V_gamma = -np.pi/2 V_delta = -np.pi/2 # Functions to implement A, B, C (generalized). def A_gate(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B_gate(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C_gate(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) # Higher abstraction functions. def controlled_V(qc, control, target): C_gate(qc, target, V_beta, V_delta) qc.cx(control, target) B_gate(qc, target, V_beta, V_gamma, V_delta) qc.cx(control, target) A_gate(qc, target, V_beta, V_gamma) qc.t(control) # Using T gate because V_alpha = pi/4. def controlled_Vdg(qc, control, target): C_gate(qc, target, V_beta, V_delta) qc.cx(control, target) B_gate(qc, target, V_beta, -V_gamma, V_delta) qc.cx(control, target) A_gate(qc, target, V_beta, -V_gamma) qc.tdg(control) # Using Tdg gate because V_alpha = pi/4, so Vdg_alpha would be -pi/4. def double_controlled_X(qc, control1, control2, target): controlled_V(qc, control2, target) qc.cx(control1, control2) controlled_Vdg(qc, control2, target) qc.cx(control1, control2) controlled_V(qc, control1, target) ############ Constructing the circuit ############## qc6 = QuantumCircuit(7, 5) # No need to measure ancillary qubits :P # q0, q1, q2, q3 are control qubits # q4, q5 are ancillary qubits # q6 is the target qubit # Change the following line to try different combinations of control qubits: qc6.x([0,1,2,3]) C_gate(qc6, 6, H_beta, H_delta) double_controlled_X(qc6, 0, 1, 4) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 4, 5, 6) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 0, 1, 4) B_gate(qc6, 6, H_beta, H_gamma, H_delta) double_controlled_X(qc6, 0, 1, 4) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 4, 5, 6) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 0, 1, 4) A_gate(qc6, 6, H_beta, H_gamma) qc6.s([0,1,2,3]) # Using S gate because H_alpha = pi/2. qc6.measure(0, 0) qc6.measure(1, 1) qc6.measure(2, 2) qc6.measure(3, 3) qc6.measure(6, 4) qc6.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 2000).result() counts = result.get_counts() return counts counts = run_circuit(qc6) print(counts) plot_histogram(counts)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def BuildGHZ(n): U = QuantumCircuit(n) U.h(0) for i in range(1, n): U.cx(0, i) U = U.to_gate() U.name = 'Build GHZ' #ctl_U = U.control() make it a controlled gate return U n = 5 mc = QuantumCircuit(n, n) U = BuildGHZ(n) mc.append(U, range(n)) mc.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mc, backend=backend, shots=atp).result() ans = res.get_counts() mc.draw('mpl') plot_histogram(ans)
https://github.com/pkaran57/quantum-computing-final-project
pkaran57
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") from qiskit import transpile, schedule as build_schedule from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1 schedule = build_schedule(transpiled_circ, backend) schedule.draw() from qiskit import pulse with pulse.build() as h_q0: pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'), pulse.DriveChannel(0)) circ.add_calibration('h', [0], h_q0) schedule = build_schedule(circ, backend) schedule.draw() circ = QuantumCircuit(2, 2) circ.x(0) circ.x(0) circ.x(1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") schedule = build_schedule(circ, backend, method="as_late_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() schedule = build_schedule(circ, backend, method="as_soon_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) qc.z(1) matrix = DensityMatrix(qc) plot_state_qsphere(matrix, show_state_phases = True, use_degrees = True)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) es_problem = driver.run() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver numpy_solver = NumPyMinimumEigensolver() from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD ansatz = UCCSD( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, initial_state=HartreeFock( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, ), ) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = [0.0] * ansatz.num_parameters from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.circuit.library import TwoLocal tl_circuit = TwoLocal( rotation_blocks=["h", "rx"], entanglement_blocks="cz", entanglement="full", reps=2, parameter_prefix="y", ) another_solver = VQE(Estimator(), tl_circuit, SLSQP()) from qiskit_nature.second_q.algorithms import GroundStateEigensolver calc = GroundStateEigensolver(mapper, vqe_solver) res = calc.solve(es_problem) print(res) calc = GroundStateEigensolver(mapper, numpy_solver) res = calc.solve(es_problem) print(res) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.mappers import DirectMapper from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis([2, 2, 2, 2]) vib_problem = driver.run(basis=basis) vib_problem.hamiltonian.truncation_order = 2 mapper = DirectMapper() solver_without_filter = NumPyMinimumEigensolver() solver_with_filter = NumPyMinimumEigensolver( filter_criterion=vib_problem.get_default_filter_criterion() ) gsc_wo = GroundStateEigensolver(mapper, solver_without_filter) result_wo = gsc_wo.solve(vib_problem) gsc_w = GroundStateEigensolver(mapper, solver_with_filter) result_w = gsc_w.solve(vib_problem) print(result_wo) print("\n\n") print(result_w) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/neelkamath/quantum-experiments
neelkamath
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector ### Creating 3 qubit and 2 classical bits in each separate register qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) ### A third party eve helps to create an entangled state def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a, b) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, a, b): qc.cx(a, b) qc.h(a) teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): qc.barrier() qc.measure(a,0) qc.measure(b,1) teleportation_circuit.barrier() measure_and_send(teleportation_circuit, 0, 1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) qc.z(qubit).c_if(crz, 1) teleportation_circuit.barrier() bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() from qiskit.extensions import Initialize import math qc = QuantumCircuit(1) initial_state = [0,1] init_gate = Initialize(initial_state) # qc.append(initialize_qubit, [0]) qr = QuantumRegister(3) # Protocol uses 3 qubits crz = ClassicalRegister(1) # and 2 classical registers crx = ClassicalRegister(1) qc = QuantumCircuit(qr, crz, crx) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) # Bob decodes qubits bob_gates(qc, 2, crz, crx) qc.draw() backend = BasicAer.get_backend('statevector_simulator') out_vector = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out_vector) inverse_init_gate = init_gate.gates_to_uncompute() qc.append(inverse_init_gate, [2]) qc.draw() cr_result = ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw() backend = BasicAer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1024).result().get_counts() plot_histogram(counts) def bob_gates(qc, a, b, c): qc.cz(a, c) qc.cx(b, c) qc = QuantumCircuit(3,1) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) qc.barrier() # Alice sends classical bits to Bob bob_gates(qc, 0, 1, 2) # We undo the initialisation process qc.append(inverse_init_gate, [2]) # See the results, we only care about the state of qubit 2 qc.measure(2,0) # View the results: qc.draw() from qiskit import IBMQ IBMQ.save_account('### IMB TOKEN ') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) job_exp = execute(qc, backend=backend, shots=8192) exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(qc) print(exp_measurement_result) plot_histogram(exp_measurement_result) error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \ * 100./ sum(list(exp_measurement_result.values())) print("The experimental error rate : ", error_rate_percent, "%")
https://github.com/IvanIsCoding/Quantum
IvanIsCoding
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/Heisenbug-s-Dog/qnn_visualization
Heisenbug-s-Dog
# 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 # # https://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. pip install tensorflow==1.5.1 !pip -q install lucid>=0.3.8 !pip -q install umap-learn>=0.3.7 # General support import math import tensorflow as tf import numpy as np # For plots import matplotlib.pyplot as plt # Dimensionality reduction import umap from sklearn.manifold import TSNE # General lucid code from lucid.misc.io import save, show, load import lucid.modelzoo.vision_models as models # For rendering feature visualizations import lucid.optvis.objectives as objectives import lucid.optvis.param as param import lucid.optvis.render as render import lucid.optvis.transform as transform model = models.InceptionV1() model.load_graphdef() # model.layers[7] is "mixed4c" layer = "mixed4c" print(model.layers[7]) raw_activations = model.layers[7].activations activations = raw_activations[:100000] print(activations.shape) def whiten(full_activations): correl = np.matmul(full_activations.T, full_activations) / len(full_activations) correl = correl.astype("float32") S = np.linalg.inv(correl) S = S.astype("float32") return S S = whiten(raw_activations) def normalize_layout(layout, min_percentile=1, max_percentile=99, relative_margin=0.1): """Removes outliers and scales layout to between [0,1].""" # compute percentiles mins = np.percentile(layout, min_percentile, axis=(0)) maxs = np.percentile(layout, max_percentile, axis=(0)) # add margins mins -= relative_margin * (maxs - mins) maxs += relative_margin * (maxs - mins) # `clip` broadcasts, `[None]`s added only for readability clipped = np.clip(layout, mins, maxs) # embed within [0,1] along both axes clipped -= clipped.min(axis=0) clipped /= clipped.max(axis=0) return clipped layout = umap.UMAP(n_components=2, verbose=True, n_neighbors=20, min_dist=0.01, metric="cosine").fit_transform(activations) ## You can optionally use TSNE as well # layout = TSNE(n_components=2, verbose=True, metric="cosine", learning_rate=10, perplexity=50).fit_transform(d) layout = normalize_layout(layout) plt.figure(figsize=(10, 10)) plt.scatter(x=layout[:,0],y=layout[:,1], s=2) plt.show() # # Whitened, euclidean neuron objective # @objectives.wrap_objective def direction_neuron_S(layer_name, vec, batch=None, x=None, y=None, S=None): def inner(T): layer = T(layer_name) shape = tf.shape(layer) x_ = shape[1] // 2 if x is None else x y_ = shape[2] // 2 if y is None else y if batch is None: raise RuntimeError("requires batch") acts = layer[batch, x_, y_] vec_ = vec if S is not None: vec_ = tf.matmul(vec_[None], S)[0] # mag = tf.sqrt(tf.reduce_sum(acts**2)) dot = tf.reduce_mean(acts * vec_) # cossim = dot/(1e-4 + mag) return dot return inner # # Whitened, cosine similarity objective # @objectives.wrap_objective def direction_neuron_cossim_S(layer_name, vec, batch=None, x=None, y=None, cossim_pow=1, S=None): def inner(T): layer = T(layer_name) shape = tf.shape(layer) x_ = shape[1] // 2 if x is None else x y_ = shape[2] // 2 if y is None else y if batch is None: raise RuntimeError("requires batch") acts = layer[batch, x_, y_] vec_ = vec if S is not None: vec_ = tf.matmul(vec_[None], S)[0] mag = tf.sqrt(tf.reduce_sum(acts**2)) dot = tf.reduce_mean(acts * vec_) cossim = dot/(1e-4 + mag) cossim = tf.maximum(0.1, cossim) return dot * cossim ** cossim_pow return inner # # Renders a batch of activations as icons # def render_icons(directions, model, layer, size=80, n_steps=128, verbose=False, S=None, num_attempts=2, cossim=True, alpha=True): image_attempts = [] loss_attempts = [] # Render multiple attempts, and pull the one with the lowest loss score. for attempt in range(num_attempts): # Render an image for each activation vector param_f = lambda: param.image(size, batch=directions.shape[0], fft=True, decorrelate=True, alpha=alpha) if(S is not None): if(cossim is True): obj_list = ([ direction_neuron_cossim_S(layer, v, batch=n, S=S, cossim_pow=4) for n,v in enumerate(directions) ]) else: obj_list = ([ direction_neuron_S(layer, v, batch=n, S=S) for n,v in enumerate(directions) ]) else: obj_list = ([ objectives.direction_neuron(layer, v, batch=n) for n,v in enumerate(directions) ]) obj = objectives.Objective.sum(obj_list) transforms = [] if alpha: transforms.append(transform.collapse_alpha_random()) transforms.append(transform.pad(2, mode='constant', constant_value=1)) transforms.append(transform.jitter(4)) transforms.append(transform.jitter(4)) transforms.append(transform.jitter(8)) transforms.append(transform.jitter(8)) transforms.append(transform.jitter(8)) transforms.append(transform.random_scale([0.995**n for n in range(-5,80)] + [0.998**n for n in 2*list(range(20,40))])) transforms.append(transform.random_rotate(list(range(-20,20))+list(range(-10,10))+list(range(-5,5))+5*[0])) transforms.append(transform.jitter(2)) # This is the tensorflow optimization process. # We can't use the lucid helpers here because we need to know the loss. print("attempt: ", attempt) with tf.Graph().as_default(), tf.Session() as sess: learning_rate = 0.05 losses = [] trainer = tf.train.AdamOptimizer(learning_rate) T = render.make_vis_T(model, obj, param_f, trainer, transforms) loss_t, vis_op, t_image = T("loss"), T("vis_op"), T("input") losses_ = [obj_part(T) for obj_part in obj_list] tf.global_variables_initializer().run() for i in range(n_steps): loss, _ = sess.run([losses_, vis_op]) losses.append(loss) if (i % 100 == 0): print(i) img = t_image.eval() img_rgb = img[:,:,:,:3] if alpha: print("alpha true") k = 0.8 bg_color = 0.0 img_a = img[:,:,:,3:] img_merged = img_rgb*((1-k)+k*img_a) + bg_color * k*(1-img_a) image_attempts.append(img_merged) else: print("alpha false") image_attempts.append(img_rgb) loss_attempts.append(losses[-1]) # Use the icon with the lowest loss loss_attempts = np.asarray(loss_attempts) loss_final = [] image_final = [] print("Merging best scores from attempts...") for i, d in enumerate(directions): # note, this should be max, it is not a traditional loss mi = np.argmax(loss_attempts[:,i]) image_final.append(image_attempts[mi][i]) return (image_final, loss_final) # # Takes a list of x,y layout and bins them into grid cells # def grid(xpts=None, ypts=None, grid_size=(8,8), x_extent=(0., 1.), y_extent=(0., 1.)): xpx_length = grid_size[0] ypx_length = grid_size[1] xpt_extent = x_extent ypt_extent = y_extent xpt_length = xpt_extent[1] - xpt_extent[0] ypt_length = ypt_extent[1] - ypt_extent[0] xpxs = ((xpts - xpt_extent[0]) / xpt_length) * xpx_length ypxs = ((ypts - ypt_extent[0]) / ypt_length) * ypx_length ix_s = range(grid_size[0]) iy_s = range(grid_size[1]) xs = [] for xi in ix_s: ys = [] for yi in iy_s: xpx_extent = (xi, (xi + 1)) ypx_extent = (yi, (yi + 1)) in_bounds_x = np.logical_and(xpx_extent[0] <= xpxs, xpxs <= xpx_extent[1]) in_bounds_y = np.logical_and(ypx_extent[0] <= ypxs, ypxs <= ypx_extent[1]) in_bounds = np.logical_and(in_bounds_x, in_bounds_y) in_bounds_indices = np.where(in_bounds)[0] ys.append(in_bounds_indices) xs.append(ys) return np.asarray(xs) def render_layout(model, layer, S, xs, ys, activ, n_steps=512, n_attempts=2, min_density=10, grid_size=(10, 10), icon_size=80, x_extent=(0., 1.0), y_extent=(0., 1.0)): grid_layout = grid(xpts=xs, ypts=ys, grid_size=grid_size, x_extent=x_extent, y_extent=y_extent) icons = [] for x in range(grid_size[0]): for y in range(grid_size[1]): indices = grid_layout[x, y] if len(indices) > min_density: average_activation = np.average(activ[indices], axis=0) icons.append((average_activation, x, y)) icons = np.asarray(icons) icon_batch, losses = render_icons(icons[:,0], model, alpha=False, layer=layer, S=S, n_steps=n_steps, size=icon_size, num_attempts=n_attempts) canvas = np.ones((icon_size * grid_size[0], icon_size * grid_size[1], 3)) for i, icon in enumerate(icon_batch): y = int(icons[i, 1]) x = int(icons[i, 2]) canvas[(grid_size[0] - x - 1) * icon_size:(grid_size[0] - x) * icon_size, (y) * icon_size:(y + 1) * icon_size] = icon return canvas # # Given a layout, renders an icon for the average of all the activations in each grid cell. # xs = layout[:, 0] ys = layout[:, 1] canvas = render_layout(model, layer, S, xs, ys, raw_activations, n_steps=512, grid_size=(20, 20), n_attempts=1) show(canvas)
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_histogram import numpy as np # creating a constant oracle, input has no effect on the ouput # Create a quantum circuit with 2 qubits. One as input and other as output constant_oracle = QuantumCircuit(2) # get a random number from 0 or 1 output = np.random.randint(2) # what ever get in input, its having no effect. # the output will be the random value 0 or 1 if output == 1: constant_oracle.x(1) # draw the circuit constant_oracle.draw('mpl') # creating a balanced oracle, # perform CNOTs with first qubit input as a control and the second qubit output as the target. balanced_oracle = QuantumCircuit(2) # Place X-gate for input qubit balanced_oracle.x(0) # Use barrier as divider balanced_oracle.barrier() # Place Controlled-NOT gates balanced_oracle.cx(0, 1) # using barrier as a divider and avoid cancelling gates by the transpiler balanced_oracle.barrier() # Place X-gates balanced_oracle.x(0) # Show oracle balanced_oracle.draw('mpl') #initialise the input qubits in the state |+⟩ # and the output qubit in the state |−⟩ dj_circuit = QuantumCircuit(2, 1) # Apply H-gates dj_circuit.h(0) # Put qubit in state |-> dj_circuit.x(1) dj_circuit.h(1) dj_circuit.draw('mpl') # define the oracle function to use #oracle_fn = constant_oracle oracle_fn = balanced_oracle # Add oracle function dj_circuit += oracle_fn dj_circuit.draw('mpl') # perform H-gates on qubit and measure input register dj_circuit.h(qubit) dj_circuit.barrier() # Measure dj_circuit.measure(0, 0) # Display circuit dj_circuit.draw('mpl') # check the output # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(dj_circuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np import json import csv # Array of JSON Objects header = ['instance','p','distance', 'mean'] length_p = 3 length_instances = 2 with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) instance_index = 0 for instance in range(length_instances): instance_index += 1 first_p = False UNIFORM_CONVERGENCE_P = [] UNIFORM_CONVERGENCE_SAMPLE = [] for p in range(length_p): p = p+1 if first_p == False: print("Vuelve a llamar a test_solution") job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p) first_p = True else: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0] UNIFORM_CONVERGENCE_P.append({ "mean":convergence_min["mean"], "probabilities": convergence_min["probabilities"] }) cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1] p_index = 0 for p_state in UNIFORM_CONVERGENCE_P: p_index += 1 print(p_index) mean = p_state["mean"] print(p_state) print(mean) distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"])) writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/Qubit-MU/Qiskit_Fall_Fest_2023
Qubit-MU
######################################## # ENTER YOUR NAME AND WISC EMAIL HERE: # ######################################## # Name: Rochelle Li # Email: rli484@wisc.edu ## Run this cell to make sure your grader is setup correctly %set_env QC_GRADE_ONLY=true %set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com from qiskit import QuantumCircuit from qiskit.circuit import QuantumRegister, ClassicalRegister qr = QuantumRegister(1) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # unpack the qubit and classical bits from the registers (q0,) = qr b0, b1 = cr # apply Hadamard qc.h(q0) # measure qc.measure(q0, b0) # begin if test block. the contents of the block are executed if b0 == 1 with qc.if_test((b0, 1)): # if the condition is satisfied (b0 == 1), then flip the bit back to 0 qc.x(q0) # finally, measure q0 again qc.measure(q0, b1) qc.draw(output="mpl", idle_wires=False) from qiskit_aer import AerSimulator # initialize the simulator backend_sim = AerSimulator() # run the circuit reset_sim_job = backend_sim.run(qc) # get the results reset_sim_result = reset_sim_job.result() # retrieve the bitstring counts reset_sim_counts = reset_sim_result.get_counts() print(f"Counts: {reset_sim_counts}") from qiskit.visualization import * # plot histogram plot_histogram(reset_sim_counts) qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) q0, q1 = qr b0, b1 = cr qc.h(q0) qc.measure(q0, b0) ## Write your code below this line ## with qc.if_test((b0, 0)) as else_: qc.x(1) with else_: qc.h(1) ## Do not change the code below this line ## qc.measure(q1, b1) qc.draw(output="mpl", idle_wires=False) backend_sim = AerSimulator() job_1 = backend_sim.run(qc) result_1 = job_1.result() counts_1 = result_1.get_counts() print(f"Counts: {counts_1}") # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex3b grade_ex3b(qc) controls = QuantumRegister(2, name="control") target = QuantumRegister(1, name="target") mid_measure = ClassicalRegister(2, name="mid") final_measure = ClassicalRegister(1, name="final") base = QuantumCircuit(controls, target, mid_measure, final_measure) def trial( circuit: QuantumCircuit, target: QuantumRegister, controls: QuantumRegister, measures: ClassicalRegister, ): """Probabilistically perform Rx(theta) on the target, where cos(theta) = 3/5.""" ## Write your code below this line, making sure it's indented to where this comment begins from ## c0,c1 = controls (t0,) = target b0, b1 = mid_measure circuit.h(c0) circuit.h(c1) circuit.h(t0) circuit.ccx(c0, c1, t0) circuit.s(t0) circuit.ccx(c0, c1, t0) circuit.h(c0) circuit.h(c1) circuit.h(t0) circuit.measure(c0, b0) circuit.measure(c1, b1) ## Do not change the code below this line ## qc = base.copy_empty_like() trial(qc, target, controls, mid_measure) qc.draw("mpl", cregbundle=False) # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex3c grade_ex3c(qc) def reset_controls( circuit: QuantumCircuit, controls: QuantumRegister, measures: ClassicalRegister ): """Reset the control qubits if they are in |1>.""" ## Write your code below this line, making sure it's indented to where this comment begins from ## c0, c1 = controls r0, r1 = measures # circuit.h(c0) # circuit.h(c1) # circuit.measure(c0, r0) # circuit.measure(c1, r1) with circuit.if_test((r0, 1)): circuit.x(c0) with circuit.if_test((r1, 1)): circuit.x(c1) ## Do not change the code below this line ## qc = base.copy_empty_like() trial(qc, target, controls, mid_measure) reset_controls(qc, controls, mid_measure) qc.measure(controls, mid_measure) qc.draw("mpl", cregbundle=False) # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex3d grade_ex3d(qc) # Set the maximum number of trials max_trials = 2 # Create a clean circuit with the same structure (bits, registers, etc) as the initial base we set up. circuit = base.copy_empty_like() # The first trial does not need to reset its inputs, since the controls are guaranteed to start in the |0> state. trial(circuit, target, controls, mid_measure) # Manually add the rest of the trials. In the future, we will be able to use a dynamic `while` loop to do this, but for now, # we statically add each loop iteration with a manual condition check on each one. # This involves more classical synchronizations than the while loop, but will suffice for now. for _ in range(max_trials - 1): reset_controls(circuit, controls, mid_measure) with circuit.if_test((mid_measure, 0b00)) as else_: # This is the success path, but Qiskit can't directly # represent a negative condition yet, so we have an # empty `true` block in order to use the `else` branch. pass with else_: ## Write your code below this line, making sure it's indented to where this comment begins from ## # (t0,) = target circuit.x(2) trial(circuit, target, controls, mid_measure) ## Do not change the code below this line ## # We need to measure the control qubits again to ensure we get their final results; this is a hardware limitation. circuit.measure(controls, mid_measure) # Finally, let's measure our target, to check that we're getting the rotation we desired. circuit.measure(target, final_measure) circuit.draw("mpl", cregbundle=False) # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex3e grade_ex3e(circuit) sim = AerSimulator() job = sim.run(circuit, shots=1000) result = job.result() counts = result.get_counts() plot_histogram(counts)
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/community.qiskit.org
qiskit-community
%matplotlib inline # useful additional packages #import math tools import numpy as np # We import the tools to handle general Graphs import networkx as nx # We import plotting tools import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter # importing Qiskit from qiskit import Aer, IBMQ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram # Generating the butterfly graph with 5 nodes n = 5 V = np.arange(0,n,1) E =[(0,1,1.0),(0,2,1.0),(1,2,1.0),(3,2,1.0),(3,4,1.0),(4,2,1.0)] G = nx.Graph() G.add_nodes_from(V) G.add_weighted_edges_from(E) # Generate plot of the Graph colors = ['r' for node in G.nodes()] default_axes = plt.axes(frameon=True) pos = nx.spring_layout(G) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=1, ax=default_axes, pos=pos) # Evaluate the function step_size = 0.1; a_gamma = np.arange(0, np.pi, step_size) a_beta = np.arange(0, np.pi, step_size) a_gamma, a_beta = np.meshgrid(a_gamma,a_beta) F1 = 3-(np.sin(2*a_beta)**2*np.sin(2*a_gamma)**2-0.5*np.sin(4*a_beta)*np.sin(4*a_gamma))*(1+np.cos(4*a_gamma)**2) # Grid search for the minimizing variables result = np.where(F1 == np.amax(F1)) a = list(zip(result[0],result[1]))[0] gamma = a[0]*step_size; beta = a[1]*step_size; # Plot the expetation value F1 fig = plt.figure() ax = fig.gca(projection='3d') surf = ax.plot_surface(a_gamma, a_beta, F1, cmap=cm.coolwarm, linewidth=0, antialiased=True) ax.set_zlim(1,4) ax.zaxis.set_major_locator(LinearLocator(3)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) plt.show() #The smallest paramters and the expectation can be extracted print('\n --- OPTIMAL PARAMETERS --- \n') print('The maximal expectation value is: M1 = %.03f' % np.amax(F1)) print('This is attained for gamma = %.03f and beta = %.03f' % (gamma,beta)) # preapre the quantum and classical resisters QAOA = QuantumCircuit(len(V), len(V)) # apply the layer of Hadamard gates to all qubits QAOA.h(range(len(V))) QAOA.barrier() # apply the Ising type gates with angle gamma along the edges in E for edge in E: k = edge[0] l = edge[1] QAOA.cu1(-2*gamma, k, l) QAOA.u1(gamma, k) QAOA.u1(gamma, l) # then apply the single qubit X - rotations with angle beta to all qubits QAOA.barrier() QAOA.rx(2*beta, range(len(V))) # Finally measure the result in the computational basis QAOA.barrier() QAOA.measure(range(len(V)),range(len(V))) ### draw the circuit for comparison QAOA.draw(output='mpl') # Compute the value of the cost function def cost_function_C(x,G): E = G.edges() if( len(x) != len(G.nodes())): return np.nan C = 0; for index in E: e1 = index[0] e2 = index[1] w = G[e1][e2]['weight'] C = C + w*x[e1]*(1-x[e2]) + w*x[e2]*(1-x[e1]) return C # run on local simulator backend = Aer.get_backend("qasm_simulator") shots = 10000 simulate = execute(QAOA, backend=backend, shots=shots) QAOA_results = simulate.result() plot_histogram(QAOA_results.get_counts(),figsize = (8,6),bar_labels = False) # Evaluate the data from the simulator counts = QAOA_results.get_counts() avr_C = 0 max_C = [0,0] hist = {} for k in range(len(G.edges())+1): hist[str(k)] = hist.get(str(k),0) for sample in list(counts.keys()): # use sampled bit string x to compute C(x) x = [int(num) for num in list(sample)] tmp_eng = cost_function_C(x,G) # compute the expectation value and energy distribution avr_C = avr_C + counts[sample]*tmp_eng hist[str(round(tmp_eng))] = hist.get(str(round(tmp_eng)),0) + counts[sample] # save best bit string if( max_C[1] < tmp_eng): max_C[0] = sample max_C[1] = tmp_eng M1_sampled = avr_C/shots print('\n --- SIMULATION RESULTS ---\n') print('The sampled mean value is M1_sampled = %.02f while the true value is M1 = %.02f \n' % (M1_sampled,np.amax(F1))) print('The approximate solution is x* = %s with C(x*) = %d \n' % (max_C[0],max_C[1])) print('The cost function is distributed as: \n') plot_histogram(hist,figsize = (8,6),bar_labels = False) # Use the IBMQ essex device provider = IBMQ.load_account() backend = provider.get_backend('ibmq_essex') shots = 2048 job_exp = execute(QAOA, backend=backend, shots=shots) job_monitor(job_exp) exp_results = job_exp.result() plot_histogram(exp_results.get_counts(),figsize = (10,8),bar_labels = False) # Evaluate the data from the experiment counts = exp_results.get_counts() avr_C = 0 max_C = [0,0] hist = {} for k in range(len(G.edges())+1): hist[str(k)] = hist.get(str(k),0) for sample in list(counts.keys()): # use sampled bit string x to compute C(x) x = [int(num) for num in list(sample)] tmp_eng = cost_function_C(x,G) # compute the expectation value and energy distribution avr_C = avr_C + counts[sample]*tmp_eng hist[str(round(tmp_eng))] = hist.get(str(round(tmp_eng)),0) + counts[sample] # save best bit string if( max_C[1] < tmp_eng): max_C[0] = sample max_C[1] = tmp_eng M1_sampled = avr_C/shots print('\n --- EXPERIMENTAL RESULTS ---\n') print('The sampled mean value is M1_sampled = %.02f while the true value is M1 = %.02f \n' % (M1_sampled,np.amax(F1))) print('The approximate solution is x* = %s with C(x*) = %d \n' % (max_C[0],max_C[1])) print('The cost function is distributed as: \n') plot_histogram(hist,figsize = (8,6),bar_labels = False) import qiskit qiskit.__qiskit_version__
https://github.com/Dpbm/scientific-research-1-quantum-oracles
Dpbm
%matplotlib inline from qiskit import QuantumCircuit, QuantumRegister, transpile, ClassicalRegister from qiskit.quantum_info import Statevector from qiskit.visualization import array_to_latex, plot_histogram, plot_bloch_multivector from qiskit.circuit.library import CHGate from qiskit_aer import AerSimulator from functools import partial import numpy as np from utils import get_image_path show_unitary = partial(array_to_latex, max_size=100000) show_state = lambda qc: Statevector(qc).draw('latex') def get_unitary(qc, sim=AerSimulator()): qc_copy = qc.copy() qc_copy.save_unitary() unitary = sim.run(transpile(qc_copy, sim), shots=1000).result().get_unitary() return unitary def measure(qc, sim=AerSimulator(), qubits=None): qc_copy = qc.copy() if(not qubits): qc_copy.measure_all() else: qc_copy.measure(qubits, list(range(len(qubits)))) result = sim.run(transpile(qc_copy, sim), shots=1000).result().get_counts() return result mem = QuantumCircuit(2, name="QROM") mem.cz(0,1) display(mem.draw('mpl')) show_unitary(get_unitary(mem)) qc = QuantumCircuit(2) qc.x(range(2)) qc.append(mem, [0,1]) qc.x(range(2)) display(qc.draw('mpl')) display(show_unitary(get_unitary(qc))) show_state(qc) mem = QuantumCircuit(2, name="QROM") mem.cp(np.pi/3,0,1) display(mem.draw('mpl')) show_unitary(get_unitary(mem)) qc = QuantumCircuit(2) qc.x(range(2)) qc.append(mem, [0,1]) qc.x(range(2)) display(qc.draw('mpl')) display(show_unitary(get_unitary(qc))) show_state(qc) plot_bloch_multivector(qc) qc = QuantumCircuit(3) qc.x(range(2)) qc.h(2) qc.barrier() qc.append(mem, [0,1]) qc.barrier() qc.cx(2,1) qc.x(range(2)) qc.h(2) display(qc.draw('mpl')) display(show_unitary(get_unitary(qc))) display(show_state(qc)) display(plot_histogram(measure(qc))) qc = QuantumCircuit(1) #qc.h(0) qc.p(np.pi/2, 0) #qc.barrier() #qc.cx(1,0) qc.h(0) display(qc.draw('mpl')) display(show_unitary(get_unitary(qc))) display(show_state(qc)) display(plot_histogram(measure(qc))) mem = QuantumCircuit(2, name="QROM") mem.cp(np.pi/3,0,1) mem.x(range(2)) mem.cp(np.pi/7,0,1) mem.x(range(2)) display(mem.draw('mpl')) show_unitary(get_unitary(mem)) qc = QuantumCircuit(2) #qc.x(range(2)) qc.append(mem, [0,1]) #qc.x(range(2)) display(qc.draw('mpl')) display(show_unitary(get_unitary(qc))) show_state(qc) mem = QuantumCircuit(2, name="qrom") mem.ch(0,1) mem.x(0) mem.cry(np.pi/3, 0, 1) mem.x(0) display(mem.draw('mpl', filename=get_image_path("qrom_1.png"))) display(show_unitary(get_unitary(mem))) show_state(mem) addr = QuantumRegister(1, name="addr") out = QuantumRegister(1, name="out") q = QuantumRegister(1,name="q") result = ClassicalRegister(1, "m") qc = QuantumCircuit(addr, out, q, result) qc.x(addr) qc.barrier(addr) qc.append(mem, [addr, out]) qc.cx(out, q) display(qc.draw('mpl')) display(show_unitary(get_unitary(qc))) display(show_state(qc)) display(plot_histogram(measure(qc, qubits=[2]))) addr = QuantumRegister(1, name="addr") out = QuantumRegister(1, name="out") q = QuantumRegister(1,name="q") result = ClassicalRegister(1, "m") qc = QuantumCircuit(addr, out, q) qc.h(addr) qc.barrier(addr) qc.append(mem, [addr, out]) qc.cx(out, q) display(qc.draw('mpl', filename=get_image_path("qrom_1_usage.png"))) display(show_unitary(get_unitary(qc))) display(show_state(qc)) #display(plot_histogram(measure(qc, qubits=[2]))) CCH = CHGate().control(1) addr = QuantumRegister(2, name="addr") data = QuantumRegister(2, name="data") mem = QuantumCircuit(addr, data, name="qrom") mem.x(addr[0]) mem.ccx(addr[0], addr[1], data[0]) mem.x(addr[0]) mem.barrier() mem.append(CCH, [addr[0], addr[1], data[0]]) mem.ccx(addr[0], addr[1], data[1]) display(mem.draw('mpl')) display(show_unitary(get_unitary(mem))) show_state(mem) addr = QuantumRegister(2, name="addr") data = QuantumRegister(2, name="data") q = QuantumRegister(1, name="q") out = ClassicalRegister(1, name="c") qc = QuantumCircuit(addr, data, q, out) qc.x(range(2)) qc.barrier(addr) qc.append(mem, [*addr, *data]) qc.cx(data[1], q[0]) qc.cx(data[0], q[0]) qc.append(mem, [*addr, *data]) qc.barrier(addr) qc.x(range(2)) display(qc.draw('mpl')) #display(show_unitary(get_unitary(qc))) display(show_state(qc)) display(plot_histogram(measure(qc, qubits=[4]))) #memory with teleportation addr = QuantumRegister(1, name="addr") data = QuantumRegister(1, name="data") mem = QuantumCircuit(addr, data, name="qrom") mem.cry(np.pi/5, 0, 1) display(mem.draw('mpl')) display(show_unitary(get_unitary(mem))) show_state(mem) addr = QuantumRegister(1, name="addr") data = QuantumRegister(2, name="data") q = QuantumRegister(1, name="q") out = ClassicalRegister(1, name="c") qc = QuantumCircuit(addr, data, q, out) qc.x(addr) qc.barrier(addr) qc.append(mem, [addr, data[0]]) qc.cx(data[0], q) qc.barrier(addr) qc.append(mem, [addr, data[0]]) qc.x(addr) display(qc.draw('mpl')) #display(show_unitary(get_unitary(qc))) display(show_state(qc)) display(plot_histogram(measure(qc, qubits=[3]))) addr = QuantumRegister(1, name="addr") data = QuantumRegister(2, name="data") q = QuantumRegister(1, name="q") out = ClassicalRegister(1, name="c") qc = QuantumCircuit(addr, data, q, out) qc.x(addr) qc.barrier(addr) qc.append(mem, [addr, data[0]]) qc.h(data[1]) qc.cx(data[1], q) qc.cx(data[0], data[1]) qc.h(data[0]) qc.cx(data[1], q) qc.cz(data[0], q) display(qc.draw('mpl')) #display(show_unitary(get_unitary(qc))) display(show_state(qc)) display(plot_histogram(measure(qc, qubits=[3]))) display(plot_histogram(measure(qc, qubits=[1]))) (np.cos(np.pi/5/2))**2, (np.sin(np.pi/5/2))**2 qc = QuantumCircuit(3,3) qc.ry(np.pi/5, 0) qc.barrier() qc.h(1) qc.cx(1,2) qc.barrier() qc.cx(0,1) qc.h(0) qc.cx(1,2) qc.cz(0,2) qc.draw('mpl') display(qc.draw('mpl')) #display(show_unitary(get_unitary(qc))) display(show_state(qc)) display(plot_histogram(measure(qc, qubits=[2]))) data = QuantumRegister(1, name="data") teleportation_provider = QuantumRegister(1, name="t") q = QuantumRegister(1, name="q") meas = ClassicalRegister(1, name="out") qram = QuantumCircuit(data, teleportation_provider, q,meas) qram.h(teleportation_provider) qram.cx(teleportation_provider, data) qram.barrier() qram.ry(np.pi/7, q) qram.barrier() qram.cx(q, teleportation_provider) qram.h(q) qram.cx(teleportation_provider, data) qram.cz(q, data) display(qram.draw('mpl')) #display(show_unitary(get_unitary(qram))) display(show_state(qram)) display(plot_histogram(measure(qram, qubits=[0]))) display(plot_histogram(measure(qram, qubits=[2]))) np.cos(np.pi/7/2)**2, np.sin(np.pi/7/2)**2 data = QuantumRegister(2, name="data") teleportation_provider = QuantumRegister(2, name="t") q = QuantumRegister(2, name="q") meas = ClassicalRegister(1, name="out") qram = QuantumCircuit(data, teleportation_provider, q,meas) qram.h(teleportation_provider) qram.cx(teleportation_provider, data) qram.barrier() qram.ry(np.pi/3, q[0]) qram.ry(np.pi/7, q[1]) qram.barrier() qram.cx(q, teleportation_provider) qram.h(q) qram.cx(teleportation_provider, data) qram.cz(q, data) display(qram.draw('mpl', filename=get_image_path('qram.png'))) #display(show_unitary(get_unitary(qram))) display(show_state(qram)) display(plot_histogram(measure(qram, qubits=[0]))) display(plot_histogram(measure(qram, qubits=[4]))) display(plot_histogram(measure(qram, qubits=[1]))) display(plot_histogram(measure(qram, qubits=[5]))) np.cos(np.pi/3/2)**2, np.sin(np.pi/3/2)**2 data = QuantumRegister(2, name="data") teleportation_provider = QuantumRegister(2, name="t") q = QuantumRegister(2, name="q") meas = ClassicalRegister(1, name="out") qram = QuantumCircuit(data, teleportation_provider, q,meas) qram.h(teleportation_provider) qram.cx(teleportation_provider, data) qram.barrier() qram.h(q[0]) qram.h(q[1]) qram.barrier() qram.cx(q, teleportation_provider) qram.h(q) qram.cx(teleportation_provider, data) qram.cz(q, data) qram.barrier(label='second') qram.cz(q, data) qram.cx(teleportation_provider, data) qram.h(q) qram.cx(q, teleportation_provider) qram.barrier() qram.h(q[0]) qram.barrier() qram.cx(q, teleportation_provider) qram.h(q) qram.cx(teleportation_provider, data) qram.cz(q, data) display(qram.draw('mpl')) #display(show_unitary(get_unitary(qram))) display(show_state(qram)) display(plot_histogram(measure(qram, qubits=[0]))) display(plot_histogram(measure(qram, qubits=[4]))) display(plot_histogram(measure(qram, qubits=[1]))) display(plot_histogram(measure(qram, qubits=[5]))) data = QuantumRegister(2, name="data") teleportation_provider = QuantumRegister(1, name="t") q = QuantumRegister(2, name="q") meas = ClassicalRegister(1, name="out") qram = QuantumCircuit(data, teleportation_provider, q,meas) qram.h(teleportation_provider) qram.cx(teleportation_provider, data) qram.barrier() qram.ry(np.pi/3, q[0]) qram.ry(np.pi/7, q[1]) qram.barrier() qram.cx(q, teleportation_provider) qram.h(q) qram.cx(teleportation_provider, data) qram.cz(q, data) display(qram.draw('mpl', filename=get_image_path('qram.png'))) #display(show_unitary(get_unitary(qram))) display(show_state(qram)) display(plot_histogram(measure(qram, qubits=[0]))) display(plot_histogram(measure(qram, qubits=[4]))) display(plot_histogram(measure(qram, qubits=[1]))) display(plot_histogram(measure(qram, qubits=[5])))
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. """Tests basic functionality of the transpile function""" import copy import io import math import os import sys import unittest from logging import StreamHandler, getLogger from test import combine # pylint: disable=wrong-import-order from unittest.mock import patch import numpy as np import rustworkx as rx from ddt import data, ddt, unpack from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, pulse, qasm3, qpy from qiskit.circuit import ( Clbit, ControlFlowOp, ForLoopOp, Gate, IfElseOp, Parameter, Qubit, Reset, SwitchCaseOp, WhileLoopOp, ) from qiskit.circuit.classical import expr from qiskit.circuit.delay import Delay from qiskit.circuit.library import ( CXGate, CZGate, HGate, RXGate, RYGate, RZGate, SXGate, U1Gate, U2Gate, UGate, XGate, ) from qiskit.circuit.measure import Measure from qiskit.compiler import transpile from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGOpNode, DAGOutNode from qiskit.exceptions import QiskitError from qiskit.providers.backend import BackendV2 from qiskit.providers.fake_provider import ( FakeBoeblingen, FakeMelbourne, FakeMumbaiV2, FakeNairobiV2, FakeRueschlikon, FakeSherbrooke, FakeVigo, ) from qiskit.providers.options import Options from qiskit.pulse import InstructionScheduleMap from qiskit.quantum_info import Operator, random_unitary from qiskit.test import QiskitTestCase, slow_test from qiskit.tools import parallel from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout from qiskit.transpiler.passmanager_config import PassManagerConfig from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager, level_0_pass_manager from qiskit.transpiler.target import InstructionProperties, Target class CustomCX(Gate): """Custom CX gate representation.""" def __init__(self): super().__init__("custom_cx", 2, []) def _define(self): self._definition = QuantumCircuit(2) self._definition.cx(0, 1) def connected_qubits(physical: int, coupling_map: CouplingMap) -> set: """Get the physical qubits that have a connection to this one in the coupling map.""" for component in coupling_map.connected_components(): if physical in (qubits := set(component.graph.nodes())): return qubits raise ValueError(f"physical qubit {physical} is not in the coupling map") @ddt class TestTranspile(QiskitTestCase): """Test transpile function.""" def test_empty_transpilation(self): """Test that transpiling an empty list is a no-op. Regression test of gh-7287.""" self.assertEqual(transpile([]), []) def test_pass_manager_none(self): """Test passing the default (None) pass manager to the transpiler. It should perform the default qiskit flow: unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates and should be equivalent to using tools.compile """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) coupling_map = [[1, 0]] basis_gates = ["u1", "u2", "u3", "cx", "id"] backend = BasicAer.get_backend("qasm_simulator") circuit2 = transpile( circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates, ) circuit3 = transpile( circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates ) self.assertEqual(circuit2, circuit3) def test_transpile_basis_gates_no_backend_no_coupling_map(self): """Verify transpile() works with no coupling_map or backend.""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) basis_gates = ["u1", "u2", "u3", "cx", "id"] circuit2 = transpile(circuit, basis_gates=basis_gates, optimization_level=0) resources_after = circuit2.count_ops() self.assertEqual({"u2": 2, "cx": 4}, resources_after) def test_transpile_non_adjacent_layout(self): """Transpile pipeline can handle manual layout on non-adjacent qubits. circuit: .. parsed-literal:: ┌───┐ qr_0: ┤ H ├──■──────────── -> 1 └───┘┌─┴─┐ qr_1: ─────┤ X ├──■─────── -> 2 └───┘┌─┴─┐ qr_2: ──────────┤ X ├──■── -> 3 └───┘┌─┴─┐ qr_3: ───────────────┤ X ├ -> 5 └───┘ device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map basis_gates = FakeMelbourne().configuration().basis_gates initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] new_circuit = transpile( circuit, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, ) qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map) def test_transpile_qft_grid(self): """Transpile pipeline can handle 8-qubit QFT on 14-qubit grid.""" qr = QuantumRegister(8) circuit = QuantumCircuit(qr) for i, _ in enumerate(qr): for j in range(i): circuit.cp(math.pi / float(2 ** (i - j)), qr[i], qr[j]) circuit.h(qr[i]) coupling_map = FakeMelbourne().configuration().coupling_map basis_gates = FakeMelbourne().configuration().basis_gates new_circuit = transpile(circuit, basis_gates=basis_gates, coupling_map=coupling_map) qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map) def test_already_mapped_1(self): """Circuit not remapped if matches topology. See: https://github.com/Qiskit/qiskit-terra/issues/342 """ backend = FakeRueschlikon() coupling_map = backend.configuration().coupling_map basis_gates = backend.configuration().basis_gates qr = QuantumRegister(16, "qr") cr = ClassicalRegister(16, "cr") qc = QuantumCircuit(qr, cr) qc.cx(qr[3], qr[14]) qc.cx(qr[5], qr[4]) qc.h(qr[9]) qc.cx(qr[9], qr[8]) qc.x(qr[11]) qc.cx(qr[3], qr[4]) qc.cx(qr[12], qr[11]) qc.cx(qr[13], qr[4]) qc.measure(qr, cr) new_qc = transpile( qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=Layout.generate_trivial_layout(qr), ) qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)} cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"] cx_qubits_physical = [ [qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits ] self.assertEqual( sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]] ) def test_already_mapped_via_layout(self): """Test that a manual layout that satisfies a coupling map does not get altered. See: https://github.com/Qiskit/qiskit-terra/issues/2036 circuit: .. parsed-literal:: ┌───┐ ┌───┐ ░ ┌─┐ qn_0: ┤ H ├──■────────────■──┤ H ├─░─┤M├─── -> 9 └───┘ │ │ └───┘ ░ └╥┘ qn_1: ───────┼────────────┼────────░──╫──── -> 6 │ │ ░ ║ qn_2: ───────┼────────────┼────────░──╫──── -> 5 │ │ ░ ║ qn_3: ───────┼────────────┼────────░──╫──── -> 0 │ │ ░ ║ qn_4: ───────┼────────────┼────────░──╫──── -> 1 ┌───┐┌─┴─┐┌──────┐┌─┴─┐┌───┐ ░ ║ ┌─┐ qn_5: ┤ H ├┤ X ├┤ P(2) ├┤ X ├┤ H ├─░──╫─┤M├ -> 4 └───┘└───┘└──────┘└───┘└───┘ ░ ║ └╥┘ cn: 2/════════════════════════════════╩══╩═ 0 1 device: 0 -- 1 -- 2 -- 3 -- 4 | | 5 -- 6 -- 7 -- 8 -- 9 | | 10 - 11 - 12 - 13 - 14 | | 15 - 16 - 17 - 18 - 19 """ basis_gates = ["u1", "u2", "u3", "cx", "id"] coupling_map = [ [0, 1], [0, 5], [1, 0], [1, 2], [2, 1], [2, 3], [3, 2], [3, 4], [4, 3], [4, 9], [5, 0], [5, 6], [5, 10], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12], [8, 7], [8, 9], [9, 4], [9, 8], [9, 14], [10, 5], [10, 11], [10, 15], [11, 10], [11, 12], [12, 7], [12, 11], [12, 13], [13, 12], [13, 14], [14, 9], [14, 13], [14, 19], [15, 10], [15, 16], [16, 15], [16, 17], [17, 16], [17, 18], [18, 17], [18, 19], [19, 14], [19, 18], ] q = QuantumRegister(6, name="qn") c = ClassicalRegister(2, name="cn") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[5]) qc.cx(q[0], q[5]) qc.p(2, q[5]) qc.cx(q[0], q[5]) qc.h(q[0]) qc.h(q[5]) qc.barrier(q) qc.measure(q[0], c[0]) qc.measure(q[5], c[1]) initial_layout = [ q[3], q[4], None, None, q[5], q[2], q[1], None, None, q[0], None, None, None, None, None, None, None, None, None, None, ] new_qc = transpile( qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=initial_layout ) qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)} cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"] cx_qubits_physical = [ [qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits ] self.assertEqual(sorted(cx_qubits_physical), [[9, 4], [9, 4]]) def test_transpile_bell(self): """Test Transpile Bell. If all correct some should exists. """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuits = transpile(qc, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpile_one(self): """Test transpile a single circuit. Check that the top-level `transpile` function returns a single circuit.""" backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuit = transpile(qc, backend) self.assertIsInstance(circuit, QuantumCircuit) def test_transpile_two(self): """Test transpile two circuits. Check that the transpiler returns a list of two circuits. """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qubit_reg2 = QuantumRegister(2) clbit_reg2 = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = QuantumCircuit(qubit_reg, qubit_reg2, clbit_reg, clbit_reg2, name="extra") qc_extra.measure(qubit_reg, clbit_reg) circuits = transpile([qc, qc_extra], backend) self.assertIsInstance(circuits, list) self.assertEqual(len(circuits), 2) for circuit in circuits: self.assertIsInstance(circuit, QuantumCircuit) def test_transpile_singleton(self): """Test transpile a single-element list with a circuit. Check that `transpile` returns a single-element list. See https://github.com/Qiskit/qiskit-terra/issues/5260 """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuits = transpile([qc], backend) self.assertIsInstance(circuits, list) self.assertEqual(len(circuits), 1) self.assertIsInstance(circuits[0], QuantumCircuit) def test_mapping_correction(self): """Test mapping works in previous failed case.""" backend = FakeRueschlikon() qr = QuantumRegister(name="qr", size=11) cr = ClassicalRegister(name="qc", size=11) circuit = QuantumCircuit(qr, cr) circuit.u(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3]) circuit.u(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5]) circuit.cx(qr[5], qr[3]) circuit.p(0.856768317675967, qr[3]) circuit.u(-3.3911273825190915, 0.0, 0.0, qr[5]) circuit.cx(qr[3], qr[5]) circuit.u(2.159209321625547, 0.0, 0.0, qr[5]) circuit.cx(qr[5], qr[3]) circuit.u(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3]) circuit.u(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5]) circuit.u(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7]) circuit.u(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8]) circuit.cx(qr[8], qr[7]) circuit.p(2.2196187596178616, qr[7]) circuit.u(-3.152367609631023, 0.0, 0.0, qr[8]) circuit.cx(qr[7], qr[8]) circuit.u(1.2646005789809263, 0.0, 0.0, qr[8]) circuit.cx(qr[8], qr[7]) circuit.u(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7]) circuit.u(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8]) circuit.u(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1]) circuit.u(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4]) circuit.cx(qr[4], qr[1]) circuit.p(2.1899329069137394, qr[1]) circuit.u(-1.8371715243173294, 0.0, 0.0, qr[4]) circuit.cx(qr[1], qr[4]) circuit.u(0.4717053496327104, 0.0, 0.0, qr[4]) circuit.cx(qr[4], qr[1]) circuit.u(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1]) circuit.u(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4]) circuit.u(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10]) circuit.u(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6]) circuit.cx(qr[6], qr[10]) circuit.p(1.067395863586385, qr[10]) circuit.u(-0.7044917541291232, 0.0, 0.0, qr[6]) circuit.cx(qr[10], qr[6]) circuit.u(2.1830003849921527, 0.0, 0.0, qr[6]) circuit.cx(qr[6], qr[10]) circuit.u(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10]) circuit.u(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6]) circuit.u(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9]) circuit.u(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0]) circuit.cx(qr[0], qr[9]) circuit.p(2.6209599970201007, qr[9]) circuit.u(0.04680566321901303, 0.0, 0.0, qr[0]) circuit.cx(qr[9], qr[0]) circuit.u(1.7728411151289603, 0.0, 0.0, qr[0]) circuit.cx(qr[0], qr[9]) circuit.u(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9]) circuit.u(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) circuits = transpile(circuit, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpiler_layout_from_intlist(self): """A list of ints gives layout to correctly map circuit. virtual physical q1_0 - 4 ---[H]--- q2_0 - 5 q2_1 - 6 ---[H]--- q3_0 - 8 q3_1 - 9 q3_2 - 10 ---[H]--- """ qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") qr3 = QuantumRegister(3, "qr3") qc = QuantumCircuit(qr1, qr2, qr3) qc.h(qr1[0]) qc.h(qr2[1]) qc.h(qr3[2]) layout = [4, 5, 6, 8, 9, 10] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] new_circ = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout ) qubit_indices = {bit: idx for idx, bit in enumerate(new_circ.qubits)} mapped_qubits = [] for instruction in new_circ.data: mapped_qubits.append(qubit_indices[instruction.qubits[0]]) self.assertEqual(mapped_qubits, [4, 6, 10]) def test_mapping_multi_qreg(self): """Test mapping works for multiple qregs.""" backend = FakeRueschlikon() qr = QuantumRegister(3, name="qr") qr2 = QuantumRegister(1, name="qr2") qr3 = QuantumRegister(4, name="qr3") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, qr2, qr3, cr) qc.h(qr[0]) qc.cx(qr[0], qr2[0]) qc.cx(qr[1], qr3[2]) qc.measure(qr, cr) circuits = transpile(qc, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpile_circuits_diff_registers(self): """Transpile list of circuits with different qreg names.""" backend = FakeRueschlikon() circuits = [] for _ in range(2): qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr, cr) circuits.append(circuit) circuits = transpile(circuits, backend) self.assertIsInstance(circuits[0], QuantumCircuit) def test_wrong_initial_layout(self): """Test transpile with a bad initial layout.""" backend = FakeMelbourne() qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) bad_initial_layout = [ QuantumRegister(3, "q")[0], QuantumRegister(3, "q")[1], QuantumRegister(3, "q")[2], ] with self.assertRaises(TranspilerError): transpile(qc, backend, initial_layout=bad_initial_layout) def test_parameterized_circuit_for_simulator(self): """Verify that a parameterized circuit can be transpiled for a simulator backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator")) expected_qc = QuantumCircuit(qr) expected_qc.append(RZGate(theta), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameterized_circuit_for_device(self): """Verify that a parameterized circuit can be transpiled for a device backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) transpiled_qc = transpile( qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr) ) qr = QuantumRegister(14, "q") expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0) expected_qc.append(U1Gate(theta), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameter_expression_circuit_for_simulator(self): """Verify that a circuit including expressions of parameters can be transpiled for a simulator backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") square = theta * theta qc.rz(square, qr[0]) transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator")) expected_qc = QuantumCircuit(qr) expected_qc.append(RZGate(square), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameter_expression_circuit_for_device(self): """Verify that a circuit including expressions of parameters can be transpiled for a device backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") square = theta * theta qc.rz(square, qr[0]) transpiled_qc = transpile( qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr) ) qr = QuantumRegister(14, "q") expected_qc = QuantumCircuit(qr, global_phase=-1 * square / 2.0) expected_qc.append(U1Gate(square), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_final_measurement_barrier_for_devices(self): """Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm")) layout = Layout.generate_trivial_layout(*circ.qregs) orig_pass = BarrierBeforeFinalMeasurements() with patch.object(BarrierBeforeFinalMeasurements, "run", wraps=orig_pass.run) as mock_pass: transpile( circ, coupling_map=FakeRueschlikon().configuration().coupling_map, initial_layout=layout, ) self.assertTrue(mock_pass.called) def test_do_not_run_gatedirection_with_symmetric_cm(self): """When the coupling map is symmetric, do not run GateDirection.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm")) layout = Layout.generate_trivial_layout(*circ.qregs) coupling_map = [] for node1, node2 in FakeRueschlikon().configuration().coupling_map: coupling_map.append([node1, node2]) coupling_map.append([node2, node1]) orig_pass = GateDirection(CouplingMap(coupling_map)) with patch.object(GateDirection, "run", wraps=orig_pass.run) as mock_pass: transpile(circ, coupling_map=coupling_map, initial_layout=layout) self.assertFalse(mock_pass.called) def test_optimize_to_nothing(self): """Optimize gates up to fixed point in the default pipeline See https://github.com/Qiskit/qiskit-terra/issues/2035 """ # ┌───┐ ┌───┐┌───┐┌───┐ ┌───┐ # q0_0: ┤ H ├──■──┤ X ├┤ Y ├┤ Z ├──■──┤ H ├──■────■── # └───┘┌─┴─┐└───┘└───┘└───┘┌─┴─┐└───┘┌─┴─┐┌─┴─┐ # q0_1: ─────┤ X ├───────────────┤ X ├─────┤ X ├┤ X ├ # └───┘ └───┘ └───┘└───┘ qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.x(qr[0]) circ.y(qr[0]) circ.z(qr[0]) circ.cx(qr[0], qr[1]) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.cx(qr[0], qr[1]) after = transpile(circ, coupling_map=[[0, 1], [1, 0]], basis_gates=["u3", "u2", "u1", "cx"]) expected = QuantumCircuit(QuantumRegister(2, "q"), global_phase=-np.pi / 2) msg = f"after:\n{after}\nexpected:\n{expected}" self.assertEqual(after, expected, msg=msg) def test_pass_manager_empty(self): """Test passing an empty PassManager() to the transpiler. It should perform no transformations on the circuit. """ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) resources_before = circuit.count_ops() pass_manager = PassManager() out_circuit = pass_manager.run(circuit) resources_after = out_circuit.count_ops() self.assertDictEqual(resources_before, resources_after) def test_move_measurements(self): """Measurements applied AFTER swap mapping.""" backend = FakeRueschlikon() cmap = backend.configuration().coupling_map qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "move_measurements.qasm")) lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6] out = transpile(circ, initial_layout=lay, coupling_map=cmap, routing_method="stochastic") out_dag = circuit_to_dag(out) meas_nodes = out_dag.named_nodes("measure") for meas_node in meas_nodes: is_last_measure = all( isinstance(after_measure, DAGOutNode) for after_measure in out_dag.quantum_successors(meas_node) ) self.assertTrue(is_last_measure) @data(0, 1, 2, 3) def test_init_resets_kept_preset_passmanagers(self, optimization_level): """Test initial resets kept at all preset transpilation levels""" num_qubits = 5 qc = QuantumCircuit(num_qubits) qc.reset(range(num_qubits)) num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"] self.assertEqual(num_resets, num_qubits) @data(0, 1, 2, 3) def test_initialize_reset_is_not_removed(self, optimization_level): """The reset in front of initializer should NOT be removed at beginning""" qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]]) qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]]) after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level) self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.") def test_initialize_FakeMelbourne(self): """Test that the zero-state resets are remove in a device not supporting them.""" desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) out = transpile(qc, backend=FakeMelbourne()) out_dag = circuit_to_dag(out) reset_nodes = out_dag.named_nodes("reset") self.assertEqual(len(reset_nodes), 3) def test_non_standard_basis(self): """Test a transpilation with a non-standard basis""" qr1 = QuantumRegister(1, "q1") qr2 = QuantumRegister(2, "q2") qr3 = QuantumRegister(3, "q3") qc = QuantumCircuit(qr1, qr2, qr3) qc.h(qr1[0]) qc.h(qr2[1]) qc.h(qr3[2]) layout = [4, 5, 6, 8, 9, 10] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["h"], initial_layout=layout ) dag_circuit = circuit_to_dag(circuit) resources_after = dag_circuit.count_ops() self.assertEqual({"h": 3}, resources_after) def test_hadamard_to_rot_gates(self): """Test a transpilation from H to Rx, Ry gates""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.h(0) expected = QuantumCircuit(qr, global_phase=np.pi / 2) expected.append(RYGate(theta=np.pi / 2), [0]) expected.append(RXGate(theta=np.pi), [0]) circuit = transpile(qc, basis_gates=["rx", "ry"], optimization_level=0) self.assertEqual(circuit, expected) def test_basis_subset(self): """Test a transpilation with a basis subset of the standard basis""" qr = QuantumRegister(1, "q1") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.x(qr[0]) qc.t(qr[0]) layout = [4] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["u3"], initial_layout=layout ) dag_circuit = circuit_to_dag(circuit) resources_after = dag_circuit.count_ops() self.assertEqual({"u3": 1}, resources_after) def test_check_circuit_width(self): """Verify transpilation of circuit with virtual qubits greater than physical qubits raises error""" cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] qc = QuantumCircuit(15, 15) with self.assertRaises(TranspilerError): transpile(qc, coupling_map=cmap) @data(0, 1, 2, 3) def test_ccx_routing_method_none(self, optimization_level): """CCX without routing method.""" qc = QuantumCircuit(3) qc.cx(0, 1) qc.cx(1, 2) out = transpile( qc, routing_method="none", basis_gates=["u", "cx"], initial_layout=[0, 1, 2], seed_transpiler=0, coupling_map=[[0, 1], [1, 2]], optimization_level=optimization_level, ) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_ccx_routing_method_none_failed(self, optimization_level): """CCX without routing method cannot be routed.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) with self.assertRaises(TranspilerError): transpile( qc, routing_method="none", basis_gates=["u", "cx"], initial_layout=[0, 1, 2], seed_transpiler=0, coupling_map=[[0, 1], [1, 2]], optimization_level=optimization_level, ) @data(0, 1, 2, 3) def test_ms_unrolls_to_cx(self, optimization_level): """Verify a Rx,Ry,Rxx circuit transpile to a U3,CX target.""" qc = QuantumCircuit(2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) out = transpile(qc, basis_gates=["u3", "cx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_ms_can_target_ms(self, optimization_level): """Verify a Rx,Ry,Rxx circuit can transpile to an Rx,Ry,Rxx target.""" qc = QuantumCircuit(2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_cx_can_target_ms(self, optimization_level): """Verify a U3,CX circuit can transpiler to a Rx,Ry,Rxx target.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.rz(math.pi / 4, [0, 1]) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_measure_doesnt_unroll_ms(self, optimization_level): """Verify a measure doesn't cause an Rx,Ry,Rxx circuit to unroll to U3,CX.""" qc = QuantumCircuit(2, 2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) qc.measure([0, 1], [0, 1]) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertEqual(qc, out) @data( ["cx", "u3"], ["cz", "u3"], ["cz", "rx", "rz"], ["rxx", "rx", "ry"], ["iswap", "rx", "rz"], ) def test_block_collection_runs_for_non_cx_bases(self, basis_gates): """Verify block collection is run when a single two qubit gate is in the basis.""" twoq_gate, *_ = basis_gates qc = QuantumCircuit(2) qc.cx(0, 1) qc.cx(1, 0) qc.cx(0, 1) qc.cx(0, 1) out = transpile(qc, basis_gates=basis_gates, optimization_level=3) self.assertLessEqual(out.count_ops()[twoq_gate], 2) @unpack @data( (["u3", "cx"], {"u3": 1, "cx": 1}), (["rx", "rz", "iswap"], {"rx": 6, "rz": 12, "iswap": 2}), (["rx", "ry", "rxx"], {"rx": 6, "ry": 5, "rxx": 1}), ) def test_block_collection_reduces_1q_gate(self, basis_gates, gate_counts): """For synthesis to non-U3 bases, verify we minimize 1q gates.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) out = transpile(qc, basis_gates=basis_gates, optimization_level=3) self.assertTrue(Operator(out).equiv(qc)) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) for basis_gate in basis_gates: self.assertLessEqual(out.count_ops()[basis_gate], gate_counts[basis_gate]) @combine( optimization_level=[0, 1, 2, 3], basis_gates=[ ["u3", "cx"], ["rx", "rz", "iswap"], ["rx", "ry", "rxx"], ], ) def test_translation_method_synthesis(self, optimization_level, basis_gates): """Verify translation_method='synthesis' gets to the basis.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) out = transpile( qc, translation_method="synthesis", basis_gates=basis_gates, optimization_level=optimization_level, ) self.assertTrue(Operator(out).equiv(qc)) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) def test_transpiled_custom_gates_calibration(self): """Test if transpiled calibrations is equal to custom gates circuit calibrations.""" custom_180 = Gate("mycustom", 1, [3.14]) custom_90 = Gate("mycustom", 1, [1.57]) circ = QuantumCircuit(2) circ.append(custom_180, [0]) circ.append(custom_90, [1]) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) with pulse.build() as q1_y90: pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1)) # Add calibration circ.add_calibration(custom_180, [0], q0_x180) circ.add_calibration(custom_90, [1], q1_y90) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, layout_method="trivial", ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) self.assertEqual(list(transpiled_circuit.count_ops().keys()), ["mycustom"]) self.assertEqual(list(transpiled_circuit.count_ops().values()), [2]) def test_transpiled_basis_gates_calibrations(self): """Test if the transpiled calibrations is equal to basis gates circuit calibrations.""" circ = QuantumCircuit(2) circ.h(0) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration("h", [0], q0_x180) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) def test_transpile_calibrated_custom_gate_on_diff_qubit(self): """Test if the custom, non calibrated gate raises QiskitError.""" custom_180 = Gate("mycustom", 1, [3.14]) circ = QuantumCircuit(2) circ.append(custom_180, [0]) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration(custom_180, [1], q0_x180) backend = FakeBoeblingen() with self.assertRaises(QiskitError): transpile(circ, backend=backend, layout_method="trivial") def test_transpile_calibrated_nonbasis_gate_on_diff_qubit(self): """Test if the non-basis gates are transpiled if they are on different qubit that is not calibrated.""" circ = QuantumCircuit(2) circ.h(0) circ.h(1) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration("h", [1], q0_x180) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) self.assertEqual(set(transpiled_circuit.count_ops().keys()), {"u2", "h"}) def test_transpile_subset_of_calibrated_gates(self): """Test transpiling a circuit with both basis gate (not-calibrated) and a calibrated gate on different qubits.""" x_180 = Gate("mycustom", 1, [3.14]) circ = QuantumCircuit(2) circ.h(0) circ.append(x_180, [0]) circ.h(1) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration(x_180, [0], q0_x180) circ.add_calibration("h", [1], q0_x180) # 'h' is calibrated on qubit 1 transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"u2", "mycustom", "h"}) def test_parameterized_calibrations_transpile(self): """Check that gates can be matched to their calibrations before and after parameter assignment.""" tau = Parameter("tau") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [2 * 3.14 * tau]), [0]) def q0_rxt(tau): with pulse.build() as q0_rxt: pulse.play(pulse.library.Gaussian(20, 0.4 * tau, 3.0), pulse.DriveChannel(0)) return q0_rxt circ.add_calibration("rxt", [0], q0_rxt(tau), [2 * 3.14 * tau]) transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"}) circ = circ.assign_parameters({tau: 1}) transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"}) def test_inst_durations_from_calibrations(self): """Test that circuit calibrations can be used instead of explicitly supplying inst_durations. """ qc = QuantumCircuit(2) qc.append(Gate("custom", 1, []), [0]) with pulse.build() as cal: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("custom", [0], cal) out = transpile(qc, scheduling_method="alap") self.assertEqual(out.duration, cal.duration) @data(0, 1, 2, 3) def test_multiqubit_gates_calibrations(self, opt_level): """Test multiqubit gate > 2q with calibrations works Adapted from issue description in https://github.com/Qiskit/qiskit-terra/issues/6572 """ circ = QuantumCircuit(5) custom_gate = Gate("my_custom_gate", 5, []) circ.append(custom_gate, [0, 1, 2, 3, 4]) circ.measure_all() backend = FakeBoeblingen() with pulse.build(backend, name="custom") as my_schedule: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(1) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(2) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(3) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(4) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(1) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(2) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(3) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(4) ) circ.add_calibration("my_custom_gate", [0, 1, 2, 3, 4], my_schedule, []) trans_circ = transpile(circ, backend, optimization_level=opt_level, layout_method="trivial") self.assertEqual({"measure": 5, "my_custom_gate": 1, "barrier": 1}, trans_circ.count_ops()) @data(0, 1, 2, 3) def test_circuit_with_delay(self, optimization_level): """Verify a circuit with delay can transpile to a scheduled circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) out = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)], optimization_level=optimization_level, ) self.assertEqual(out.duration, 1200) def test_delay_converts_to_dt(self): """Test that a delay instruction is converted to units of dt given a backend.""" qc = QuantumCircuit(2) qc.delay(1000, [0], unit="us") backend = FakeRueschlikon() backend.configuration().dt = 0.5e-6 out = transpile([qc, qc], backend) self.assertEqual(out[0].data[0].operation.unit, "dt") self.assertEqual(out[1].data[0].operation.unit, "dt") out = transpile(qc, dt=1e-9) self.assertEqual(out.data[0].operation.unit, "dt") def test_scheduling_backend_v2(self): """Test that scheduling method works with Backendv2.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() backend = FakeMumbaiV2() out = transpile([qc, qc], backend, scheduling_method="alap") self.assertIn("delay", out[0].count_ops()) self.assertIn("delay", out[1].count_ops()) @data(1, 2, 3) def test_no_infinite_loop(self, optimization_level): """Verify circuit cost always descends and optimization does not flip flop indefinitely.""" qc = QuantumCircuit(1) qc.ry(0.2, 0) out = transpile( qc, basis_gates=["id", "p", "sx", "cx"], optimization_level=optimization_level ) # Expect a -pi/2 global phase for the U3 to RZ/SX conversion, and # a -0.5 * theta phase for RZ to P twice, once at theta, and once at 3 pi # for the second and third RZ gates in the U3 decomposition. expected = QuantumCircuit( 1, global_phase=-np.pi / 2 - 0.5 * (-0.2 + np.pi) - 0.5 * 3 * np.pi ) expected.p(-np.pi, 0) expected.sx(0) expected.p(np.pi - 0.2, 0) expected.sx(0) error_message = ( f"\nOutput circuit:\n{out!s}\n{Operator(out).data}\n" f"Expected circuit:\n{expected!s}\n{Operator(expected).data}" ) self.assertEqual(out, expected, error_message) @data(0, 1, 2, 3) def test_transpile_preserves_circuit_metadata(self, optimization_level): """Verify that transpile preserves circuit metadata in the output.""" circuit = QuantumCircuit(2, metadata={"experiment_id": "1234", "execution_number": 4}) circuit.h(0) circuit.cx(0, 1) cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] res = transpile( circuit, basis_gates=["id", "p", "sx", "cx"], coupling_map=cmap, optimization_level=optimization_level, ) self.assertEqual(circuit.metadata, res.metadata) @data(0, 1, 2, 3) def test_transpile_optional_registers(self, optimization_level): """Verify transpile accepts circuits without registers end-to-end.""" qubits = [Qubit() for _ in range(3)] clbits = [Clbit() for _ in range(3)] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.measure(qubits, clbits) out = transpile(qc, FakeBoeblingen(), optimization_level=optimization_level) self.assertEqual(len(out.qubits), FakeBoeblingen().configuration().num_qubits) self.assertEqual(len(out.clbits), len(clbits)) @data(0, 1, 2, 3) def test_translate_ecr_basis(self, optimization_level): """Verify that rewriting in ECR basis is efficient.""" circuit = QuantumCircuit(2) circuit.append(random_unitary(4, seed=1), [0, 1]) circuit.barrier() circuit.cx(0, 1) circuit.barrier() circuit.swap(0, 1) circuit.barrier() circuit.iswap(0, 1) res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=optimization_level) self.assertEqual(res.count_ops()["ecr"], 9) self.assertTrue(Operator(res).equiv(circuit)) def test_optimize_ecr_basis(self): """Test highest optimization level can optimize over ECR.""" circuit = QuantumCircuit(2) circuit.swap(1, 0) circuit.iswap(0, 1) res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3) self.assertEqual(res.count_ops()["ecr"], 1) self.assertTrue(Operator(res).equiv(circuit)) def test_approximation_degree_invalid(self): """Test invalid approximation degree raises.""" circuit = QuantumCircuit(2) circuit.swap(0, 1) with self.assertRaises(QiskitError): transpile(circuit, basis_gates=["u", "cz"], approximation_degree=1.1) def test_approximation_degree(self): """Test more approximation gives lower-cost circuit.""" circuit = QuantumCircuit(2) circuit.swap(0, 1) circuit.h(0) circ_10 = transpile( circuit, basis_gates=["u", "cx"], translation_method="synthesis", approximation_degree=0.1, ) circ_90 = transpile( circuit, basis_gates=["u", "cx"], translation_method="synthesis", approximation_degree=0.9, ) self.assertLess(circ_10.depth(), circ_90.depth()) @data(0, 1, 2, 3) def test_synthesis_translation_method_with_single_qubit_gates(self, optimization_level): """Test that synthesis basis translation works for solely 1q circuit""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) res = transpile( qc, basis_gates=["id", "rz", "x", "sx", "cx"], translation_method="synthesis", optimization_level=optimization_level, ) expected = QuantumCircuit(3, global_phase=3 * np.pi / 4) expected.rz(np.pi / 2, 0) expected.rz(np.pi / 2, 1) expected.rz(np.pi / 2, 2) expected.sx(0) expected.sx(1) expected.sx(2) expected.rz(np.pi / 2, 0) expected.rz(np.pi / 2, 1) expected.rz(np.pi / 2, 2) self.assertEqual(res, expected) @data(0, 1, 2, 3) def test_synthesis_translation_method_with_gates_outside_basis(self, optimization_level): """Test that synthesis translation works for circuits with single gates outside bassis""" qc = QuantumCircuit(2) qc.swap(0, 1) res = transpile( qc, basis_gates=["id", "rz", "x", "sx", "cx"], translation_method="synthesis", optimization_level=optimization_level, ) if optimization_level != 3: self.assertTrue(Operator(qc).equiv(res)) self.assertNotIn("swap", res.count_ops()) else: # Optimization level 3 eliminates the pointless swap self.assertEqual(res, QuantumCircuit(2)) @data(0, 1, 2, 3) def test_target_ideal_gates(self, opt_level): """Test that transpile() with a custom ideal sim target works.""" theta = Parameter("θ") phi = Parameter("ϕ") lam = Parameter("λ") target = Target(num_qubits=2) target.add_instruction(UGate(theta, phi, lam), {(0,): None, (1,): None}) target.add_instruction(CXGate(), {(0, 1): None}) target.add_instruction(Measure(), {(0,): None, (1,): None}) qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) result = transpile(qc, target=target, optimization_level=opt_level) self.assertEqual(Operator.from_circuit(result), Operator.from_circuit(qc)) @data(0, 1, 2, 3) def test_transpile_with_custom_control_flow_target(self, opt_level): """Test transpile() with a target and constrol flow ops.""" target = FakeMumbaiV2().target target.add_instruction(ForLoopOp, name="for_loop") target.add_instruction(WhileLoopOp, name="while_loop") target.add_instruction(IfElseOp, name="if_else") target.add_instruction(SwitchCaseOp, name="switch_case") circuit = QuantumCircuit(6, 1) circuit.h(0) circuit.measure(0, 0) circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.for_loop((1,)): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with else_: circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.switch(circuit.cregs[0]) as case_: with case_(0): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with case_(1): circuit.cx(1, 2) circuit.cz(1, 3) circuit.append(CustomCX(), [2, 3], []) transpiled = transpile( circuit, optimization_level=opt_level, target=target, seed_transpiler=12434 ) # Tests of the complete validity of a circuit are mostly done at the indiviual pass level; # here we're just checking that various passes do appear to have run. self.assertIsInstance(transpiled, QuantumCircuit) # Assert layout ran. self.assertIsNot(getattr(transpiled, "_layout", None), None) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) # Assert unrolling ran. self.assertNotIsInstance(instruction.operation, CustomCX) # Assert translation ran. self.assertNotIsInstance(instruction.operation, CZGate) # Assert routing ran. _visit_block( transpiled, qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)}, ) @data(1, 2, 3) def test_transpile_identity_circuit_no_target(self, opt_level): """Test circuit equivalent to identity is optimized away for all optimization levels >0. Reproduce taken from https://github.com/Qiskit/qiskit-terra/issues/9217 """ qr1 = QuantumRegister(3, "state") qr2 = QuantumRegister(2, "ancilla") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr1, qr2, cr) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[0], qr1[1]) qc.h(qr1[0]) empty_qc = QuantumCircuit(qr1, qr2, cr) result = transpile(qc, optimization_level=opt_level) self.assertEqual(empty_qc, result) @data(0, 1, 2, 3) def test_initial_layout_with_loose_qubits(self, opt_level): """Regression test of gh-10125.""" qc = QuantumCircuit([Qubit(), Qubit()]) qc.cx(0, 1) transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level) self.assertIsNotNone(transpiled.layout) self.assertEqual( transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]}) ) @data(0, 1, 2, 3) def test_initial_layout_with_overlapping_qubits(self, opt_level): """Regression test of gh-10125.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(bits=qr1[:]) qc = QuantumCircuit(qr1, qr2) qc.cx(0, 1) transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level) self.assertIsNotNone(transpiled.layout) self.assertEqual( transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]}) ) @combine(opt_level=[0, 1, 2, 3], basis=[["rz", "x"], ["rx", "z"], ["rz", "y"], ["ry", "x"]]) def test_paulis_to_constrained_1q_basis(self, opt_level, basis): """Test that Pauli-gate circuits can be transpiled to constrained 1q bases that do not contain any root-Pauli gates.""" qc = QuantumCircuit(1) qc.x(0) qc.barrier() qc.y(0) qc.barrier() qc.z(0) transpiled = transpile(qc, basis_gates=basis, optimization_level=opt_level) self.assertGreaterEqual(set(basis) | {"barrier"}, transpiled.count_ops().keys()) self.assertEqual(Operator(qc), Operator(transpiled)) @ddt class TestPostTranspileIntegration(QiskitTestCase): """Test that the output of `transpile` is usable in various other integration contexts.""" def _regular_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) base.cz(1, 4) base.cx(1, 5) base.measure(1, 1) base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]).c_if(base.cregs[0], 3) base.ry(a, 4) base.measure(4, 2) return base def _control_flow_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) with base.if_test((base.cregs[0], 1)) as else_: base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) with else_: base.cz(1, 4) with base.for_loop((1, 2)): base.cx(1, 5) base.measure(2, 2) with base.while_loop((2, False)): base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]) base.ry(a, 4) base.measure(4, 2) with base.switch(base.cregs[0]) as case_: with case_(0, 1): base.cz(3, 5) with case_(case_.DEFAULT): base.cz(1, 4) base.append(CustomCX(), [2, 4]) base.append(CustomCX(), [3, 4]) return base def _control_flow_expr_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) with base.if_test(expr.equal(base.cregs[0], 1)) as else_: base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) with else_: base.cz(1, 4) with base.for_loop((1, 2)): base.cx(1, 5) base.measure(2, 2) with base.while_loop(expr.logic_not(bits[2])): base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]) base.ry(a, 4) base.measure(4, 2) with base.switch(expr.bit_and(base.cregs[0], 2)) as case_: with case_(0, 1): base.cz(3, 5) with case_(case_.DEFAULT): base.cz(1, 4) base.append(CustomCX(), [2, 4]) base.append(CustomCX(), [3, 4]) return base @data(0, 1, 2, 3) def test_qpy_roundtrip(self, optimization_level): """Test that the output of a transpiled circuit can be round-tripped through QPY.""" transpiled = transpile( self._regular_circuit(), backend=FakeMelbourne(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_backendv2(self, optimization_level): """Test that the output of a transpiled circuit can be round-tripped through QPY.""" transpiled = transpile( self._regular_circuit(), backend=FakeMumbaiV2(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be round-tripped through QPY.""" if optimization_level == 3 and sys.platform == "win32": self.skipTest( "This test case triggers a bug in the eigensolver routine on windows. " "See #10345 for more details." ) backend = FakeMelbourne() transpiled = transpile( self._control_flow_circuit(), backend=backend, basis_gates=backend.configuration().basis_gates + ["if_else", "for_loop", "while_loop", "switch_case"], optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_backendv2(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be round-tripped through QPY.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_expr(self, optimization_level): """Test that the output of a transpiled circuit with control flow including `Expr` nodes can be round-tripped through QPY.""" if optimization_level == 3 and sys.platform == "win32": self.skipTest( "This test case triggers a bug in the eigensolver routine on windows. " "See #10345 for more details." ) backend = FakeMelbourne() transpiled = transpile( self._control_flow_expr_circuit(), backend=backend, basis_gates=backend.configuration().basis_gates + ["if_else", "for_loop", "while_loop", "switch_case"], optimization_level=optimization_level, seed_transpiler=2023_07_26, ) buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_expr_backendv2(self, optimization_level): """Test that the output of a transpiled circuit with control flow including `Expr` nodes can be round-tripped through QPY.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2023_07_26, ) buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qasm3_output(self, optimization_level): """Test that the output of a transpiled circuit can be dumped into OpenQASM 3.""" transpiled = transpile( self._regular_circuit(), backend=FakeMelbourne(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance(qasm3.dumps(transpiled).strip(), str) @data(0, 1, 2, 3) def test_qasm3_output_control_flow(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be dumped into OpenQASM 3.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance( qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(), str, ) @data(0, 1, 2, 3) def test_qasm3_output_control_flow_expr(self, optimization_level): """Test that the output of a transpiled circuit with control flow and `Expr` nodes can be dumped into OpenQASM 3.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2023_07_26, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance( qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(), str, ) @data(0, 1, 2, 3) def test_transpile_target_no_measurement_error(self, opt_level): """Test that transpile with a target which contains ideal measurement works Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8969 """ target = Target() target.add_instruction(Measure(), {(0,): None}) qc = QuantumCircuit(1, 1) qc.measure(0, 0) res = transpile(qc, target=target, optimization_level=opt_level) self.assertEqual(qc, res) def test_transpile_final_layout_updated_with_post_layout(self): """Test that the final layout is correctly set when vf2postlayout runs. Reproduce from #10457 """ def _get_index_layout(transpiled_circuit: QuantumCircuit, num_source_qubits: int): """Return the index layout of a transpiled circuit""" layout = transpiled_circuit.layout if layout is None: return list(range(num_source_qubits)) pos_to_virt = {v: k for k, v in layout.input_qubit_mapping.items()} qubit_indices = [] for index in range(num_source_qubits): qubit_idx = layout.initial_layout[pos_to_virt[index]] if layout.final_layout is not None: qubit_idx = layout.final_layout[transpiled_circuit.qubits[qubit_idx]] qubit_indices.append(qubit_idx) return qubit_indices vf2_post_layout_called = False def callback(**kwargs): nonlocal vf2_post_layout_called if isinstance(kwargs["pass_"], VF2PostLayout): vf2_post_layout_called = True self.assertIsNotNone(kwargs["property_set"]["post_layout"]) backend = FakeVigo() qubits = 3 qc = QuantumCircuit(qubits) for i in range(5): qc.cx(i % qubits, int(i + qubits / 2) % qubits) tqc = transpile(qc, backend=backend, seed_transpiler=4242, callback=callback) self.assertTrue(vf2_post_layout_called) self.assertEqual([3, 2, 1], _get_index_layout(tqc, qubits)) class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestLogTranspile(QiskitTestCase): """Testing the log_transpile option.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) self.circuit = QuantumCircuit(QuantumRegister(1)) def assertTranspileLog(self, log_msg): """Runs the transpiler and check for logs containing specified message""" transpile(self.circuit) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() transpile_log_lines = [x for x in output_lines if log_msg in x] self.assertTrue(len(transpile_log_lines) > 0) def test_transpile_log_time(self): """Check Total Transpile Time is logged""" self.assertTranspileLog("Total Transpile Time") class TestTranspileCustomPM(QiskitTestCase): """Test transpile function with custom pass manager""" def test_custom_multiple_circuits(self): """Test transpiling with custom pass manager and multiple circuits. This tests created a deadlock, so it needs to be monitored for timeout. See: https://github.com/Qiskit/qiskit-terra/issues/3925 """ qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) pm_conf = PassManagerConfig( initial_layout=None, basis_gates=["u1", "u2", "u3", "cx"], coupling_map=CouplingMap([[0, 1]]), backend_properties=None, seed_transpiler=1, ) passmanager = level_0_pass_manager(pm_conf) transpiled = passmanager.run([qc, qc]) expected = QuantumCircuit(QuantumRegister(2, "q")) expected.append(U2Gate(0, 3.141592653589793), [0]) expected.cx(0, 1) self.assertEqual(len(transpiled), 2) self.assertEqual(transpiled[0], expected) self.assertEqual(transpiled[1], expected) @ddt class TestTranspileParallel(QiskitTestCase): """Test transpile() in parallel.""" def setUp(self): super().setUp() # Force parallel execution to True to test multiprocessing for this class original_val = parallel.PARALLEL_DEFAULT def restore_default(): parallel.PARALLEL_DEFAULT = original_val self.addCleanup(restore_default) parallel.PARALLEL_DEFAULT = True @data(0, 1, 2, 3) def test_parallel_multiprocessing(self, opt_level): """Test parallel dispatch works with multiprocessing.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() backend = FakeMumbaiV2() pm = generate_preset_pass_manager(opt_level, backend) res = pm.run([qc, qc]) for circ in res: self.assertIsInstance(circ, QuantumCircuit) @data(0, 1, 2, 3) def test_parallel_with_target(self, opt_level): """Test that parallel dispatch works with a manual target.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() target = FakeMumbaiV2().target res = transpile([qc] * 3, target=target, optimization_level=opt_level) self.assertIsInstance(res, list) for circ in res: self.assertIsInstance(circ, QuantumCircuit) @data(0, 1, 2, 3) def test_parallel_dispatch(self, opt_level): """Test that transpile in parallel works for all optimization levels.""" backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr, cr) qlist = [qc for k in range(15)] tqc = transpile( qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242 ) result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() counts = result.get_counts() for count in counts: self.assertTrue(math.isclose(count["0000000000000000"], 500, rel_tol=0.1)) self.assertTrue(math.isclose(count["0111111111111111"], 500, rel_tol=0.1)) def test_parallel_dispatch_lazy_cal_loading(self): """Test adding calibration by lazy loading in parallel environment.""" class TestAddCalibration(TransformationPass): """A fake pass to test lazy pulse qobj loading in parallel environment.""" def __init__(self, target): """Instantiate with target.""" super().__init__() self.target = target def run(self, dag): """Run test pass that adds calibration of SX gate of qubit 0.""" dag.add_calibration( "sx", qubits=(0,), schedule=self.target["sx"][(0,)].calibration, # PulseQobj is parsed here ) return dag backend = FakeMumbaiV2() # This target has PulseQobj entries that provides a serialized schedule data pass_ = TestAddCalibration(backend.target) pm = PassManager(passes=[pass_]) self.assertIsNone(backend.target["sx"][(0,)]._calibration._definition) qc = QuantumCircuit(1) qc.sx(0) qc_copied = [qc for _ in range(10)] qcs_cal_added = pm.run(qc_copied) ref_cal = backend.target["sx"][(0,)].calibration for qc_test in qcs_cal_added: added_cal = qc_test.calibrations["sx"][((0,), ())] self.assertEqual(added_cal, ref_cal) @data(0, 1, 2, 3) def test_backendv2_and_basis_gates(self, opt_level): """Test transpile() with BackendV2 and basis_gates set.""" backend = FakeNairobiV2() qc = QuantumCircuit(5) qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.cz(0, 3) qc.cz(0, 4) qc.measure_all() tqc = transpile( qc, backend=backend, basis_gates=["u", "cz"], optimization_level=opt_level, seed_transpiler=12345678942, ) op_count = set(tqc.count_ops()) self.assertEqual({"u", "cz", "measure", "barrier"}, op_count) for inst in tqc.data: if inst.operation.name not in {"u", "cz"}: continue qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) self.assertIn(qubits, backend.target.qargs) @data(0, 1, 2, 3) def test_backendv2_and_coupling_map(self, opt_level): """Test transpile() with custom coupling map.""" backend = FakeNairobiV2() qc = QuantumCircuit(5) qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.cz(0, 3) qc.cz(0, 4) qc.measure_all() cmap = CouplingMap.from_line(5, bidirectional=False) tqc = transpile( qc, backend=backend, coupling_map=cmap, optimization_level=opt_level, seed_transpiler=12345678942, ) op_count = set(tqc.count_ops()) self.assertTrue({"rz", "sx", "x", "cx", "measure", "barrier"}.issuperset(op_count)) for inst in tqc.data: if len(inst.qubits) == 2: qubit_0 = tqc.find_bit(inst.qubits[0]).index qubit_1 = tqc.find_bit(inst.qubits[1]).index self.assertEqual(qubit_1, qubit_0 + 1) def test_transpile_with_multiple_coupling_maps(self): """Test passing a different coupling map for every circuit""" backend = FakeNairobiV2() qc = QuantumCircuit(3) qc.cx(0, 2) # Add a connection between 0 and 2 so that transpile does not change # the gates cmap = CouplingMap.from_line(7) cmap.add_edge(0, 2) with self.assertRaisesRegex(TranspilerError, "Only a single input coupling"): # Initial layout needed to prevent transpiler from relabeling # qubits to avoid doing the swap transpile( [qc] * 2, backend, coupling_map=[backend.coupling_map, cmap], initial_layout=(0, 1, 2), ) @data(0, 1, 2, 3) def test_backend_and_custom_gate(self, opt_level): """Test transpile() with BackendV2, custom basis pulse gate.""" backend = FakeNairobiV2() inst_map = InstructionScheduleMap() inst_map.add("newgate", [0, 1], pulse.ScheduleBlock()) newgate = Gate("newgate", 2, []) circ = QuantumCircuit(2) circ.append(newgate, [0, 1]) tqc = transpile( circ, backend, inst_map=inst_map, basis_gates=["newgate"], optimization_level=opt_level ) self.assertEqual(len(tqc.data), 1) self.assertEqual(tqc.data[0].operation, newgate) qubits = tuple(tqc.find_bit(x).index for x in tqc.data[0].qubits) self.assertIn(qubits, backend.target.qargs) @ddt class TestTranspileMultiChipTarget(QiskitTestCase): """Test transpile() with a disjoint coupling map.""" def setUp(self): super().setUp() class FakeMultiChip(BackendV2): """Fake multi chip backend.""" def __init__(self): super().__init__() graph = rx.generators.directed_heavy_hex_graph(3) num_qubits = len(graph) * 3 rng = np.random.default_rng(seed=12345678942) rz_props = {} x_props = {} sx_props = {} measure_props = {} delay_props = {} self._target = Target("Fake multi-chip backend", num_qubits=num_qubits) for i in range(num_qubits): qarg = (i,) rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0) x_props[qarg] = InstructionProperties( error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7) ) sx_props[qarg] = InstructionProperties( error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7) ) measure_props[qarg] = InstructionProperties( error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7) ) delay_props[qarg] = None self._target.add_instruction(XGate(), x_props) self._target.add_instruction(SXGate(), sx_props) self._target.add_instruction(RZGate(Parameter("theta")), rz_props) self._target.add_instruction(Measure(), measure_props) self._target.add_instruction(Delay(Parameter("t")), delay_props) cz_props = {} for i in range(3): for root_edge in graph.edge_list(): offset = i * len(graph) edge = (root_edge[0] + offset, root_edge[1] + offset) cz_props[edge] = InstructionProperties( error=rng.uniform(1e-5, 5e-3), duration=rng.uniform(1e-8, 9e-7) ) self._target.add_instruction(CZGate(), cz_props) @property def target(self): return self._target @property def max_circuits(self): return None @classmethod def _default_options(cls): return Options(shots=1024) def run(self, circuit, **kwargs): raise NotImplementedError self.backend = FakeMultiChip() @data(0, 1, 2, 3) def test_basic_connected_circuit(self, opt_level): """Test basic connected circuit on disjoint backend""" qc = QuantumCircuit(5) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_triple_circuit(self, opt_level): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() if opt_level == 0: with self.assertRaises(TranspilerError): tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) return tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) def test_disjoint_control_flow(self): """Test control flow circuit on disjoint coupling map.""" qc = QuantumCircuit(6, 1) qc.h(0) qc.ecr(0, 1) qc.cx(0, 2) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)): qc.reset(0) qc.cz(1, 0) qc.h(3) qc.cz(3, 4) qc.cz(3, 5) target = self.backend.target target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)}) target.add_instruction(IfElseOp, name="if_else") tqc = transpile(qc, target=target) edges = set(target.build_coupling_map().graph.edge_list()) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) elif len(qargs) == 2: self.assertIn(qargs, edges) self.assertIn(instruction.operation.name, target) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) def test_disjoint_control_flow_shared_classical(self): """Test circuit with classical data dependency between connected components.""" creg = ClassicalRegister(19) qc = QuantumCircuit(25) qc.add_register(creg) qc.h(0) for i in range(18): qc.cx(0, i + 1) for i in range(18): qc.measure(i, creg[i]) with qc.if_test((creg, 0)): qc.h(20) qc.ecr(20, 21) qc.ecr(20, 22) qc.ecr(20, 23) qc.ecr(20, 24) target = self.backend.target target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)}) target.add_instruction(IfElseOp, name="if_else") tqc = transpile(qc, target=target) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) @slow_test @data(2, 3) def test_six_component_circuit(self, opt_level): """Test input circuit with more than 1 component per backend component.""" qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) def test_six_component_circuit_level_1(self): """Test input circuit with more than 1 component per backend component.""" opt_level = 1 qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_shared_classical_between_components_condition(self, opt_level): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(19) qc = QuantumCircuit(25) qc.add_register(creg) qc.h(0) for i in range(18): qc.cx(0, i + 1) for i in range(18): qc.measure(i, creg[i]) qc.ecr(20, 21).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) @data(0, 1, 2, 3) def test_shared_classical_between_components_condition_large_to_small(self, opt_level): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(2) qc = QuantumCircuit(25) qc.add_register(creg) # Component 0 qc.h(24) qc.cx(24, 23) qc.measure(24, creg[0]) qc.measure(23, creg[1]) # Component 1 qc.h(0).c_if(creg, 0) for i in range(18): qc.ecr(0, i + 1).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=123456789) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[23]], coupling_map), connected_qubits(initial_layout[qc.qubits[0]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in [23, 24]}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(19)}, components[1]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] # The first node should be a measurement self.assertIsInstance(first_meas_node.op, Measure) # This should be in the first component self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while isinstance(op_node, DAGOpNode): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] @data(1, 2, 3) def test_shared_classical_between_components_condition_large_to_small_reverse_index( self, opt_level ): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(2) qc = QuantumCircuit(25) qc.add_register(creg) # Component 0 qc.h(0) qc.cx(0, 1) qc.measure(0, creg[0]) qc.measure(1, creg[1]) # Component 1 qc.h(24).c_if(creg, 0) for i in range(23, 5, -1): qc.ecr(24, i).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[0]], coupling_map), connected_qubits(initial_layout[qc.qubits[6]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(2)}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(6, 25)}, components[1]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] # The first node should be a measurement self.assertIsInstance(first_meas_node.op, Measure) # This shoulde be in the first ocmponent self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while isinstance(op_node, DAGOpNode): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] @data(1, 2, 3) def test_chained_data_dependency(self, opt_level): """Test 3 component circuit with shared clbits between each component.""" creg = ClassicalRegister(1) qc = QuantumCircuit(30) qc.add_register(creg) # Component 0 qc.h(0) for i in range(9): qc.cx(0, i + 1) measure_op = Measure() qc.append(measure_op, [9], [creg[0]]) # Component 1 qc.h(10).c_if(creg, 0) for i in range(11, 20): qc.ecr(10, i).c_if(creg, 0) measure_op = Measure() qc.append(measure_op, [19], [creg[0]]) # Component 2 qc.h(20).c_if(creg, 0) for i in range(21, 30): qc.cz(20, i).c_if(creg, 0) measure_op = Measure() qc.append(measure_op, [29], [creg[0]]) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[0]], coupling_map), connected_qubits(initial_layout[qc.qubits[10]], coupling_map), connected_qubits(initial_layout[qc.qubits[20]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10)}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10, 20)}, components[1]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(20, 30)}, components[2]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIsInstance(first_meas_node.op, Measure) self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while not isinstance(op_node.op, Measure): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while not isinstance(op_node.op, Measure): self.assertIn(qubit_map[op_node.qargs[0]], components[2]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIn(qubit_map[op_node.qargs[0]], components[2]) @data("sabre", "stochastic", "basic", "lookahead") def test_basic_connected_circuit_dense_layout(self, routing_method): """Test basic connected circuit on disjoint backend""" qc = QuantumCircuit(5) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) # Lookahead swap skipped for performance @data("sabre", "stochastic", "basic") def test_triple_circuit_dense_layout(self, routing_method): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data("sabre", "stochastic", "basic", "lookahead") def test_triple_circuit_invalid_layout(self, routing_method): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() with self.assertRaises(TranspilerError): transpile( qc, self.backend, layout_method="trivial", routing_method=routing_method, seed_transpiler=42, ) # Lookahead swap skipped for performance reasons @data("sabre", "stochastic", "basic") def test_six_component_circuit_dense_layout(self, routing_method): """Test input circuit with more than 1 component per backend component.""" qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops(self, opt_level): """Test qubits without operations aren't ever used.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(3) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) tqc = transpile(qc, target=target, optimization_level=opt_level) invalid_qubits = {3, 4} self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_with_routing(self, opt_level): """Test qubits without operations aren't ever used.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]}, ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(1, 3) qc.cx(0, 3) tqc = transpile(qc, target=target, optimization_level=opt_level) invalid_qubits = { 4, } self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_circuit_too_large(self, opt_level): """Test qubits without operations aren't ever used and error if circuit needs them.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) with self.assertRaises(TranspilerError): transpile(qc, target=target, optimization_level=opt_level) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_circuit_too_large_disconnected( self, opt_level ): """Test qubits without operations aren't ever used if a disconnected circuit needs them.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(5) qc.x(0) qc.x(1) qc.x(3) qc.x(4) with self.assertRaises(TranspilerError): transpile(qc, target=target, optimization_level=opt_level) @data(0, 1, 2, 3) def test_transpile_does_not_affect_backend_coupling(self, opt_level): """Test that transpiliation of a circuit does not mutate the `CouplingMap` stored by a V2 backend. Regression test of gh-9997.""" if opt_level == 3: raise unittest.SkipTest("unitary resynthesis fails due to gh-10004") qc = QuantumCircuit(127) for i in range(1, 127): qc.ecr(0, i) backend = FakeSherbrooke() original_map = copy.deepcopy(backend.coupling_map) transpile(qc, backend, optimization_level=opt_level) self.assertEqual(original_map, backend.coupling_map) @combine( optimization_level=[0, 1, 2, 3], scheduling_method=["asap", "alap"], ) def test_transpile_target_with_qubits_without_delays_with_scheduling( self, optimization_level, scheduling_method ): """Test qubits without operations aren't ever used.""" no_delay_qubits = [1, 3, 4] target = Target(num_qubits=5, dt=1) target.add_instruction( XGate(), {(i,): InstructionProperties(duration=160) for i in range(4)} ) target.add_instruction( HGate(), {(i,): InstructionProperties(duration=160) for i in range(4)} ) target.add_instruction( CXGate(), { edge: InstructionProperties(duration=800) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)] }, ) target.add_instruction( Delay(Parameter("t")), {(i,): None for i in range(4) if i not in no_delay_qubits} ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(1, 3) qc.cx(0, 3) tqc = transpile( qc, target=target, optimization_level=optimization_level, scheduling_method=scheduling_method, ) invalid_qubits = { 4, } self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) if isinstance(inst.operation, Delay): self.assertNotIn(tqc.find_bit(bit).index, no_delay_qubits)
https://github.com/soultanis/Quantum-SAT-Solver
soultanis
# Import the Qiskit SDK. from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, Aer from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state # Define the number of n-qbits. n = 6 # Create a Quantum Register with n-qbits. q = QuantumRegister(n) # Create a Classical Register with n-bits. c = ClassicalRegister(n) # Create a Quantum Circuit qc = QuantumCircuit(q, c) # Init with |1> qc.x(q[0]) qc.x(q[1]) # Add H-gate to get superposition. qc.h(q[0]) qc.h(q[1]) # Apply the oracle 11. qc.cx(q[0],q[1],q[2]) qc.x(q[0]) qc.x(q[1]) qc.cx(q[0],q[1],q[3]) qc.x(q[0]) qc.x(q[1]) qc.x(q[0]) qc.cx(q[0],q[4]) qc.x(q[0]) qc.x(q[2]) qc.x(q[3]) qc.x(q[4]) qc.x(q[5]) qc.cx(q[2],q[3],q[4],q[5]) qc.x(q[2]) qc.x(q[3]) qc.x(q[4]) qc.x(q[5]) qc.z(q[5]) qc.x(q[2]) qc.x(q[3]) qc.x(q[4]) qc.x(q[5]) qc.cx(q[2],q[3],q[4],q[5]) qc.x(q[2]) qc.x(q[3]) qc.x(q[4]) qc.x(q[5]) qc.x(q[0]) qc.cx(q[0],q[4]) qc.x(q[0]) qc.x(q[0]) qc.x(q[1]) qc.cx(q[0],q[1],q[3]) qc.x(q[0]) qc.x(q[1]) qc.cx(q[0],q[1],q[2]) # Apply the grover-algorithm 11 # Measure qubit to bit. . qc.measure(q, c) # Get Aer backend. backend_sim = Aer.get_backend('qasm_simulator') # Compile and run the Quantum circuit on a simulator backend. sim_result1 = execute(qc, backend_sim, shots=1000).result() counts1 = sim_result1.get_counts(qc) # Show the results as text and plot. print("Simulation: ", sim_result1) print("Output: ", counts1) plot_histogram(counts1) circuit_drawer(qc)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np # useful math functions from math import pi, cos, acos, sqrt # importing the QISKit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend import sys, 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.') # import basic plot tools from qiskit.tools.visualization import plot_histogram M = 16 # Maximum number of physical qubits available numberOfCoins = 8 # This number should be up to M-1, where M is the number of qubits available indexOfFalseCoin = 6 # This should be 0, 1, ..., numberOfCoins - 1, where we use Python indexing if numberOfCoins < 4 or numberOfCoins >= M: raise Exception("Please use numberOfCoins between 4 and ", M-1) if indexOfFalseCoin < 0 or indexOfFalseCoin >= numberOfCoins: raise Exception("indexOfFalseCoin must be between 0 and ", numberOfCoins-1) # Creating registers # numberOfCoins qubits for the binary query string and 1 qubit for working and recording the result of quantum balance qr = QuantumRegister(numberOfCoins+1) # for recording the measurement on qr cr = ClassicalRegister(numberOfCoins+1) circuitName = "QueryStateCircuit" queryStateCircuit = QuantumCircuit(qr, cr) N = numberOfCoins # Create uniform superposition of all strings of length N for i in range(N): queryStateCircuit.h(qr[i]) # Perform XOR(x) by applying CNOT gates sequentially from qr[0] to qr[N-1] and storing the result to qr[N] for i in range(N): queryStateCircuit.cx(qr[i], qr[N]) # Measure qr[N] and store the result to cr[N]. We continue if cr[N] is zero, or repeat otherwise queryStateCircuit.measure(qr[N], cr[N]) # we proceed to query the quantum beam balance if the value of cr[0]...cr[N] is all zero # by preparing the Hadamard state of |1>, i.e., |0> - |1> at qr[N] queryStateCircuit.x(qr[N]).c_if(cr, 0) queryStateCircuit.h(qr[N]).c_if(cr, 0) # we rewind the computation when cr[N] is not zero for i in range(N): queryStateCircuit.h(qr[i]).c_if(cr, 2**N) k = indexOfFalseCoin # Apply the quantum beam balance on the desired superposition state (marked by cr equal to zero) queryStateCircuit.cx(qr[k], qr[N]).c_if(cr, 0) # Apply Hadamard transform on qr[0] ... qr[N-1] for i in range(N): queryStateCircuit.h(qr[i]).c_if(cr, 0) # Measure qr[0] ... qr[N-1] for i in range(N): queryStateCircuit.measure(qr[i], cr[i]) backend = "local_qasm_simulator" shots = 1 # We perform a one-shot experiment results = execute(queryStateCircuit, backend=backend, shots=shots).result() answer = results.get_counts() for key in answer.keys(): if key[0:1] == "1": raise Exception("Fail to create desired superposition of balanced query string. Please try again") plot_histogram(answer) from collections import Counter for key in answer.keys(): normalFlag, _ = Counter(key[1:]).most_common(1)[0] #get most common label for i in range(2,len(key)): if key[i] != normalFlag: print("False coin index is: ", len(key) - i - 1)
https://github.com/qiskit-community/prototype-qrao
qiskit-community
import numpy as np from qiskit.utils import QuantumInstance from qiskit.algorithms.minimum_eigen_solvers import VQE from qiskit.circuit.library import RealAmplitudes from qiskit.algorithms.optimizers import SPSA from qiskit_aer import Aer from qrao import ( QuantumRandomAccessEncoding, QuantumRandomAccessOptimizer, SemideterministicRounding, ) from qrao.utils import get_random_maxcut_qp # Generate a random QUBO in the form of a QuadraticProgram problem = get_random_maxcut_qp(degree=3, num_nodes=6, seed=3, draw=True) print(problem.export_as_lp_string()) # Create an encoding object with a maximum of 3 variables per qubit, aka a (3,1,p)-QRAC encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3) # Encode the QUBO problem into an encoded Hamiltonian operator encoding.encode(problem) # This is our encoded operator print(f"Our encoded Hamiltonian is:\n( {encoding.qubit_op} ).\n") print( "We achieve a compression ratio of " f"({encoding.num_vars} binary variables : {encoding.num_qubits} qubits) " f"≈ {encoding.compression_ratio}.\n" ) # Create a QuantumInstance for solving the relaxed Hamiltonian using VQE relaxed_qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=1024) # Set up the variational quantum eigensolver (ansatz width is determined by the encoding) vqe = VQE( ansatz=RealAmplitudes(encoding.num_qubits), optimizer=SPSA(maxiter=50), quantum_instance=relaxed_qi, ) # Use semideterministic rounding, known as "Pauli rounding" # in https://arxiv.org/pdf/2111.03167v2.pdf # (This is the default if no rounding scheme is specified.) rounding_scheme = SemideterministicRounding() # Construct the optimizer qrao = QuantumRandomAccessOptimizer( encoding=encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme ) # Solve the optimization problem results = qrao.solve(problem) qrao_fval = results.fval print(results) # relaxed function value results.relaxed_fval # optimal function value results.fval # optimal value results.x # status results.status print( f"The obtained solution places a partition between nodes {np.where(results.x == 0)[0]} " f"and nodes {np.where(results.x == 1)[0]}." ) results.relaxed_results results.rounding_results.samples # pylint: disable=wrong-import-order from qiskit_optimization.algorithms import CplexOptimizer cplex_optimizer = CplexOptimizer() cplex_results = cplex_optimizer.solve(problem) exact_fval = cplex_results.fval cplex_results approximation_ratio = qrao_fval / exact_fval print("QRAO Approximate Optimal Function Value:", qrao_fval) print("Exact Optimal Function Value:", exact_fval) print(f"Approximation Ratio: {approximation_ratio:.2f}") import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from docplex.mp.model import Model from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import CobylaOptimizer, MinimumEigenOptimizer from qiskit_optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer from qiskit_optimization.translators import from_docplex_mp # If CPLEX is installed, you can uncomment this line to import the CplexOptimizer. # CPLEX can be used in this tutorial to solve the convex continuous problem, # but also as a reference to solve the QUBO, or even the full problem. # # from qiskit.optimization.algorithms import CplexOptimizer # define COBYLA optimizer to handle convex continuous problems. cobyla = CobylaOptimizer() # define QAOA via the minimum eigen optimizer qaoa = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA())) # exact QUBO solver as classical benchmark exact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) # to solve QUBOs # in case CPLEX is installed it can also be used for the convex problems, the QUBO, # or as a benchmark for the full problem. # # cplex = CplexOptimizer() # construct model using docplex mdl = Model("ex6") v = mdl.binary_var(name="v") w = mdl.binary_var(name="w") t = mdl.binary_var(name="t") u = mdl.continuous_var(name="u") mdl.minimize(v + w + t + 5 * (u - 2) ** 2) mdl.add_constraint(v + 2 * w + t + u <= 3, "cons1") mdl.add_constraint(v + w + t >= 1, "cons2") mdl.add_constraint(v + w == 1, "cons3") # load quadratic program from docplex model qp = from_docplex_mp(mdl) print(qp.prettyprint()) admm_params = ADMMParameters( rho_initial=1001, beta=1000, factor_c=900, maxiter=100, three_block=True, tol=1.0e-6 ) # define QUBO optimizer qubo_optimizer = exact # qubo_optimizer = cplex # uncomment to use CPLEX instead # define classical optimizer convex_optimizer = cobyla # convex_optimizer = cplex # uncomment to use CPLEX instead # initialize ADMM with classical QUBO and convex optimizer admm = ADMMOptimizer( params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer ) # run ADMM to solve problem result = admm.solve(qp) print(result.prettyprint()) plt.plot(result.state.residuals) plt.xlabel("Iterations") plt.ylabel("Residuals") plt.show() # define QUBO optimizer qubo_optimizer = qaoa # define classical optimizer convex_optimizer = cobyla # convex_optimizer = cplex # uncomment to use CPLEX instead # initialize ADMM with quantum QUBO optimizer and classical convex optimizer admm_q = ADMMOptimizer( params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer ) # run ADMM to solve problem result_q = admm_q.solve(qp) print(result.prettyprint()) plt.clf() plt.plot(result_q.state.residuals) plt.xlabel("Iterations") plt.ylabel("Residuals") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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. """ A collection of functions that decide the layout of an output image. See :py:mod:`~qiskit.visualization.timeline.types` for more info on the required data. There are 2 types of layout functions in this module. 1. layout.bit_arrange In this stylesheet entry the input data is a list of `types.Bits` and returns a sorted list of `types.Bits`. The function signature of the layout is restricted to: ```python def my_layout(bits: List[types.Bits]) -> List[types.Bits]: # your code here: sort input bits and return list of bits ``` 2. layout.time_axis_map In this stylesheet entry the input data is `Tuple[int, int]` that represents horizontal axis limit of the output image. The layout function returns `types.HorizontalAxis` data which is consumed by the plotter API to make horizontal axis. The function signature of the layout is restricted to: ```python def my_layout(time_window: Tuple[int, int]) -> types.HorizontalAxis: # your code here: create and return axis config ``` Arbitrary layout function satisfying the above format can be accepted. """ import warnings from typing import List, Tuple import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import types def qreg_creg_ascending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by ascending order. Bit order becomes Q0, Q1, ..., Cl0, Cl1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") with warnings.catch_warnings(): warnings.simplefilter("ignore") qregs = sorted(qregs, key=lambda x: x.index, reverse=False) cregs = sorted(cregs, key=lambda x: x.index, reverse=False) return qregs + cregs def qreg_creg_descending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by descending order. Bit order becomes Q_N, Q_N-1, ..., Cl_N, Cl_N-1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") qregs = sorted(qregs, key=lambda x: x.index, reverse=True) cregs = sorted(cregs, key=lambda x: x.index, reverse=True) return qregs + cregs def time_map_in_dt(time_window: Tuple[int, int]) -> types.HorizontalAxis: """Layout function for the horizontal axis formatting. Generate equispaced 6 horizontal axis ticks. Args: time_window: Left and right edge of this graph. Returns: Axis formatter object. """ # shift time axis t0, t1 = time_window # axis label axis_loc = np.linspace(max(t0, 0), t1, 6) axis_label = axis_loc.copy() # consider time resolution label = "System cycle time (dt)" formatted_label = [f"{val:.0f}" for val in axis_label] return types.HorizontalAxis( window=(t0, t1), axis_map=dict(zip(axis_loc, formatted_label)), label=label )
https://github.com/C2QA/bosonic-qiskit
C2QA
from qiskit import QuantumRegister class QumodeRegister: """Wrapper to QisKit QuantumRegister to represent multiple qubits per qumode. Implements __getitem__ to make QumodeRegister appear to work just like QuantumRegister with instances of CVCircuit. """ def __init__( self, num_qumodes: int, num_qubits_per_qumode: int = 2, name: str = None ): """Initialize QumodeRegister Args: num_qumodes (int): total number of qumodes num_qubits_per_qumode (int, optional): Number of qubits representing each qumode. Defaults to 2. name (str, optional): Name of register. Defaults to None. """ self.size = num_qumodes * num_qubits_per_qumode self.num_qumodes = num_qumodes self.num_qubits_per_qumode = num_qubits_per_qumode self.cutoff = QumodeRegister.calculate_cutoff(num_qubits_per_qumode) # Aggregate the QuantumRegister representing these qumodes as # extending the class confuses QisKit when overriding __getitem__(). # It doesn't expect a list of Qubit back when indexing a single value # (i.e., qmr[0] is represented by multiple qubits). self.qreg = QuantumRegister(size=self.size, name=name) @staticmethod def calculate_cutoff(num_qubits_per_qumode: int): return 2**num_qubits_per_qumode def get_qumode_index(self, qubit): """Get the qumode index for the given qubit in this register""" qubit_index = self.qreg.index(qubit) return qubit_index // self.num_qubits_per_qumode def __iter__(self): """Iterate over the list of lists representing the qubits for each qumode in the register""" return QumodeIterator(self) def __getitem__(self, key): """Return a list of QisKit Qubit for each indexed qumode Args: key (slice or int): index into qumode register Raises: ValueError: if slice or int not provided Returns: list: ;ost pf qubits from QuantumRegister representing qumode """ start = None stop = self.size step = None if isinstance(key, slice): start_index = key.start if key.start else 0 stop_index = key.stop if key.stop else self.size start = self.num_qubits_per_qumode * start_index stop = ( self.num_qubits_per_qumode * stop_index ) + self.num_qubits_per_qumode step = (key.step * self.num_qubits_per_qumode) if key.step else None elif isinstance(key, int): start = self.num_qubits_per_qumode * key stop = start + self.num_qubits_per_qumode else: raise ValueError("Must provide slice or int.") return self.qreg[start:stop:step] def __len__(self): """The length of a QumodeRegister is the number of qumodes (not the num_qumodes * num_qubits_per_qumode)""" return self.num_qumodes def __contains__(self, qubit): """Return true if this QumodeRegister contains the given qubit. This allows callers to use `in` python syntax.""" return qubit in self.qreg class QumodeIterator: """Iterate over the list of lists representing the qubits for each qumode in the register""" def __init__(self, register: QumodeRegister): self._index = 0 self._register = register def __iter__(self): return self def __next__(self): if self._index < self._register.num_qumodes: next = self._register[self._index] self._index += 1 return next else: raise StopIteration
https://github.com/usamisaori/qLipschitz
usamisaori
from sklearn import datasets import numpy as np import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') X_train, Y_train = datasets.make_circles(n_samples=500, noise=0.09, factor=0.4) X_test, Y_test = datasets.make_circles(n_samples=200, noise=0.09, factor=0.4) print('Training Data:') print(X_train[:10]) print('\nTraining Label:') print(Y_train[:10]) plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train) plt.show() print(f'Total datas: {len(X_train)}') print(f'labels: {list(set(Y_train))}') print(f' - label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f' - label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}') Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5 temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1)) temp[:, :-1] = X_train temp[:, -1] = Z_train X_train2 = temp Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5 temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1)) temp[:, :-1] = X_test temp[:, -1] = Z_test X_test2 = temp print('Solved Training Data:') print(X_train2[:10]) def plot3D(X, Y): fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') ax.scatter( X[:, 0], X[:, 1], X[:, 2], zdir='z', s=30, c=Y, depthshade=True ) plt.show() plot3D(X_train2, Y_train) X, Y = datasets.load_iris(return_X_y=True) X_train_0 = X[0:30] X_train_1 = X[50:80] X_train_iris = np.vstack((X_train_0, X_train_1)) Y_train_0 = Y[0:30] Y_train_1 = Y[50:80] Y_train_iris = np.vstack((Y_train_0, Y_train_1)).flatten() X, Y = datasets.load_iris(return_X_y=True) X_test_0 = X[30:50] X_test_1 = X[80:100] X_test_iris = np.vstack((X_test_0, X_test_1)) Y_test_0 = Y[30:50] Y_test_1 = Y[80:100] Y_test_iris = np.vstack((Y_test_0, Y_test_1)).flatten() X_train_iris = (X_train_iris - X_train_iris.min(axis=0)) / (X_train_iris.max(axis=0) - X_train_iris.min(axis=0)) X_test_iris = (X_test_iris - X_test_iris.min(axis=0)) / (X_test_iris.max(axis=0) - X_test_iris.min(axis=0)) import qiskit from qiskit import QuantumCircuit from qiskit import Aer, execute qasm_backend = Aer.get_backend('qasm_simulator') params = [ [[-1.18991246e-01, -8.69694713e-01, 1.43722811e-03], [ 3.47641545e+00, -4.73632073e-02, 1.97135609e+00], [ 1.95775707e+00, -1.12139160e-02, -6.21796144e-03]], [[ 2.02460380e-02, -2.25797547e+00, 5.14234265e-03], [-1.71552299e-02, 2.46283604e-03, -1.03805722e-02], [-2.37244982e-03, -3.35799404e-03, 6.10191152e-03]] ] params_iris = [ [[-3.42142600e-02, -5.45047534e-03, 8.11905347e-01], [-1.52484152e+00, 1.49884676e+00, -1.25408626e-02], [-1.89515860e-03, 1.35760410e-02, 8.22999582e-03], [ 1.39102114e+00, 4.19729865e-01, 1.60000380e-04]], [[ 7.88431068e-01, -8.86177264e-01, 1.33830291e-02], [-3.71228143e-03, -1.12994101e-02, -1.27897783e-02], [ 9.45954683e-03, -3.34659883e-03, 1.17217829e-02], [ 1.98256181e-02, -1.07358054e-02, 7.53621360e-03]] ] def createInputCircuit(data): qubits_num = len(data) qcircuit = QuantumCircuit(qubits_num, qubits_num) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) return qcircuit # Test 1: create input circuit test1_circuit = createInputCircuit(X_train2[0]) test1_circuit.draw(output='mpl') def createModelCircuit(params): qubits_num = len(params[0]) qcircuit = QuantumCircuit(qubits_num, qubits_num) qubits = qcircuit.qubits for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) for i in range(qubits_num - 1): qcircuit.cz(qubits[i], qubits[i + 1]) qcircuit.cz(qubits[0], qubits[qubits_num - 1]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) return qcircuit # Test 2: create model circuit test2_circuit = createModelCircuit(params) test2_circuit.draw(output='mpl') def createCircuit(params, data): input_circuit = createInputCircuit(data) model_circuit = createModelCircuit(params) full_circuit = input_circuit.compose(model_circuit) return full_circuit # Test 3-1: create full quantum circuit - circle test3_circuit = createCircuit(params, X_train2[0]) test3_circuit.draw(output='mpl') # Test 3-2: create full quantum circuit - iris test3_circuit = createCircuit(params_iris, X_train_iris[1]) test3_circuit.draw(output='mpl') def predict(model, data): qubits_num = len(data) input_circuit = createInputCircuit(data) qcircuit = input_circuit.compose(model) # the measurement qcircuit.measure(list(range(qubits_num)), list(range(qubits_num))) # job execution shots = 1000 job_sim = execute(qcircuit, qasm_backend, shots=shots) result_sim = job_sim.result() counts = result_sim.get_counts(qcircuit) p1 = 0 for i in range(2 ** (qubits_num - 1)): comb = str(bin(i + 2 ** (qubits_num - 1))[2:]) p1 += counts.get(comb, 0) p1 /= shots if p1 > 0.5: return 1 else: return 0 def accuracy(model, datas, labels): predictions = [ predict(model, data) for data in datas ] acc = 0 for i, p in enumerate(predictions): if p == labels[i]: acc += 1 return acc / len(predictions) def evaluate(model, X_test, Y_test): acc = accuracy(model, X_test, Y_test) print("FINAL ACCURACY: {:0.2f}%".format(acc * 100)) # Test 4: evaluate noiseless model test4_circuit = createModelCircuit(params_iris) evaluate(test4_circuit, X_train_iris, Y_train_iris) evaluate(test4_circuit, X_test_iris, Y_test_iris) from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.utils import insert_noise from qiskit.providers.aer.noise import pauli_error, depolarizing_error def createNoiseModel(p, errorType): # QuantumError objects if errorType == 'bit_flip': error = pauli_error([('X', p), ('I', 1 - p)]) elif errorType == 'phase_flip': error = pauli_error([('Z', p), ('I', 1 - p)]) elif errorType == 'depolarizing': error = depolarizing_error(p, num_qubits=1) ## two-qubits quantumError objects if errorType == 'depolarizing': error_2qubits = depolarizing_error(p, num_qubits=2) else: error_2qubits = error.tensor(error) # Add errors to noise model noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ['u3']) noise_model.add_all_qubit_quantum_error(error_2qubits, ['cz']) return noise_model def createNoisyModelCircuit(params, p, errorType): noise_model = createNoiseModel(p, errorType) model_circuit = createModelCircuit(params) return insert_noise(model_circuit, noise_model) # Test 5-1: create noisy model circuit - circle test5_p = 0.001 test5_circuit = createNoisyModelCircuit(params, test5_p, 'phase_flip') test5_circuit.draw(output='mpl') # Test 5-2: create noisy model circuit - iris test5_p = 0.001 test5_circuit = createNoisyModelCircuit(params_iris, test5_p, 'bit_flip') test5_circuit.draw(output='mpl') # Test 6-1: evaluate noisy model - circle test6_p = 0.001 models_type = [ 'noiseless', 'bit_flip', 'phase_flip', 'depolarizing' ] test6_circuits = [ createModelCircuit(params), createNoisyModelCircuit(params, test6_p, 'bit_flip'), createNoisyModelCircuit(params, test6_p, 'phase_flip'), createNoisyModelCircuit(params, test6_p, 'depolarizing') ] for i, model_type in enumerate(models_type): print(f'Evaluate <{model_type}>: ') evaluate(test6_circuits[i], X_test2, Y_test) print() # Test 6-2: evaluate noisy model - iris test6_p = 0.5 models_type = [ 'noiseless', 'bit_flip', 'phase_flip', 'depolarizing' ] test6_circuits = [ createModelCircuit(params_iris), createNoisyModelCircuit(params_iris, test6_p, 'bit_flip'), createNoisyModelCircuit(params_iris, test6_p, 'phase_flip'), createNoisyModelCircuit(params_iris, test6_p, 'depolarizing') ] for i, model_type in enumerate(models_type): print(f'Evaluate <{model_type}>: ') evaluate(test6_circuits[i], X_test_iris, Y_test_iris) print() from functools import reduce Dag = lambda matrix: matrix.conj().T Kron = lambda *matrices: reduce(np.kron, matrices) from qiskit.quantum_info import DensityMatrix, Statevector def getDensityMatrix(circuit): return DensityMatrix(circuit).data def getStatevector(circuit): return Statevector(circuit).data psi_0 = np.array([1.0, 0.0]) psi_1 = np.array([0.0, 1.0]) I = np.eye(2) M_0 = psi_0.reshape([2, 1]) @ psi_0.reshape([1, 2]).conj() M_1 = psi_1.reshape([2, 1]) @ psi_1.reshape([1, 2]).conj() def getMeasurements(qubits_num): measurement_0 = [M_0] measurement_1 = [M_1] for i in range(qubits_num - 1): measurement_0.append(I) measurement_1.append(I) return [ Kron(*measurement_0), Kron(*measurement_1) ] # Test 7: test measure test7_M_0, test7_M_1 = getMeasurements(qubits_num=3) # 2: |0> - X - test7_1_circuit = QuantumCircuit(3, 3) test7_1_circuit.x(test7_1_circuit.qubits[2]) test7_1_circuit.draw(output='mpl') test7_1_density_matrix = getDensityMatrix(test7_1_circuit) test7_1_p1 = np.trace( test7_M_1 @ test7_1_density_matrix @ Dag(test7_M_1) ) print(test7_1_p1) # should be 1 # 2: |0> - H - test7_2_circuit = QuantumCircuit(3, 3) test7_2_circuit.h(test7_2_circuit.qubits[2]) test7_2_circuit.draw(output='mpl') test7_2_density_matrix = getDensityMatrix(test7_2_circuit) test7_2_p1 = np.trace( test7_M_1 @ test7_2_density_matrix @ Dag(test7_M_1) ) print(test7_2_p1) # should be 0.5 test7_M_0, test7_M_1 = getMeasurements(qubits_num=4) # 3: |0> - H - test7_3_circuit = QuantumCircuit(4, 4) test7_3_circuit.h(test7_3_circuit.qubits[3]) test7_3_circuit.draw(output='mpl') test7_3_density_matrix = getDensityMatrix(test7_3_circuit) test7_3_p1 = np.trace( test7_M_1 @ test7_3_density_matrix @ Dag(test7_M_1) ) print(test7_3_p1) # should be 0.5 def powerSets(items): N = len(items) combs = [] for i in range(2 ** N): comb = [] for j in range(N): if (i >> j) % 2: comb.append(items[j]) combs.append(comb) return combs # Test 8: calculate power sets print(powerSets([0, 1])) class Algorithm: def __init__(self, model_circuit, measurements, outputs): # DensityMatrix of model self.E = getDensityMatrix(model_circuit) # Measurements self.M = dict() for index, output in enumerate(outputs): self.M[output] = measurements[index] # Outputs self.O = outputs self.O_ = powerSets(outputs) # Test 9: algorithm objects test9_circuit = createModelCircuit(params_iris) test9_A = Algorithm(test9_circuit, getMeasurements(qubits_num=4), [0, 1]) print(test9_A.E.shape) print(test9_A.O) print(test9_A.O_) from scipy.linalg import sqrtm def D(rou, sigma): A = rou - sigma A_ = sqrtm( np.dot( A.conj().T, A ) ) return 0.5 * np.linalg.norm( np.trace(A_) ) # Test 10: trace distance example from math import isclose # example from: quantumnanophotonics.org/media/Module2Lecture8.pdf test10_rou = np.array([[2.0, 0.0], [0.0, 1.0]]) / 3 test10_sigma = np.array([[3.0, 0.0], [0.0, 1.0]]) / 4 assert isclose(D(test10_rou, test10_sigma), 1/12) # Test 11: calculate input states' distance test11_rou = getDensityMatrix(createInputCircuit(X_train2[0])) test11_sigma = getDensityMatrix(createInputCircuit(X_train2[1])) print(D(test11_rou, test11_rou)) # should be 0 print(D(test11_rou, test11_sigma)) def d(A, rou, sigma): distance = 0 for output in A.O: trace = np.trace( Dag(A.M[output]) @ A.M[output] @ (A.E @ (rou - sigma) @ Dag(A.E)) ) distance += np.linalg.norm(trace) return distance / 2 # Test 12: calculate total variation distance test12_circuit = createModelCircuit(params) test12_A = Algorithm(test12_circuit, getMeasurements(qubits_num=3), [0, 1]) test12_rou = getDensityMatrix(createInputCircuit(X_train2[0])) test12_sigma = getDensityMatrix(createInputCircuit(X_train2[1])) print(d(test12_A, test12_rou, test12_rou)) print(d(test12_A, test12_rou, test12_sigma)) def Lipschitz(A): E, M, O, O_ = A.E, A.M, A.O, A.O_ # Step 1: Calculate W_i W = dict() for i in O: W[i] = Dag(E) @ Dag(M[i]) @ M[i] @ E # Step 2: Calculate K_star K_star = 0; vectors = [None, None] M_star = np.zeros(E.shape) for S in O_: if len(S) == 0: continue # calculate M_S = Σ Wi M_S = np.zeros(E.shape).astype('complex64') for i in S: M_S += W[i] # calculate eigenvalues and eigenvectors of M_S eigenvalues, eigenvectors = np.linalg.eigh(M_S) min_index = np.where(eigenvalues == eigenvalues.min()) max_index = np.where(eigenvalues == eigenvalues.max()) # calculate K_S K_S = np.linalg.norm(eigenvalues[max_index][0] - eigenvalues[min_index][0]) if K_S > K_star: K_star = K_S vectors[0] = eigenvectors.T[max_index][0] vectors[1] = eigenvectors.T[min_index][0] return K_star, np.array(vectors) # Test 13: calculate lipschitz constant print('Classifier for centric circle: ') test13_1_circuit = createModelCircuit(params) test13_1_A = Algorithm(test13_1_circuit, getMeasurements(qubits_num=3), [0, 1]) print(Lipschitz(test13_1_A)) print('\nClassifier for Iris: ') test13_2_circuit = createModelCircuit(params_iris) test13_2_A = Algorithm(test13_2_circuit, getMeasurements(qubits_num=4), [0, 1]) print(Lipschitz(test13_2_A)) # Test 14-1: calculate lipschitz constant in noisy model test14_p = [0.0001, 0.001, 0.05, 0.1] models_type = [ 'noiseless', 'bit_flip', 'phase_flip', 'depolarizing' ] print('Classifier for centric circle: ') for p in test14_p: test14_1_circuits = [ createModelCircuit(params), createNoisyModelCircuit(params, p, 'bit_flip'), createNoisyModelCircuit(params, p, 'phase_flip'), createNoisyModelCircuit(params, p, 'depolarizing') ] print(f'p: {p}') for i, model_type in enumerate(models_type): test14_1_noisy_A = Algorithm(test14_1_circuits[i], getMeasurements(qubits_num=3), [0, 1]) print(f'{model_type} model: {Lipschitz(test14_1_noisy_A)[0]}') print() # Test 14-2: calculate lipschitz constant in noisy model test14_p = [0.0001, 0.001, 0.05, 0.1] models_type = [ 'noiseless', 'bit_flip', 'phase_flip', 'depolarizing' ] print('Classifier for Iris: ') for p in test14_p: test14_2_circuits = [ createModelCircuit(params_iris), createNoisyModelCircuit(params_iris, p, 'bit_flip'), createNoisyModelCircuit(params_iris, p, 'phase_flip'), createNoisyModelCircuit(params_iris, p, 'depolarizing') ] print(f'p: {p}') for i, model_type in enumerate(models_type): test14_2_noisy_A = Algorithm(test14_2_circuits[i], getMeasurements(qubits_num=4), [0, 1]) print(f'{model_type} model: {Lipschitz(test14_2_noisy_A)[0]}') print() def FairVeriQ(A, epsilon, delta): # epsilon <= 1 and delta > 0 K_star, kernel = Lipschitz(A) if delta >= K_star * epsilon: return True, None else: return False, kernel # Test 15-1: find proper epsilon - circle import random # D(rou, sigma) <= epsilon indices = [] while len(indices) < 50: a = random.randint(0, len(X_train2) - 1) b = random.randint(0, len(X_train2) - 1) if a != b: indices.append([a, b]) distances = [] for pair in indices: rou = getDensityMatrix(createInputCircuit(X_train2[pair[0]])) sigma = getDensityMatrix(createInputCircuit(X_train2[pair[1]])) distances.append(D(rou, sigma)) print('find proper epsilon - centric circle') print(f'Mean distance: {sum(distances) / len(distances)}') print(f'Max distance: {max(distances)}') print(f'Min distance: {min(distances)}') # Test 15-2: find proper epsilon - iris # D(rou, sigma) <= epsilon indices = [] while len(indices) < 50: a = random.randint(0, len(X_train_iris) - 1) b = random.randint(0, len(X_train_iris) - 1) if a != b: indices.append([a, b]) distances = [] for pair in indices: rou = getDensityMatrix(createInputCircuit(X_train_iris[pair[0]])) sigma = getDensityMatrix(createInputCircuit(X_train_iris[pair[1]])) distances.append(D(rou, sigma)) print('find proper epsilon - centric iris') print(f'Mean distance: {sum(distances) / len(distances)}') print(f'Max distance: {max(distances)}') print(f'Min distance: {min(distances)}') # Test 16-1: find proper delta - circle test16_1_circuit = createModelCircuit(params) test16_1_A = Algorithm(test16_1_circuit, getMeasurements(qubits_num=3), [0, 1]) # d(A(rou), A(sigma)) <= delta indices = [] while len(indices) < 50: a = random.randint(0, len(X_train2) - 1) b = random.randint(0, len(X_train2) - 1) if a != b: indices.append([a, b]) distances = [] for pair in indices: rou = getDensityMatrix(createInputCircuit(X_train2[pair[0]])) sigma = getDensityMatrix(createInputCircuit(X_train2[pair[1]])) distances.append(d(test16_1_A, rou, sigma)) print('find proper delta - circle') print(f'Mean distance: {sum(distances) / len(distances)}') print(f'Max distance: {max(distances)}') print(f'Min distance: {min(distances)}') # Test 16-2: find proper delta - iris test16_2_circuit = createModelCircuit(params_iris) test16_2_A = Algorithm(test16_2_circuit, getMeasurements(qubits_num=4), [0, 1]) # d(A(rou), A(sigma)) <= delta indices = [] while len(indices) < 50: a = random.randint(0, len(X_train_iris) - 1) b = random.randint(0, len(X_train_iris) - 1) if a != b: indices.append([a, b]) distances = [] for pair in indices: rou = getDensityMatrix(createInputCircuit(X_train_iris[pair[0]])) sigma = getDensityMatrix(createInputCircuit(X_train_iris[pair[1]])) distances.append(d(test16_2_A, rou, sigma)) print('find proper delta - iris') print(f'Mean distance: {sum(distances) / len(distances)}') print(f'Max distance: {max(distances)}') print(f'Min distance: {min(distances)}') # Test 17-1: fairness verifying - circle test17_1_circuit = createNoisyModelCircuit(params, p=0.001, errorType='bit_flip') test17_1_A = Algorithm(test17_1_circuit, getMeasurements(qubits_num=3), [0, 1]) print(f'Lipschitz constant: {Lipschitz(test17_1_A)[0]}\n') test17_1_fairness_params = [ # epsilon, delta [1, 1], [0.9, 0.89], [0.6, 0.58], [0.6, 0.59] ] for epsilon, delta in test17_1_fairness_params: flag, kernel = FairVeriQ(test17_1_A, epsilon, delta) print(f'A is ({epsilon},{delta})-fair: <{flag}>') if not flag: print(f' - bias kernel pair is: {kernel}') print() # Test 17-2: fairness verifying - iris test17_2_circuit = createNoisyModelCircuit(params_iris, p=0.001, errorType='phase_flip') test17_2_A = Algorithm(test17_2_circuit, getMeasurements(qubits_num=4), [0, 1]) print(f'Lipschitz constant: {Lipschitz(test17_2_A)[0]}\n') test17_2_fairness_params = [ # epsilon, delta [1, 0.99], [0.8, 0.79], [0.5, 0.3] ] for epsilon, delta in test17_2_fairness_params: flag, kernel = FairVeriQ(test17_2_A, epsilon, delta) print(f'A is ({epsilon},{delta})-fair: <{flag}>') if not flag: print(f' - bias kernel pair is: {kernel}') print() def generateBiasPair(sigma, kernel, epsilon): psi, phi = kernel size = len(psi) psi = psi.reshape(size, 1) @ Dag(psi.reshape(size, 1)) phi = phi.reshape(size, 1) @ Dag(phi.reshape(size, 1)) rou_psi = epsilon * psi + (1 - epsilon) * sigma rou_phi = epsilon * phi + (1 - epsilon) * sigma return np.array([ rou_psi, rou_phi ]) # Test 18: generate bias pair test18_circuit = createNoisyModelCircuit(params_iris, p=0.01, errorType='depolarizing') test18_A = Algorithm(test18_circuit, getMeasurements(qubits_num=4), [0, 1]) print(f'Lipschitz constant: {Lipschitz(test17_2_A)[0]}\n') flag, kernel = FairVeriQ(test18_A, epsilon=0.9, delta=0.3) print(f'fairness: {flag}') assert (not flag) test18_sigma = getDensityMatrix(createInputCircuit(X_train_iris[11])) test18_bias_pair = generateBiasPair(test18_sigma, kernel, epsilon=0.9) test18_rou_psi, test18_rou_phi = test18_bias_pair # print(test18_bias_pair) print(f'epsilon=0.9, delta=0.3') print('D: ', D(test18_rou_psi, test18_rou_phi)) print('d: ', d(test18_A, test18_rou_psi, test18_rou_phi))
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
Alice-Bob-SW
from typing import Iterator, Tuple import pytest from qiskit import QuantumCircuit, transpile from qiskit.extensions.quantum_initializer import Initialize from qiskit_alice_bob_provider.local.backend import ProcessorSimulator from qiskit_alice_bob_provider.processor.description import ( ProcessorDescription, ) from .processor_fixture import SimpleAllToAllProcessor, SimpleProcessor def gen_circuits() -> Iterator[Tuple[str, QuantumCircuit, int]]: circ = QuantumCircuit(2, 2) circ.initialize('0', 0) circ.initialize('+', 1) circ.x(0) circ.rz(11, 1) circ.cx(0, 1) circ.measure(0, 0) circ.measure_x(1, 1) yield ('qubits_competing_for_duration', circ, 11100110) sub_sub_circ = QuantumCircuit(2, 0) sub_sub_circ.x(0) sub_sub_circ.rz(11, 1) sub_circ = QuantumCircuit(2, 0) sub_circ.append(sub_sub_circ.to_instruction(), [1, 0]) circ = QuantumCircuit(2, 2) circ.initialize('0', 0) circ.initialize('+', 1) circ.append(sub_circ.to_instruction(), [1, 0]) circ.cx(0, 1) circ.measure(0, 0) circ.measure_x(1, 1) yield ('sub_circuits', circ, 11100110) def gen_all_to_all_circuits() -> Iterator[Tuple[str, QuantumCircuit, int]]: circ = QuantumCircuit(2, 2) circ.initialize('0', 0) # 1e3 circ.initialize('+', 1) # 1e2 circ.x(0) # 1e7 circ.t(1) # 1e6 circ.cx(0, 1) # 1e1 circ.measure(0, 0) # 1e5 circ.measure_x(1, 1) # 1e4 yield ('qubits_competing_for_duration', circ, 10101010) sub_sub_circ = QuantumCircuit(2, 0) sub_sub_circ.x(0) # 1e7 sub_sub_circ.t(1) # 1e6 sub_circ = QuantumCircuit(2, 0) sub_circ.append(sub_sub_circ.to_instruction(), [1, 0]) circ = QuantumCircuit(2, 2) circ.initialize('0', 0) # 1e3 circ.initialize('+', 1) # 1e2 circ.append(sub_circ.to_instruction(), [1, 0]) circ.cx(0, 1) # 1e1 circ.measure(0, 0) # 1e5 circ.measure_x(1, 1) # 1e4 yield ('sub_circuits', circ, 10101010) @pytest.mark.parametrize( 'tup,proc', [(tup, SimpleAllToAllProcessor(1)) for tup in gen_all_to_all_circuits()] + [(tup, SimpleProcessor(1)) for tup in gen_circuits()], ) def test_circuit( tup: Tuple[str, QuantumCircuit, int], proc: ProcessorDescription ) -> None: _, circ, expected_duration = tup backend = ProcessorSimulator(proc) transpiled = transpile(circ, backend) try: assert transpiled.duration == expected_duration except AssertionError: print('==== Original circuit ====') print(circ) print('==== Transpiled circuit ====') print(transpiled) raise @pytest.mark.parametrize( 'proc', [ SimpleProcessor(1), SimpleAllToAllProcessor(1), ], ) def test_reset_to_initialize(proc: ProcessorDescription) -> None: circ = QuantumCircuit(1, 0) circ.reset(0) backend = ProcessorSimulator(proc) transpiled = transpile(circ, backend) initializes = transpiled.get_instructions('initialize') print(circ) print(transpiled) assert len(initializes) == 1 assert isinstance(initializes[0].operation, Initialize) assert initializes[0].operation.params[0] == '0' assert len(transpiled.get_instructions('reset')) == 0
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
gustavomirapalheta
import numpy as np D0 = np.array([[1],[0]]); D0 NOT = np.array([[0,1],[1,0]]); NOT NOT.dot(D0) D1 = np.array([[0],[1]]); D1 NOT.dot(D1) AND = np.array([[1,1,1,0],[0,0,0,1]]); AND AND.dot(np.kron(D0,D0)) AND.dot(np.kron(D0,D1)) AND.dot(np.kron(D1,D0)) AND.dot(np.kron(D1,D1)) OR = np.array([[1,0,0,0],[0,1,1,1]]); OR OR.dot(np.kron(D0,D0)) OR.dot(np.kron(D0,D1)) OR.dot(np.kron(D1,D0)) OR.dot(np.kron(D1,D1)) NAND = np.array([[0,0,0,1],[1,1,1,0]]); NAND NOT.dot(AND) NOR = np.array([[0,1,1,1],[1,0,0,0]]);NOR NOT.dot(OR) np.kron(NOT,AND) OR.dot(np.kron(NOT,AND)) NOT.dot(AND).dot(np.kron(NOT,NOT)) OR NOT.dot(OR).dot(np.kron(NOT,NOT)) AND import numpy as np k = np.kron XOR = np.array([[1,0,0,1], [0,1,1,0]]) AND = np.array(([1,1,1,0], [0,0,0,1])) k(XOR,AND) def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) k(XOR,AND).dot(criaCompat(2,2)) import numpy as np k = np.kron def criaCompat(nbits,nvezes): nlins = 2**(nbits*nvezes) ncols = 2**nbits compat = np.zeros(nlins*ncols).reshape(nlins,ncols) for i in range(ncols): formato = "0" + str(nbits) + "b" binario = format(i,formato)*nvezes decimal = int(binario,2) compat[decimal,i] = 1 return(compat) criaCompat(2,2) NOT = np.array([[0,1], [1,0]]) AND3 = np.array([[1,1,1,1,1,1,1,0], [0,0,0,0,0,0,0,1]]) OR4 = np.array([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]) I2 = np.array([[1,0], [0,1]]) t1z = k(NOT,k(NOT,I2)) t2z = k(NOT,k(I2,NOT)) t3z = k(I2,k(NOT,NOT)) t4z = k(I2,k(I2,I2)) ORz = k(AND3,k(AND3,k(AND3,AND3))) ORz = OR4.dot(ORz).dot(k(t1z,k(t2z,k(t3z,t4z)))) t1c = k(NOT,k(I2,I2)) t2c = k(I2,k(NOT,I2)) t3c = k(I2,k(I2,NOT)) t4c = k(I2,k(I2,I2)) ORc = k(AND3,k(AND3,k(AND3,AND3))) ORc = OR4.dot(ORc).dot(k(t1c,k(t2c,k(t3c,t4c)))) compat = criaCompat(3,8) k(ORz,ORc).dot(compat) import numpy as np TOFFOLI = np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0]]) TOFFOLI.dot(TOFFOLI) import numpy as np Z1 = np.array([[0,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,1,1,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,1]]) Z1 Z1I4 = np.array([[0,0,0,0], [1,0,0,0], [0,0,0,0], [0,1,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,0], [0,0,0,1]]) Z1I4 ZpY = np.zeros([8,8]) ZpY[0,0] = 1; ZpY[1,2] = 1; ZpY[2,1] = 1; ZpY[3,3] = 1 ZpY[4,4] = 1; ZpY[5,6] = 1; ZpY[6,5] = 1; ZpY[7,7] = 1 ZpY Zfim = np.array([[1,0,1,0,1,0,1,0], [0,1,0,1,0,1,0,1]]) Zfim.dot(TOFFOLI).dot(ZpY).dot(TOFFOLI).dot(Z1I4) import numpy as np fred = np.identity(8) fred[5,5] = 0; fred[5,6] = 1 fred[6,5] = 1; fred[6,6] = 0 fred fred.dot(fred) import numpy as np Fy0 = np.zeros([8,4]) Fy0[0,0] = 1; Fy0[1,1] = 1; Fy0[4,2] = 1; Fy0[5,3] = 1 Fy0 xYz = np.array([[1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1]]) xYz.dot(fred).dot(Fy0)
https://github.com/theflyingrahul/qiskitsummerschool2020
theflyingrahul
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/sebastianvromero/qecc_shor9q
sebastianvromero
import random import numpy as np from qiskit import QuantumCircuit, AncillaRegister, QuantumRegister, execute, Aer def normalize_state(a = 1, b = 0): norm = np.sqrt(a * np.conjugate(a) + b * np.conjugate(b)) return [a / norm, b / norm] def modulus_and_phase(a): return (np.absolute(a), np.angle(a)) def int_to_binary(value, n_bits = 17, reverse = True): value = int(value) if value != 0: bound = int(np.ceil(np.log2(value))) if n_bits < bound: n_bits = bound binary_format = '{0:0' + str(n_bits) + 'b}' binary = binary_format.format(value) if reverse: return binary[ : : -1] else: return binary def binary_to_int(value, reverse = True): if reverse: value = value[ : : -1] return int(value, 2) def get_state(circuit, precision = 10, fancy_print = False): # Let's simulate our circuit in order to get the final state vector! svsim = Aer.get_backend('statevector_simulator') # Do the simulation, return the result and get the state vector result = execute(circuit, svsim).result().get_statevector() if int(precision) < 8: precision = 8 result = result.round(precision) # Returns non-zero values state_indices = result.nonzero()[0] states = np.empty(0) for index in state_indices: binary_state = int_to_binary(index) states = np.append(states , [result[index], binary_state]) if fancy_print: string = '' for index in range(0, len(states), 2): coef, bstate = states[index], states[index + 1] string = string + f'{coef} |{bstate}> ' print(string) return states def random_noise(gate_label = 'Noise', reveal_error = False): # Our circuit has 9-qubits gate_circuit = QuantumCircuit(9, name = gate_label) # Define randomly the number of errors to apply from 0 (no errors) up to 2 number_of_errors = random.choice(range(3)) types_of_errors = ['X', 'Y', 'Z'] qubits_wo_errors = list(range(9)) qpacks_wo_errors = list(range(9)) global gate_reveal_label gate_reveal_label = 'I' * 9 def str_assignment(string, index, char): string = list(string) string[index] = str(char) string = ''.join(string) return string while number_of_errors > 0: qubit_assigned = random.choice(qpacks_wo_errors) type_error = random.choice(types_of_errors) number_of_errors -= 1 qubits_wo_errors.remove(qubit_assigned) gate_reveal_label = str_assignment(gate_reveal_label, qubit_assigned, type_error) # Remove 3-qubits packs after assign error to qubit in it if qubit_assigned in list(range(3)): qpacks_wo_errors = [elem for elem in qpacks_wo_errors if elem > 2] elif qubit_assigned in list(range(3, 6)): qpacks_wo_errors = [elem for elem in qpacks_wo_errors if (elem < 3 or elem > 5)] else: qpacks_wo_errors = [elem for elem in qpacks_wo_errors if elem < 6] # Can't repeat quantum error gate applied if type_error == 'Y': gate_circuit.y(qubit_assigned) break elif type_error == 'X': gate_circuit.x(qubit_assigned) try: # Maybe we don't have this errors to remove types_of_errors.remove('X') types_of_errors.remove('Y') except: pass else: gate_circuit.z(qubit_assigned) try: # Maybe we don't have this errors to remove types_of_errors.remove('Y') types_of_errors.remove('Z') except: pass # Assign identity gate for the rest of qubits for qubit in qubits_wo_errors: gate_circuit.i(qubit) gate = gate_circuit.to_gate() if reveal_error: gate.label = 'Noise:\n' + gate_reveal_label return gate def check_error_to_ancilla(state, error = None): if error is None: error = gate_reveal_label binary = state[1] error_types = ['X0', 'X1', 'X2', 'Z '] state_ancillas = [binary[3 : 5], binary[8 : 10], binary[13 : 15], binary[-2 : ]] ancillas = {} for key, anc in zip(error_types, state_ancillas): ancillas[key] = anc first_pack = list(range(0, 7, 3)) second_pack = list(range(1, 8, 3)) third_pack = list(range(2, 9, 3)) def ancilla_label(value): if value == 0: return '10' elif value == 1: return '11' else: return '01' expected = {} for key in error_types: expected[key] = '00' for qubit, gate in enumerate(list(error)): n_pack = qubit // 3 key = 'X' + str(n_pack) n_xerr = qubit % 3 if gate == 'I': continue elif gate == 'X': if qubit in first_pack: expected[key] = ancilla_label(n_xerr) elif qubit in second_pack: expected[key] = ancilla_label(n_xerr) else: expected[key] = ancilla_label(n_xerr) elif gate == 'Z': expected['Z '] = ancilla_label(n_pack) else: expected['Z '] = ancilla_label(n_pack) if qubit in first_pack: expected[key] = ancilla_label(n_xerr) elif qubit in second_pack: expected[key] = ancilla_label(n_xerr) else: expected[key] = ancilla_label(n_xerr) print('Error Anc. expected Anc. state Equal?\n' + '-' * 40) for key in error_types: print(f' {key} {expected[key]} {ancillas[key]} {expected[key] == ancillas[key]}') def cnotnot(gate_label = 'CNOTNOT'): gate_circuit = QuantumCircuit(3, name = gate_label) gate_circuit.cnot(0, 1) gate_circuit.cnot(0, 2) gate = gate_circuit.to_gate() return gate def czz(gate_label = 'CZZ'): gate_circuit = QuantumCircuit(3, name = gate_label) gate_circuit.cz(0, 1) gate_circuit.cz(0, 2) gate = gate_circuit.to_gate() return gate def invccnot(gate_label = 'invCCNOT'): gate_circuit = QuantumCircuit(3, name = gate_label) gate_circuit.x(0) gate_circuit.ccx(0, 1, 2) gate_circuit.x(0) gate = gate_circuit.to_gate() return gate def c6x(gate_label = 'C6X'): gate_circuit = QuantumCircuit(7, name = gate_label) for index in range(1, 7): gate_circuit.cnot(0, index) gate = gate_circuit.to_gate() return gate def invccz(gate_label = 'invCCZ'): gate_circuit = QuantumCircuit(3, name = gate_label) gate_circuit.x(0) gate_circuit.h(2) gate_circuit.ccx(0, 1, 2) gate_circuit.h(2) gate_circuit.x(0) gate = gate_circuit.to_gate() return gate def ccz(gate_label = 'CCZ'): gate_circuit = QuantumCircuit(3, name = gate_label) gate_circuit.h(2) gate_circuit.ccx(0, 1, 2) gate_circuit.h(2) gate = gate_circuit.to_gate() return gate
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
import numpy as np N = 10**7; d = np.arange(2,N+1,1); dl = np.zeros(len(d)); nv = np.zeros(len(d)) n = 1 for j in range(2,len(d)): nv[j] = n dl[j] = 2**n if d[j] >= dl[j]: n += 1 from matplotlib import pyplot as plt plt.plot(d,d, label=r'$d$') plt.plot(d,dl, label=r'$dl$') plt.xlabel(r'$d$'); plt.ylabel(r'$dl$'); plt.show() plt.plot(d,nv, label=r'$n$') plt.xlabel(r'$d$'); plt.ylabel(r'$n$'); plt.show()
https://github.com/ColibrITD-SAS/mpqp
ColibrITD-SAS
from mpqp.execution.vqa import * from mpqp import QCircuit from mpqp.gates import * from sympy import symbols x, y, z = symbols("x y z") circuit = QCircuit([Rx(x, 0), Ry(y, 1), Rz(z,0), Rz(z,1), CNOT(0,1)]) print(circuit) from mpqp.measures import Observable, ExpectationMeasure from mpqp.execution import IBMDevice, run import numpy as np matrix = np.array([[4, 2, 3, 8], [2, -3, 1, 0], [3, 1, -1, 5], [8, 0, 5, 2]]) hamiltonian = Observable(matrix) circuit.add(ExpectationMeasure([0, 1], observable=hamiltonian, shots=0)) minimize(circuit, Optimizer.COBYLA, IBMDevice.AER_SIMULATOR, optimizer_options={"maxiter":200}) circuit2 = circuit.without_measurements() def cost_function(params): r1 = run(circuit2, IBMDevice.AER_SIMULATOR_STATEVECTOR, {x: params[0], y: params[1], z: params[2]}) r2 = run(circuit, IBMDevice.AER_SIMULATOR, {x: params[0], y: params[1], z: params[2]}) return abs(r1.amplitudes[0]) - np.sqrt(r2.expectation_value**3) minimize(cost_function, Optimizer.COBYLA, nb_params=3, optimizer_options={"maxiter":200})
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 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 TrotterQRTE.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np from scipy.linalg import expm from numpy.testing import assert_raises from qiskit_algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE from qiskit.primitives import Estimator from qiskit import QuantumCircuit from qiskit.circuit.library import ZGate from qiskit.quantum_info import Statevector, Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.opflow import PauliSumOp, X, MatrixOp from qiskit.synthesis import SuzukiTrotter, QDrift @ddt class TestTrotterQRTE(QiskitAlgorithmsTestCase): """TrotterQRTE tests.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed @data( ( None, Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j]), ), ( SuzukiTrotter(), Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j]), ), ) @unpack def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): """Test for default TrotterQRTE on a single qubit.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) trotter_qrte = TrotterQRTE(product_formula=product_formula) evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result_state_circuit).data, expected_state.data ) @data((SparsePauliOp(["X", "Z"]), None), (SparsePauliOp(["X", "Z"]), Parameter("t"))) @unpack def test_trotter_qrte_trotter(self, operator, t_param): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" if not t_param is None: operator = SparsePauliOp(operator.paulis, np.array([t_param, 1])) # LieTrotter with 1 rep aux_ops = [Pauli("X"), Pauli("Y")] initial_state = QuantumCircuit(1) time = 3 num_timesteps = 2 evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param ) estimator = Estimator() expected_psi, expected_observables_result = self._get_expected_trotter_qrte( operator, time, num_timesteps, initial_state, aux_ops, t_param, ) expected_evolved_state = Statevector(expected_psi) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator, num_timesteps=num_timesteps) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_evolved_state.data, ) aux_ops_result = evolution_result.aux_ops_evaluated expected_aux_ops_result = [ (expected_observables_result[-1][0], {"variance": 0, "shots": 0}), (expected_observables_result[-1][1], {"variance": 0, "shots": 0}), ] means = [element[0] for element in aux_ops_result] expected_means = [element[0] for element in expected_aux_ops_result] np.testing.assert_array_almost_equal(means, expected_means) vars_and_shots = [element[1] for element in aux_ops_result] expected_vars_and_shots = [element[1] for element in expected_aux_ops_result] observables_result = evolution_result.observables expected_observables_result = [ [(o, {"variance": 0, "shots": 0}) for o in eor] for eor in expected_observables_result ] means = [sub_element[0] for element in observables_result for sub_element in element] expected_means = [ sub_element[0] for element in expected_observables_result for sub_element in element ] np.testing.assert_array_almost_equal(means, expected_means) for computed, expected in zip(vars_and_shots, expected_vars_and_shots): self.assertAlmostEqual(computed.pop("variance", 0), expected["variance"], 2) self.assertEqual(computed.pop("shots", 0), expected["shots"]) @data( ( PauliSumOp(SparsePauliOp([Pauli("XY"), Pauli("YX")])), Statevector([-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j]), ), ( PauliSumOp(SparsePauliOp([Pauli("ZZ"), Pauli("ZI"), Pauli("IZ")])), Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]), ), ( Pauli("YY"), Statevector([0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j]), ), ) @unpack def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" # LieTrotter with 1 rep initial_state = QuantumCircuit(2) evolution_problem = TimeEvolutionProblem(operator, 1, initial_state) trotter_qrte = TrotterQRTE() evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data ) @data( (QuantumCircuit(1), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j])), ( QuantumCircuit(1).compose(ZGate(), [0]), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j]), ), ) @unpack def test_trotter_qrte_qdrift(self, initial_state, expected_state): """Test for TrotterQRTE with QDrift.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data, ) @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) @unpack def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict): """Test TrotterQRTE with raising errors for parameters.""" with self.assertWarns(DeprecationWarning): operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, None, None, t_param, param_value_dict) @data(([Pauli("X"), Pauli("Y")], None)) @unpack def test_trotter_qrte_trotter_aux_ops_errors(self, aux_ops, estimator): """Test TrotterQRTE with raising errors.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, aux_ops, estimator, None, None) @data( (X, QuantumCircuit(1)), (MatrixOp([[1, 1], [0, 1]]), QuantumCircuit(1)), (PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(SparsePauliOp([Pauli("Z")])), None), ( SparsePauliOp([Pauli("X"), Pauli("Z")], np.array([Parameter("a"), Parameter("b")])), QuantumCircuit(1), ), ) @unpack def test_trotter_qrte_trotter_hamiltonian_errors(self, operator, initial_state): """Test TrotterQRTE with raising errors for evolution problem content.""" self._run_error_test(initial_state, operator, None, None, None, None) @staticmethod def _run_error_test(initial_state, operator, aux_ops, estimator, t_param, param_value_dict): time = 1 algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator) with assert_raises(ValueError): evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param, param_value_map=param_value_dict, ) _ = trotter_qrte.evolve(evolution_problem) @staticmethod def _get_expected_trotter_qrte(operator, time, num_timesteps, init_state, observables, t_param): """Compute reference values for Trotter evolution via exact matrix exponentiation.""" dt = time / num_timesteps observables = [obs.to_matrix() for obs in observables] psi = Statevector(init_state).data if t_param is None: ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in operator.to_list()] observable_results = [] observable_results.append([np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables]) for n in range(num_timesteps): if t_param is not None: time_value = (n + 1) * dt bound = operator.assign_parameters([time_value]) ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in bound.to_list()] for op in ops: psi = expm(-1j * op * dt).dot(psi) observable_results.append( [np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables] ) return psi, observable_results if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')