repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/drobiu/quantum-project
drobiu
from math import pi from qiskit import * from qiskit.circuit.library.standard_gates import PhaseGate from qiskit.circuit.library.basis_change import QFT def add(circuit, a, b, control=None, apply_QFT=True, amount=1): # Function adds a to b Original add function build by # https://github.com/TimVroomans/Quantum-Mastermind/blob/master/src/mastermind/arithmetic/dradder.py number_a = len(a) number_b = len(b) num = number_b + number_a if number_a > number_b: raise ValueError("Amount of registers in b must be larger than a") # QFT(optional) if apply_QFT: circuit = circuit.compose(QFT(num_qubits=number_b, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=True, name='qft'), [*b]) # Actual add loop for i in range(number_a): for j in range(number_b - i): if control: p_gate = PhaseGate(amount * pi / 2 ** (number_b - i - j - 1)).control(len(control) + 1) circuit.append(p_gate, [*control, a[i], b[j]]) else: circuit.cp(amount * pi / 2 ** (number_b - i - j - 1), a[i], b[j]) # Inverse QFT (optional) if apply_QFT: circuit = circuit.compose(QFT(num_qubits=number_b, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=True, name='iqft'), [*b]) return circuit # def c_add(circuit, a, b, control, apply_QFT=True, amount=1): # if __name__ == "__main__": # test a = QuantumRegister(3) b = QuantumRegister(5) qc = QuantumCircuit(a, b) test = add(qc, a, b) print(test.draw(output='text'))
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import * from qiskit.visualization import plot_histogram measure_z = QuantumCircuit(1,1) measure_z.measure(0,0) measure_z.draw(output='mpl') measure_x = QuantumCircuit(1,1) measure_x.h(0) measure_x.measure(0,0) measure_x.draw(output='mpl') qc_0 = QuantumCircuit(1) qc_0.draw(output='mpl') qc = qc_0 + measure_z print('Results for z measurement:') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc = qc_0 + measure_x print('Results for x measurement:') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc_plus = QuantumCircuit(1) qc_plus.h(0) qc_plus.draw(output='mpl') qc = qc_plus + measure_z qc.draw() print('Results for z measurement:') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc = qc_plus + measure_x print('Results for x measurement:') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc_y = QuantumCircuit(1) qc_y.ry( -3.14159/4,0) qc_y.draw(output='mpl') qc = qc_y + measure_z print('Results for z measurement:') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc = qc_y + measure_x print('\nResults for x measurement:') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc_hardy = QuantumCircuit(2) qc_hardy.ry(1.911,1) qc_hardy.cx(1,0) qc_hardy.ry(0.785,0) qc_hardy.cx(1,0) qc_hardy.ry(2.356,0) qc_hardy.draw(output='mpl') measurements = QuantumCircuit(2,2) # z measurement on both qubits measurements.measure(0,0) measurements.measure(1,1) qc = qc_hardy + measurements print('\nResults for two z measurements:') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) measurements = QuantumCircuit(2,2) # x measurement on qubit 0 measurements.h(0) measurements.measure(0,0) # z measurement on qubit 1 measurements.measure(1,1) qc = qc_hardy + measurements print('\nResults for two x measurement on qubit 0 and z measurement on qubit 1:') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) measurements = QuantumCircuit(2,2) measurements.h(0) measurements.measure(0,0) measurements.h(1) measurements.measure(1,1) qc = qc_hardy + measurements print('\nResults for two x measurement on both qubits:') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts)
https://github.com/lynnlangit/learning-quantum
lynnlangit
import numpy as np v = np.array([1,2]) A = np.array([[2,3], [5,2]]) t = A@v print (t) import numpy as np v = np.array([1,2]) A = np.array([[2,3], [5,2], [1,1]]) t = A@v print (t) import numpy as np v = np.array([1,2]) A = np.array([[1,2], [2,1]]) t = A@v print (t) import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,0]) A = np.array([[2,0], [0,2]]) t = A@v print (t) # Plot v and t vecs = np.array([t,v]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['blue'], scale=10) plt.quiver(*origin, *t, color=['orange'], scale=10) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,0]) A = np.array([[0,-1], [1,0]]) t = A@v print (t) # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t, color=['blue'], scale=10) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,0]) A = np.array([[2,1], [1,2]]) t = A@v print (t) # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t, color=['blue'], scale=10) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,1]) A = np.array([[5,2], [3,1]]) b = np.array([-2,-6]) t = A@v + b print (t) # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=15) plt.quiver(*origin, *t, color=['blue'], scale=15) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,0]) A = np.array([[2,0], [0,2]]) t1 = A@v print (t1) t2 = 2*v print (t2) fig = plt.figure() a=fig.add_subplot(1,1,1) # Plot v and t1 vecs = np.array([t1,v]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t1, color=['blue'], scale=10) plt.show() a=fig.add_subplot(1,2,1) # Plot v and t2 vecs = np.array([t2,v]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t2, color=['blue'], scale=10) plt.show() import numpy as np A = np.array([[2,0], [0,3]]) eVals, eVecs = np.linalg.eig(A) print(eVals) print(eVecs) vec1 = eVecs[:,0] lam1 = eVals[0] print('Matrix A:') print(A) print('-------') print('lam1: ' + str(lam1)) print ('v1: ' + str(vec1)) print ('Av1: ' + str(A@vec1)) print ('lam1 x v1: ' + str(lam1*vec1)) print('-------') vec2 = eVecs[:,1] lam2 = eVals[1] print('lam2: ' + str(lam2)) print ('v2: ' + str(vec2)) print ('Av2: ' + str(A@vec2)) print ('lam2 x v2: ' + str(lam2*vec2)) t1 = lam1*vec1 print (t1) t2 = lam2*vec2 print (t2) fig = plt.figure() a=fig.add_subplot(1,1,1) # Plot v and t1 vecs = np.array([t1,vec1]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t1, color=['blue'], scale=10) plt.show() a=fig.add_subplot(1,2,1) # Plot v and t2 vecs = np.array([t2,vec2]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t2, color=['blue'], scale=10) plt.show() import numpy as np A = np.array([[2,0], [0,2]]) eVals, eVecs = np.linalg.eig(A) print(eVals) print(eVecs) vec1 = eVecs[:,0] lam1 = eVals[0] print('Matrix A:') print(A) print('-------') print('lam1: ' + str(lam1)) print ('v1: ' + str(vec1)) print ('Av1: ' + str(A@vec1)) print ('lam1 x v1: ' + str(lam1*vec1)) print('-------') vec2 = eVecs[:,1] lam2 = eVals[1] print('lam2: ' + str(lam2)) print ('v2: ' + str(vec2)) print ('Av2: ' + str(A@vec2)) print ('lam2 x v2: ' + str(lam2*vec2)) # Plot the resulting vectors t1 = lam1*vec1 t2 = lam2*vec2 fig = plt.figure() a=fig.add_subplot(1,1,1) # Plot v and t1 vecs = np.array([t1,vec1]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t1, color=['blue'], scale=10) plt.show() a=fig.add_subplot(1,2,1) # Plot v and t2 vecs = np.array([t2,vec2]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t2, color=['blue'], scale=10) plt.show() import numpy as np A = np.array([[2,1], [1,2]]) eVals, eVecs = np.linalg.eig(A) print(eVals) print(eVecs) vec1 = eVecs[:,0] lam1 = eVals[0] print('Matrix A:') print(A) print('-------') print('lam1: ' + str(lam1)) print ('v1: ' + str(vec1)) print ('Av1: ' + str(A@vec1)) print ('lam1 x v1: ' + str(lam1*vec1)) print('-------') vec2 = eVecs[:,1] lam2 = eVals[1] print('lam2: ' + str(lam2)) print ('v2: ' + str(vec2)) print ('Av2: ' + str(A@vec2)) print ('lam2 x v2: ' + str(lam2*vec2)) # Plot the results t1 = lam1*vec1 t2 = lam2*vec2 fig = plt.figure() a=fig.add_subplot(1,1,1) # Plot v and t1 vecs = np.array([t1,vec1]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t1, color=['blue'], scale=10) plt.show() a=fig.add_subplot(1,2,1) # Plot v and t2 vecs = np.array([t2,vec2]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t2, color=['blue'], scale=10) plt.show() import numpy as np A = np.array([[3,2], [1,0]]) l, Q = np.linalg.eig(A) print(Q) L = np.diag(l) print (L) Qinv = np.linalg.inv(Q) print(Qinv) v = np.array([1,3]) t = A@v print(t) # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t, color=['blue'], scale=10) plt.show() import math import numpy as np import matplotlib.pyplot as plt %matplotlib inline t = (Q@(L@(Qinv)))@v # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t, color=['blue'], scale=10) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline t1 = Qinv@v t2 = L@t1 t3 = Q@t2 # Plot the transformations vecs = np.array([v,t1, t2, t3]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=20) plt.quiver(*origin, *t1, color=['blue'], scale=20) plt.quiver(*origin, *t2, color=['red'], scale=20) plt.quiver(*origin, *t3, color=['magenta'], scale=20) plt.show() import numpy as np A = np.array([[1,2], [4,3]]) l, Q = np.linalg.eig(A) L = np.diag(l) print(L) B = np.array([[3,-3,6], [2,-2,4], [1,-1,2]]) lb, Qb = np.linalg.eig(B) Lb = np.diag(lb) print(Lb) import numpy as np A = np.array([[1,2], [4,3]]) l, Q = np.linalg.eig(A) L = np.diag(l) print(Q) Linv = np.linalg.inv(L) Qinv = np.linalg.inv(Q) print(Linv) print(Qinv) Ainv = (Q@(Linv@(Qinv))) print(Ainv) print(np.linalg.inv(A))
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 01.06.2023 @ 22:19:42 Component: Swap Gate Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with two qubits circuit = QuantumCircuit(2) # Apply the SWAP gate circuit.swap(0, 1) # Measure the qubits circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/C2QA/bosonic-qiskit
C2QA
from pathlib import Path import numpy import pytest import qiskit import c2qa def __build_subcircuit(): # Define Hamiltonian parameters omega_R = 2 omega_Q = 5 chi = 0.1 # Set number of qubits per qumode num_qubits_per_qumode = 3 # Choose alpha for coherent state alpha = 1 # Choose total animation time total_time = 1*2*numpy.pi/omega_R # Create new circuit qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(1) U_JC = c2qa.CVCircuit(qmr,qbr) # Append U_R U_JC.cv_r(-omega_R*total_time, qmr[0]) # Append U_Q U_JC.rz(omega_Q*total_time,qbr[0]) # Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript U_JC.cv_c_r(-chi*total_time/2, qmr[0], qbr[0]) # Compile this circuit into a single parameterized gate U_JC = U_JC.to_gate(label='U_JC') # Instantiate the circuit and initialize the qubit to the '0' state. circuit_0 = c2qa.CVCircuit(qmr,qbr) circuit_0.initialize([1,0], qbr) # Squeeze so we can visually see rotation circuit_0.cv_sq(0.5, qmr[0]) # Now initialize the qumode in a coherent state # cutoff = 2**num_qubits_per_qumode # coeffs = [numpy.exp(-numpy.abs(alpha)**2/2)*alpha**n/(numpy.sqrt(numpy.math.factorial(n))) for n in range(0,cutoff)] # circuit_0.cv_initialize(coeffs,qmr[0]) # Append time evolution unitary circuit_0.append(U_JC,qmr[0] + [qbr[0]]) # circuit_0.assign_parameters({dt : total_time}) # dt = total_time # # Append U_R # circuit_0.cv_r(-omega_R*dt,qmr[0]) # # Append U_Q # circuit_0.rz(omega_Q*dt,qbr[0]) # # Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript # circuit_0.cv_c_r(-chi*dt/2,qmr[0],qbr[0]) # Compile this circuit into a single parameterized gate # U_JC = U_JC.to_gate(label='U_JC') # # Now repeat the above steps for a qubit initialized to the '1' state: # circuit_1 = c2qa.CVCircuit(qmr,qbr) # circuit_1.initialize([0,1], qbr) # circuit_1.cv_d(alpha,qmr[0]) # circuit_1.append(U_JC,qmr[0] + [qbr[0]]) # circuit_1 = circuit_1.assign_parameters({dt : total_time}) return circuit_0 def test_animate_subcircuit_one_gate(capsys): """ Test animating a circuit with a composite gate built from another circuit. Composite gate borrowed from Jaynes-Cummings model tutorial """ with capsys.disabled(): circuit = __build_subcircuit() # Animate wigner function of each circuit c2qa.animate.animate_wigner(circuit,file="tests/composite_gate.gif", animation_segments = 20) def test_animate_subcircuit_sequential(capsys): """ Test animating a circuit with a composite gate built from another circuit. Composite gate borrowed from Jaynes-Cummings model tutorial """ with capsys.disabled(): circuit = __build_subcircuit() # Animate wigner function of each circuit c2qa.animate.animate_wigner(circuit,file="tests/sequential_subcircuit.gif", animation_segments = 20, sequential_subcircuit = True) def test_animate_parameterized(capsys): with capsys.disabled(): a = qiskit.circuit.Parameter("𝛼") qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=4) qbr = qiskit.QuantumRegister(1) cbr = qiskit.ClassicalRegister(1) minimal_circuit = c2qa.CVCircuit(qmr, qbr, cbr) minimal_circuit.h(qbr[0]) minimal_circuit.cv_c_d(1j * a, qmr[0], qbr[0]) bound_circuit = minimal_circuit.assign_parameters({a: 2}) wigner_filename = "tests/animate_parameterized.apng" c2qa.animate.animate_wigner( bound_circuit, qubit=qbr[0], cbit=cbr[0], file=wigner_filename, axes_min=-8, axes_max=8, animation_segments=5, processes=1, shots=25, ) assert Path(wigner_filename).is_file() def test_animate_gif(capsys): with capsys.disabled(): __animate_with_cbit("tests/displacement.gif") def test_animate_apng(capsys): with capsys.disabled(): __animate_with_cbit("tests/displacement.apng") def __animate_with_cbit(filename: str): qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=4) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) dist = 3 circuit.initialize([1, 0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) c2qa.animate.animate_wigner( circuit, qubit=qr[0], cbit=cr[0], file=filename, axes_min=-8, axes_max=8, animation_segments=5, processes=1, shots=25, ) assert Path(filename).is_file() def __animate_without_cbit(filename: str, trace: bool = False): qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=4) qr = qiskit.QuantumRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr) dist = 3 circuit.initialize([1, 0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) c2qa.animate.animate_wigner( circuit, qubit=qr[0], file=filename, axes_min=-8, axes_max=8, animation_segments=5, processes=1, shots=25, trace=trace, ) assert Path(filename).is_file() def test_animate_with_trace(capsys): with capsys.disabled(): __animate_without_cbit("tests/animate_with_trace.gif", True) def test_animate_without_trace(capsys): with capsys.disabled(): __animate_without_cbit("tests/animate_without_trace.gif", False) @pytest.mark.skip(reason="GitHub actions build environments do not have ffmpeg") def test_calibration_animate_mp4(capsys): with capsys.disabled(): qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=6) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) dist = 3 circuit.initialize([1, 0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) circuit.cv_d(1j * dist, qmr[0]) circuit.cv_c_d(-dist, qmr[0], qr[0]) circuit.cv_d(-1j * dist, qmr[0]) c2qa.animate.animate_wigner( circuit, qubit=qr[0], cbit=cr[0], file="tests/displacement.mp4", axes_min=-8, axes_max=8, animation_segments=48, shots=128, )
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'parity', 'two_qubit_reduction': True, 'freeze_core': True, 'orbital_reduction': [-3, -2]}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'UCCSD'}, 'initial_state': {'name': 'HartreeFock'} } molecule = 'H .0 .0 -{0}; Li .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] pts = [x * 0.1 for x in range(6, 20)] pts += [x * 0.25 for x in range(8, 16)] pts += [4.0] energies = np.empty([len(algorithms), len(pts)]) hf_energies = np.empty(len(pts)) distances = np.empty(len(pts)) dipoles = np.empty([len(algorithms), len(pts)]) eval_counts = np.empty(len(pts)) print('Processing step __', end='') for i, d in enumerate(pts): print('\b\b{:2d}'.format(i), end='', flush=True) qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] hf_energies[i] = result['hf_energy'] dipoles[j][i] = result['total_dipole_moment'] / 0.393430307 if algorithms[j] == 'VQE': eval_counts[i] = result['algorithm_retvals']['eval_count'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print('VQE num evaluations:', eval_counts) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('LiH Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left') for j in reversed(range(len(algorithms))): pylab.plot(distances, dipoles[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Moment in debye') pylab.title('LiH Dipole Moment') pylab.legend(loc='upper right') pylab.plot(distances, eval_counts, '-o', color=[0.8500, 0.3250, 0.0980], label='VQE') pylab.xlabel('Interatomic distance') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='upper left')
https://github.com/wyqian1027/Qiskit-Fall-Fest-USC-2022
wyqian1027
import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_bloch_multivector, array_to_latex from grader import * language(True) phi_plus = QuantumCircuit(2) phi_plus.h(0) phi_plus.cnot(0, 1) phi_plus.draw('mpl') # Simulamos para ver su resultado backend = Aer.get_backend('statevector_simulator') result = execute(phi_plus, backend).result().get_statevector() array_to_latex(result) phi_minus = QuantumCircuit(2) ##### ================================== # Escribe tu solución aquí. ##### ================================== phi_minus.draw('mpl') # Esta celda te dirá si lo que has hecho da el resultado correcto. # Tómalo como un indicador, los tests que hace no consideran todas las opciones posibles. # Si crees que tu respuesta es (in)correcta y el grader dice algo diferente, simplemente pregúntame. # No intentes hacer trampas modificando el código del corrector :) ex1_grader(phi_minus) psi_plus = QuantumCircuit(2) ##### ================================== # Escribe tu solución aquí. ##### ================================== psi_plus.draw('mpl') ex2_grader(psi_plus) psi_minus = QuantumCircuit(2) ##### ================================== # Escribe tu solución aquí. ##### ================================== psi_minus.draw('mpl') ex3_grader(psi_minus) GHZ = QuantumCircuit(3) ##### ================================== # Escribe tu solución aquí. ##### ================================== GHZ.draw('mpl') ex4_grader(GHZ) Even = QuantumCircuit(3) ##### ================================== # Escribe tu solución aquí. ##### ================================== Even.draw('mpl') ex5_grader(Even) Odd = QuantumCircuit(3) ##### ================================== # Escribe tu solución aquí. ##### ================================== Odd.draw('mpl') ex6_grader(Odd) def measure_z_axis(qc, qubit, cbit): #Las medidas deben guardarse en bits clásicos. qc.measure(qubit, cbit) def measure_x_axis(qc, qubit, cbit): ##### ================================== # Escribe tu solución aquí. ##### ================================== ex7_grader(measure_x_axis) def expectation_value_single_qubit(qc, nshots=8092): # Ejecuta el circuito que ya está rotado a la base correspondiente backend_shots = Aer.get_backend('qasm_simulator') counts = execute(qc, backend_shots, shots=nshots).result().get_counts() #Counts is a dictionary that contains the number of zeros and the number of ones measured # Esto es simplemente para evitar problemas. En caso de que falte una key en el diccionario la añade if '1' not in counts.keys(): counts['1'] = 0 if '0' not in counts.keys(): counts['0'] = 0 # Obten el numero de veces que se ha medido 0 y 1 n_zeros = counts['0'] n_ones = counts['1'] # Calcula las probabilidades p_0 = n_zeros/nshots p_1 = n_ones/nshots # O 1-p_0 expectation_value = 1*p_0+(-1)*p_1 return expectation_value # Mide <Z> sobre un estado que te guste qc_z = QuantumCircuit(1,1) measure_z_axis(qc_z, 0, 0) print('<Z>=', expectation_value_single_qubit(qc_z)) qc_z.draw('mpl') # Mide <X> sobre un estado que te guste qc_x = QuantumCircuit(1,1) measure_x_axis(qc_x, 0, 0) print('<X>=', expectation_value_single_qubit(qc_x)) qc_x.draw('mpl') ##### ================================== # Escribe tu solución aquí. # Primero crea un estado de Bell # Para cada uno de los operadores que queremos medir, (ZZ, ZX, XZ and XX) crea un nuevo circuito (quizás usando qc.copy()) # que mida en ese eje. chsh_circuits = [] ##### ================================== chsh_circuits[0].draw('mpl') chsh_circuits[1].draw('mpl') chsh_circuits[2].draw('mpl') chsh_circuits[3].draw('mpl') # Hacer tests aquí que no revelasen la respuesta era complicado, así que no hay ayuda :( # Podemos correr todos los circuitos a la vez y luego postprocesar los datos nshots = 8092 # Cuantos más shots, menos error backend_shots = Aer.get_backend('qasm_simulator') counts_list = execute(chsh_circuits, backend_shots, shots=nshots).result().get_counts() counts_list ##### ================================== # Escribe tu solución aquí. # Para cada uno de los circuitos, coge las counts que tengas para ese circuito, calcula la probabilidad #de cada estado y combinalas teniendo mucho cuidado con qué signo lleva cada término # Puede que quieras inspirarte en la función expectation_value_single_qubit # Si estás muy perdido y no sabes cómo resolver esto, puedes preguntar. ##### ================================== # Si no sabes si tu respuesta es correcta, puedes calcular los resultados a mano # (de hecho seguramente sea más fácil que calcularlo así) y comprobar si tu código está funcionando ##### ================================== # Escribe tu solución aquí. exp_AB = exp_Ab = exp_aB = exp_ab = CHSH = ##### ================================== print('Tu resultado es <CHSH>=', CHSH) print('El resultado correcto es <CHSH>=', 2*np.sqrt(2)) ##### ================================== # Escribe tu solución aquí. Can_entanglement_be_teleported = #Escribe True or False :D ##### ================================== ##### ================================== # Escribe tu solución aquí. Where_did_the_bell_pair_go = 'Escribe aquí' ##### ================================== ##### ================================== # Escribe tu solución aquí. ##### ================================== import qiskit.tools.jupyter %qiskit_version_table
https://github.com/yonahirakawa/qiskit-iniciantes
yonahirakawa
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer q = QuantumRegister(2,'q') c = ClassicalRegister(2,'c') def primeiroEstadoBell(): circuito = QuantumCircuit(q,c) circuito.h(q[0]) circuito.cx(q[0],q[1]) circuito.measure(q,c) display(circuito.draw(output='mpl')) job = execute(circuito, Aer.get_backend('qasm_simulator'), shots=8192) counts = job.result().get_counts(circuito) print(counts) def segundoEstadoBell(): circuito = QuantumCircuit(q,c) circuito.x(q[0]) circuito.h(q[0]) circuito.cx(q[0],q[1]) circuito.measure(q,c) display(circuito.draw(output='mpl')) job = execute(circuito, Aer.get_backend('qasm_simulator'), shots=8192) counts = job.result().get_counts(circuito) print(counts) def terceiroEstadoBell(): circuito = QuantumCircuit(q,c) circuito.x(q[1]) circuito.h(q[0]) circuito.cx(q[0],q[1]) circuito.measure(q,c) display(circuito.draw(output='mpl')) job = execute(circuito, Aer.get_backend('qasm_simulator'), shots=8192) counts = job.result().get_counts(circuito) print(counts) def quartoEstadoBell(): circuito = QuantumCircuit(q,c) circuito.x(q[1]) circuito.h(q[0]) circuito.z(q[0]) circuito.z(q[1]) circuito.cx(q[0],q[1]) circuito.measure(q,c) display(circuito.draw(output='mpl')) job = execute(circuito, Aer.get_backend('qasm_simulator'), shots=8192) counts = job.result().get_counts(circuito) print(counts) print("Criando primeiro estado de Bell:\n") primeiroEstadoBell() print("\nCriando segundo estado de Bell:\n") segundoEstadoBell() print("\nCriando terceiro estado de Bell:\n") terceiroEstadoBell() print("\nCriando quarto estado de Bell:\n") quartoEstadoBell()
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 05.06.2023 @ 20:25:12 Component: Controlled-Z Gate Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with two qubits circuit = QuantumCircuit(2) # Apply the Controlled-Z gate with control qubit 0 and target qubit 1 circuit.cz(0, 1) # Measure the qubits circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """Functions to generate the basic approximations of single qubit gates for Solovay-Kitaev.""" from __future__ import annotations import warnings import collections import numpy as np import qiskit.circuit.library.standard_gates as gates from qiskit.circuit import Gate from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.utils import optionals from .gate_sequence import GateSequence Node = collections.namedtuple("Node", ("labels", "sequence", "children")) _1q_inverses = { "i": "i", "x": "x", "y": "y", "z": "z", "h": "h", "t": "tdg", "tdg": "t", "s": "sdg", "sdg": "s", } _1q_gates = { "i": gates.IGate(), "x": gates.XGate(), "y": gates.YGate(), "z": gates.ZGate(), "h": gates.HGate(), "t": gates.TGate(), "tdg": gates.TdgGate(), "s": gates.SGate(), "sdg": gates.SdgGate(), "sx": gates.SXGate(), "sxdg": gates.SXdgGate(), } def _check_candidate(candidate, existing_sequences, tol=1e-10): if optionals.HAS_SKLEARN: return _check_candidate_kdtree(candidate, existing_sequences, tol) warnings.warn( "The SolovayKitaev algorithm relies on scikit-learn's KDTree for a " "fast search over the basis approximations. Without this, we fallback onto a " "greedy search with is significantly slower. We highly suggest to install " "scikit-learn to use this feature.", category=RuntimeWarning, ) return _check_candidate_greedy(candidate, existing_sequences, tol) def _check_candidate_greedy(candidate, existing_sequences, tol=1e-10): # do a quick, string-based check if the same sequence already exists if any(candidate.name == existing.name for existing in existing_sequences): return False for existing in existing_sequences: if matrix_equal(existing.product_su2, candidate.product_su2, ignore_phase=True, atol=tol): # is the new sequence less or more efficient? return len(candidate.gates) < len(existing.gates) return True @optionals.HAS_SKLEARN.require_in_call def _check_candidate_kdtree(candidate, existing_sequences, tol=1e-10): """Check if there's a candidate implementing the same matrix up to ``tol``. This uses a k-d tree search and is much faster than the greedy, list-based search. """ from sklearn.neighbors import KDTree # do a quick, string-based check if the same sequence already exists if any(candidate.name == existing.name for existing in existing_sequences): return False points = np.array([sequence.product.flatten() for sequence in existing_sequences]) candidate = np.array([candidate.product.flatten()]) kdtree = KDTree(points) dist, _ = kdtree.query(candidate) return dist[0][0] > tol def _process_node(node: Node, basis: list[str], sequences: list[GateSequence]): inverse_last = _1q_inverses[node.labels[-1]] if node.labels else None for label in basis: if label == inverse_last: continue sequence = node.sequence.copy() sequence.append(_1q_gates[label]) if _check_candidate(sequence, sequences): sequences.append(sequence) node.children.append(Node(node.labels + (label,), sequence, [])) return node.children def generate_basic_approximations( basis_gates: list[str | Gate], depth: int, filename: str | None = None ) -> list[GateSequence]: """Generates a list of ``GateSequence``s with the gates in ``basic_gates``. Args: basis_gates: The gates from which to create the sequences of gates. depth: The maximum depth of the approximations. filename: If provided, the basic approximations are stored in this file. Returns: List of ``GateSequences`` using the gates in ``basic_gates``. Raises: ValueError: If ``basis_gates`` contains an invalid gate identifier. """ basis = [] for gate in basis_gates: if isinstance(gate, str): if gate not in _1q_gates.keys(): raise ValueError(f"Invalid gate identifier: {gate}") basis.append(gate) else: # gate is a qiskit.circuit.Gate basis.append(gate.name) tree = Node((), GateSequence(), []) cur_level = [tree] sequences = [tree.sequence] for _ in [None] * depth: next_level = [] for node in cur_level: next_level.extend(_process_node(node, basis, sequences)) cur_level = next_level if filename is not None: data = {} for sequence in sequences: gatestring = sequence.name data[gatestring] = sequence.product np.save(filename, data) return sequences
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. """Tests for visualization tools.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit from qiskit.visualization.circuit import _utils from qiskit.visualization import array_to_latex from qiskit.test import QiskitTestCase from qiskit.utils import optionals class TestVisualizationUtils(QiskitTestCase): """Tests for circuit drawer utilities.""" def setUp(self): super().setUp() self.qr1 = QuantumRegister(2, "qr1") self.qr2 = QuantumRegister(2, "qr2") self.cr1 = ClassicalRegister(2, "cr1") self.cr2 = ClassicalRegister(2, "cr2") self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2) self.circuit.cx(self.qr2[0], self.qr2[1]) self.circuit.measure(self.qr2[0], self.cr2[0]) self.circuit.cx(self.qr2[1], self.qr2[0]) self.circuit.measure(self.qr2[1], self.cr2[1]) self.circuit.cx(self.qr1[0], self.qr1[1]) self.circuit.measure(self.qr1[0], self.cr1[0]) self.circuit.cx(self.qr1[1], self.qr1[0]) self.circuit.measure(self.qr1[1], self.cr1[1]) def test_get_layered_instructions(self): """_get_layered_instructions without reverse_bits""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],))], [("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs) self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_reverse_bits(self): """_get_layered_instructions with reverse_bits=True""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions( self.circuit, reverse_bits=True ) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())], [("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs) self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_remove_idle_wires(self): """_get_layered_instructions with idle_wires=False""" qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(3, "qr2") cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.cx(qr2[0], qr2[1]) circuit.measure(qr2[0], cr2[0]) circuit.cx(qr2[1], qr2[0]) circuit.measure(qr2[1], cr2[1]) circuit.cx(qr1[0], qr1[1]) circuit.measure(qr1[0], cr1[0]) circuit.cx(qr1[1], qr1[0]) circuit.measure(qr1[1], cr1[1]) (qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False) exp = [ [("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())], [("measure", (qr2[0],), (cr2[0],))], [("measure", (qr1[0],), (cr1[0],))], [("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())], [("measure", (qr2[1],), (cr2[1],))], [("measure", (qr1[1],), (cr1[1],))], ] self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs) self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_simple(self): """Test _get_layered_instructions left justification simple since #2802 q_0: |0>───────■── ┌───┐ │ q_1: |0>┤ H ├──┼── ├───┤ │ q_2: |0>┤ H ├──┼── └───┘┌─┴─┐ q_3: |0>─────┤ X ├ └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_simple(self): """Test _get_layered_instructions right justification simple since #2802 q_0: |0>──■─────── │ ┌───┐ q_1: |0>──┼──┤ H ├ │ ├───┤ q_2: |0>──┼──┤ H ├ ┌─┴─┐└───┘ q_3: |0>┤ X ├───── └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_less_simple(self): """Test _get_layered_instructions left justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘└────────────┘ ║ └────────────┘ q_2: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_3: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_4: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_less_simple(self): """Test _get_layered_instructions right justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘ ║ └────────────┘ └────────────┘ q_2: |0>──────────────────────────────────╫────────────────────────────────── ║ q_3: |0>──────────────────────────────────╫────────────────────────────────── ║ q_4: |0>──────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ══════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_op_with_cargs(self): """Test _get_layered_instructions op with cargs right of measure ┌───┐┌─┐ q_0: |0>┤ H ├┤M├───────────── └───┘└╥┘┌───────────┐ q_1: |0>──────╫─┤0 ├ ║ │ add_circ │ c_0: 0 ══════╩═╡0 ╞ └───────────┘ c_1: 0 ═════════════════════ """ qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) qc_2 = QuantumCircuit(1, 1, name="add_circ") qc_2.h(0).c_if(qc_2.cregs[0], 1) qc_2.measure(0, 0) qc.append(qc_2, [1], [0]) (_, _, layered_ops) = _utils._get_layered_instructions(qc) expected = [ [("h", (Qubit(QuantumRegister(2, "q"), 0),), ())], [ ( "measure", (Qubit(QuantumRegister(2, "q"), 0),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], [ ( "add_circ", (Qubit(QuantumRegister(2, "q"), 1),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], ] self.assertEqual( expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode(self): """Test generate latex label default.""" self.assertEqual("abc", _utils.generate_latex_label("abc")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode_utf8char(self): """Test generate latex label utf8 characters.""" self.assertEqual( "{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_utf8char(self): """Test generate latex label mathtext with utf8.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc_$∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_underscore_outside(self): """Test generate latex label with underscore outside mathmode.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc$_∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_signs(self): """Test generate latex label with escaped dollarsign.""" self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self): """Test generate latex label with escaped dollar sign in mathmode.""" self.assertEqual( "a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label(r"$a$bc$_∭X∀Y"), ) def test_array_to_latex(self): """Test array_to_latex produces correct latex string""" matrix = [ [np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j], [1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2], ] matrix = np.array(matrix) exp_str = ( "\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&" "\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\" "\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-" "\\frac{9}{2}\\\\\\end{bmatrix}" ) result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "") self.assertEqual(exp_str, result) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/anpaschool/QC-School-Fall2020
anpaschool
import numpy as np zero_ket = np.array([[1], [0]]) print("|0> ket:\n", zero_ket) print("<0| bra:\n", zero_ket.T.conj()) zero_ket.T.conj() @ zero_ket one_ket = np.array([[0], [1]]) zero_ket.T.conj() @ one_ket zero_ket @ zero_ket.T.conj() ψ = np.array([[1], [0]])/np.sqrt(2) Π_0 = zero_ket @ zero_ket.T.conj() ψ.T.conj() @ Π_0 @ ψ from qiskit import QuantumCircuit, execute,QuantumCircuit, ClassicalRegister, QuantumRegister, Aer from math import pi import numpy as np from qiskit.visualization import plot_bloch_multivector, plot_histogram %matplotlib inline q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) # Apply H-gate to each qubit: circuit.h(q[0]) circuit.measure(q, c) circuit.draw('mpl') # Let's see the result: backend = Aer.get_backend('qasm_simulator') results = execute(circuit,backend, shots=1000).result() counts = results.get_counts(circuit) print(counts) plot_histogram(counts) ψ = np.array([[np.sqrt(2)/2], [np.sqrt(2)/2]]) Π_0 = zero_ket @ zero_ket.T.conj() probability_0 = ψ.T.conj() @ Π_0 @ ψ Π_0 @ ψ/np.sqrt(probability_0) backend = Aer.get_backend('qasm_simulator') q1 = QuantumRegister(1) c1 = ClassicalRegister(2) circuit1 = QuantumCircuit(q1, c1) circuit1.h(q1[0]) circuit1.measure(q1[0], c1[0]) circuit1.measure(q1[0], c1[1]) circuit1.draw('mpl') results = execute(circuit1,backend, shots=1000).result() counts1 = results.get_counts(circuit1) print(counts1) plot_histogram(counts1) q = QuantumRegister(2) c = ClassicalRegister(2) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.measure(q, c) job = execute(circuit, backend, shots=1000) plot_histogram(job.result().get_counts(circuit)) q = QuantumRegister(2) c = ClassicalRegister(2) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.cx(q[0], q[1]) circuit.measure(q, c) circuit.draw('mpl') job = execute(circuit, backend, shots=1000) plot_histogram(job.result().get_counts(circuit)) ψ = np.array([[1], [1]])/np.sqrt(2) ρ = ψ @ ψ.T.conj() Π_0 = zero_ket @ zero_ket.T.conj() np.trace(Π_0 @ ρ) probability_0 = np.trace(Π_0 @ ρ) Π_0 @ ρ @ Π_0/probability_0 zero_ket = np.array([[1], [0]]) one_ket = np.array([[0], [1]]) ψ = (zero_ket + one_ket)/np.sqrt(2) print("Density matrix of the equal superposition") print(ψ @ ψ.T.conj()) print("Density matrix of the equally mixed state of |0><0| and |1><1|") print((zero_ket @ zero_ket.T.conj()+one_ket @ one_ket.T.conj())/2)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# vector v v = [1,2,3] # vector u u=[-2,3] vu = [] for i in range(len(v)): # Each element of v will be replaced for j in range(len(u)): # the vector u will come to the replaced place after multiplying with the entry there vu.append( v[i] * u[j] ) print("v=",v) print("u=",u) print("vu=",vu) # # your solution is here # # matrix M M = [ [-1,0,1], [-2,-1,2], [1,2,-2] ] # matrix N N = [ [0,2,1], [3,-1,-2], [-1,1,0] ] # MN will be (9x9)-dimensional matrix # let's prepare it as a zero matrix # this helps us to easily fill it MN=[] for i in range(9): MN.append([]) for j in range(9): MN[i].append(0) for i in range(3): # row of M for j in range(3): # column of M for k in range(3): # row of N for l in range(3): # column of N MN[i*3+k][3*j+l] = M[i][j] * N[k][l] print("M-tensor-N is") for i in range(9): print(MN[i]) # matrix M and N were defined above # matrix NM will be prepared as a (9x9)-dimensional zero matrix NM=[] for i in range(9): NM.append([]) for j in range(9): NM[i].append(0) for i in range(3): # row of N for j in range(3): # column of N for k in range(3): # row of M for l in range(3): # column of M NM[i*3+k][3*j+l] = N[i][j] * M[k][l] print("N-tensor-M is") for i in range(9): print(NM[i]) # # your solution is here # # # your solution is here #
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
Ilan-Bondarevsky
from qiskit import * from oracle_generation import generate_oracle get_bin = lambda x, n: format(x, 'b').zfill(n) def gen_circuits(min,max,size): circuits = [] secrets = [] ORACLE_SIZE = size for i in range(min,max+1): cur_str = get_bin(i,ORACLE_SIZE-1) (circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str) circuits.append(circuit) secrets.append(secret) return (circuits, secrets)
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. """ Airspeed Velocity (ASV) benchmarks suite for simple 1-qubit/2-qubit gates """ from qiskit import QiskitError from qiskit.compiler import assemble from qiskit.providers.aer import QasmSimulator from .tools import mixed_unitary_noise_model, \ reset_noise_model, kraus_noise_model, no_noise, \ simple_cnot_circuit, simple_u3_circuit # Write the benchmarking functions here. # See "Writing benchmarks" in the asv docs for more information. class SimpleU3TimeSuite: """ Benchmark simple circuits with just one U3 gate The methods defined in this class will be executed by ASV framework as many times as the combination of all parameters exist in `self.params`, for exmaple: self.params = ([1,2,3],[4,5,6]), will run all methdos 9 times: time_method(1,4) time_method(1,5) time_method(1,6) time_method(2,4) time_method(2,5) time_method(2,6) time_method(3,4) time_method(3,5) time_method(3,6) For each noise model, we want to test various configurations of number of qubits """ def __init__(self): self.timeout = 60 * 20 self.backend = QasmSimulator() self.circuits = [] for i in 5, 10, 15: circuit = simple_u3_circuit(i) self.circuits.append(assemble(circuit, self.backend, shots=1)) self.param_names = [ "Simple u3 circuits", "Noise Model" ] self.params = (self.circuits, [ no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model() ]) def time_simple_u3(self, qobj, noise_model_wrapper): """ Benchmark for circuits with a simple u3 gate """ result = self.backend.run( qobj, noise_model=noise_model_wrapper() ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status) class SimpleCxTimeSuite: """ Benchmark simple circuits with just on CX gate For each noise model, we want to test various configurations of number of qubits """ def __init__(self): self.timeout = 60 * 20 self.backend = QasmSimulator() self.circuits = [] self.param_names = [ "Simple cnot circuits", "Noise Model" ] for i in 5, 10, 15: circuit = simple_cnot_circuit(i) self.circuits.append(assemble(circuit, self.backend, shots=1)) self.params = (self.circuits, [ no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model() ]) def time_simple_cx(self, qobj, noise_model_wrapper): """ Benchmark for circuits with a simple cx gate """ result = self.backend.run( qobj, noise_model=noise_model_wrapper() ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
https://github.com/JamesTheZhang/Qiskit2023
JamesTheZhang
######################################## # ENTER YOUR NAME AND WISC EMAIL HERE: # ######################################## # Name: Rochelle Li # Email: rli484@wisc.edu event = "Qiskit Fall Fest" ## Write your code below here. Delete the current information and replace it with your own ## ## Make sure to write your information between the quotation marks! name = "Rochelle Li" age = "19" school = "University of Wisconsin Madison" ## Now press the "Run" button in the toolbar above, or press Shift + Enter while you're active in this cell ## You do not need to write any code in this cell. Simply run this cell to see your information in a sentence. ## print(f'My name is {name}, I am {age} years old, and I attend {school}.') ## 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 # Create quantum circuit with 3 qubits and 3 classical bits # (we'll explain why we need the classical bits later) qc = QuantumCircuit(3,3) # return a drawing of the circuit qc.draw() ## You don't need to write any new code in this cell, just run it from qiskit import QuantumCircuit qc = QuantumCircuit(3,3) # measure all the qubits qc.measure([0,1,2], [0,1,2]) qc.draw(output="mpl") from qiskit.providers.aer import AerSimulator # make a new simulator object sim = AerSimulator() job = sim.run(qc) # run the experiment result = job.result() # get the results result.get_counts() # interpret the results as a "counts" dictionary from qiskit import QuantumCircuit from qiskit.providers.aer import AerSimulator ## Write your code below here ## qc = QuantumCircuit(4,4) qc.measure([0,1,2,3], [0,1,2,3]) ## Do not modify the code under this line ## qc.draw() sim = AerSimulator() # make a new simulator object job = sim.run(qc) # run the experiment result = job.result() # get the results answer1 = result.get_counts() # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex1a grade_ex1a(answer1) from qiskit import QuantumCircuit qc = QuantumCircuit(2) # We start by flipping the first qubit, which is qubit 0, using an X gate qc.x(0) # Next we add an H gate on qubit 0, putting this qubit in superposition. qc.h(0) # Finally we add a CX (CNOT) gate on qubit 0 and qubit 1 # This entangles the two qubits together qc.cx(0, 1) qc.draw(output="mpl") from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) ## Write your code below here ## qc.h(0) qc.cx(0,1) ## Do not modify the code under this line ## answer2 = qc qc.draw(output="mpl") # Grader Cell: Run this to submit your answer from qc_grader.challenges.fall_fest23 import grade_ex1b grade_ex1b(answer2)
https://github.com/erinaldi/bmn2-qiskit
erinaldi
# %% import time import fire import os import numpy as np import pandas as pd from scipy.sparse import diags from scipy.sparse import identity from qiskit import Aer from qiskit.opflow import MatrixOp, ListOp, TensoredOp, SummedOp, I from qiskit.circuit.library import EfficientSU2 from qiskit.algorithms import NumPyEigensolver, VQE from qiskit.algorithms.optimizers import SLSQP, COBYLA, L_BFGS_B, NELDER_MEAD from qiskit.utils import algorithm_globals, QuantumInstance # %% def build_operators(L: int, N: int) -> list: """Generate all the annihilation operators needed to build the hamiltonian Args: L (int): the cutoff of the single site Fock space N (int): the number of colors of gauge group SU(N) *it can not be different from 2 right now* Returns: list: a list of annihilation operators, length=N_bos, using PauliOp representation. """ # These are low-D (single boson) so we can use the MatrixOp for convenience # The annihilation operator for the single boson a_b = MatrixOp( diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1) ).to_pauli_op() # The identity operator of the Fock space of a single boson i_b = MatrixOp(identity(L)).to_pauli_op() # Now the memory starts growing! Use the PauliOp structure # Bosonic Hilbert space N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> fixed for mini-BMN 2 a_b_list = [] # this will contain a1...a6 as a list of ListOp for i in np.arange(0, N_bos): # loop over all operators operator_list = [i_b] * N_bos # only the identity repeated Nmat times operator_list[ i ] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append(ListOp(operator_list)) return [TensoredOp(a) for a in a_b_list] # %% def bmn2_hamiltonian(L: int = 2, N: int = 2, g2N: float = 0.2) -> SummedOp: """Construct the Hamiltonian of the bosonic BMN model as a sparse matrix. The cutoff for each boson is L while the 't Hooft coupling in g2N for a gauge group SU(N). The limited number of qubits only let us simulate N=2 and L=4 => for 6 bosons this is a 12 qubits problem. Args: L (int, optional): The cutoff of the bosonic modes (the annihilation operators will be LxL matrices). Defaults to 2. N (int, optional): The number of colors of a SU(N) gauge group. The degrees of freedom of one matrix will be N^2-1. Defaults to 2. g2N (float, optional): The 't Hooft coupling. Defaults to 0.2. Returns: SummedOp: the Hamiltonian in PauliOp form """ print( f"Building bosonic BMN Hamiltonian for SU({N}) with cutoff={L} and coupling={g2N}\n" ) # annihilation operators for bosons in full Hilbert space a_tensor = build_operators(L, N) N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> FIXED for mini-BMN 2 assert len(a_tensor) == N_bos # identity in full Hilbert space i_b = MatrixOp(identity(L)).to_pauli_op() i_tensor = TensoredOp(ListOp([i_b] * N_bos)) # Build the Hamiltonian # Start piece by piece # for each boson they are constructed using a and adag x_tensor = [1 / np.sqrt(2) * (~a + a) for a in a_tensor] # Free Hamiltonian # vacuum energy H_zero = 0.5 * N_bos * i_tensor # oscillators H_list = [H_zero] for a in a_tensor: H_list.append((~a @ a)) H_osc = SummedOp(H_list) # Interaction among bosons quartic1 = SummedOp( [ x_tensor[2] @ x_tensor[2] @ x_tensor[3] @ x_tensor[3], x_tensor[2] @ x_tensor[2] @ x_tensor[4] @ x_tensor[4], x_tensor[1] @ x_tensor[1] @ x_tensor[3] @ x_tensor[3], x_tensor[1] @ x_tensor[1] @ x_tensor[5] @ x_tensor[5], x_tensor[0] @ x_tensor[0] @ x_tensor[4] @ x_tensor[4], x_tensor[0] @ x_tensor[0] @ x_tensor[5] @ x_tensor[5], ] ) quartic2 = SummedOp( [ x_tensor[0] @ x_tensor[2] @ x_tensor[3] @ x_tensor[5], x_tensor[0] @ x_tensor[1] @ x_tensor[3] @ x_tensor[4], x_tensor[1] @ x_tensor[2] @ x_tensor[4] @ x_tensor[5], ], coeff=-2.0, ) ### Quartic Interaction V = quartic1 + quartic2 # full hamiltonian H = H_osc + g2N / N * V return H.to_pauli_op() # %% def run_vqe( L: int = 2, N: int = 2, g2N: float = 0.2, optimizer: str = "COBYLA", maxit: int = 5000, varform: list = ["ry"], depth: int = 3, nrep: int = 10, rngseed: int = 0, h5: bool = True, ): """Run the main VQE solver for a bosonic BMN Hamiltonian where bosons are LxL matrices and the 't Hooft coupling is g2N for a SU(N) gauge group. The VQE is initialized with a specific optimizer and a specific variational quantum circuit based on EfficientSU2. Args: L (int, optional): Cutoff of each bosonic degree of freedom. Defaults to 2. N (int, optional): Colors for the SU(N) gauge group. Defaults to 2. g2N (float, optional): 't Hooft coupling. Defaults to 0.2. optimizer (str, optional): VQE classical optimizer. Defaults to "COBYLA". maxit (int, optional): Max number of iterations for the optimizer. Defaults to 5000. varform (str, optional): EfficientSU2 rotation gates. Defaults to 'ry'. depth (int, optional): Depth of the variational form. Defaults to 3. nrep (int, optional): Number of different random initializations of parameters. Defaults to 1. rngseed (int, optional): The random seed. Defaults to 0. h5 (bool, optional): The flag to save in HDF5 format. Defaults to True. """ assert N == 2 # code only works for SU(2) :-( # Create the matrix Hamiltonian in PauliOp form qubitOp = bmn2_hamiltonian(L, N, g2N) # Next, we create the variational form. var_form = EfficientSU2( qubitOp.num_qubits, su2_gates=varform, entanglement="full", reps=depth ) # start a quantum instance # fix the random seed of the simulator to make values reproducible rng = np.random.default_rng(seed=rngseed) algorithm_globals.random_seed = rngseed algorithm_globals.massive=True # use the aer simulator instead of statevector backend = Aer.get_backend('aer_simulator') q_instance = QuantumInstance( backend, seed_transpiler=rngseed, seed_simulator=rngseed ) # initialize optimizers' parameters: number of iterations optimizers = { "COBYLA": COBYLA(maxiter=maxit), "L-BFGS-B": L_BFGS_B(maxfun=maxit), "SLSQP": SLSQP(maxiter=maxit), "NELDER-MEAD": NELDER_MEAD(maxfev=maxit), } print(f"\nRunning VQE main loop ...") start_time = time.time() try: optim = optimizers[optimizer] print(f"{optimizer} settings: {optim.settings}") except KeyError: print( f"Optimizer {optimizer} not found in our list. Try one of {[x for x in optimizers.keys()]}" ) return results = {"counts": [], "energy": [], "casimir": []} casimir_result = ( "NaN" # initialize to NaN since it will not be defined if we do not measure it ) # callback functions to store the counts from each iteration of the VQE def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # run multiple random initial points for i in np.arange(nrep): counts = [] values = [] # initital points for the angles of the rotation gates random_init = rng.uniform(-2 * np.pi, 2 * np.pi, var_form.num_parameters) # Setup the VQE algorithm with include_custom=True for Pauli expectations with snapshot vqe = VQE( ansatz=var_form, optimizer=optim, initial_point=random_init, quantum_instance=q_instance, callback=store_intermediate_result, include_custom=True, ) # run the VQE with our Hamiltonian operator result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result}") # collect results results["counts"].append(counts) results["energy"].append(values) results["casimir"].append(casimir_result) end_time = time.time() runtime = end_time - start_time print(f"Program runtime: {runtime} s") # make a dataframe from the results df = pd.DataFrame.from_dict(results) data_types_dict = {"counts": int, "energy": float} df = df.explode(["counts", "energy"]).astype(data_types_dict).rename_axis("rep") # report summary of energy across reps converged = df["energy"].groupby("rep").apply(min).values print(f"Statistics across {nrep} repetitions:\n-------------------") print( f"Least upper bound: {np.min(converged)}\nWorst upper bound: {np.max(converged)}\nMean bound: {np.mean(converged)}\nStd bound: {np.std(converged)}" ) # save results on disk varname = "-".join(varform) g2Nstr = str(g2N).replace(".", "") os.makedirs("data", exist_ok=True) if h5: outfile = f"data/bosBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.h5" print(f"Save results on disk: {outfile}") df.to_hdf(outfile, "vqe") else: outfile = f"data/bosBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.gz" print(f"Save results on disk: {outfile}") df.to_pickle(outfile) return # %% if __name__ == "__main__": fire.Fire(run_vqe)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/rubenandrebarreiro/ibm-qiskit-quantum-explorers-2023-2024
rubenandrebarreiro
# update/upgrade Python's pip module !pip install --upgrade pip -q # install the IBM Qiskit's Machine Learning and Optimization modules !pip install qiskit_machine_learning qiskit_optimization -q # build your code here answer1 = [2] # run this cell to submit your answer # import the grader for the exercise 1 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex1 # expected result type: List grade_badge6_ex1(answer1) # build your code here answer2 = [4] # run this cell to submit your answer # import the grader for the exercise 2 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex2 # expected result type: List grade_badge6_ex2(answer2) # build your code here answer3 = [3] # run this cell to submit your answer # import the grader for the exercise 3 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex3 # expected result type: List grade_badge6_ex3(answer3) # build your code here answer4 = [2] # run this cell to submit your answer # import the grader for the exercise 4 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex4 # expected result type: List grade_badge6_ex4(answer4) # build your code here answer5 = [3] # run this cell to submit your answer # import the grader for the exercise 5 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex5 # expected result type: List grade_badge6_ex5(answer5) # build your code here answer6 = [1] # run this cell to submit your answer # import the grader for the exercise 6 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex6 # expected result type: List grade_badge6_ex6(answer6) # build your code here answer7 = [2] # run this cell to submit your answer # import the grader for the exercise 7 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex7 # expected result type: list grade_badge6_ex7(answer7) # build your code here answer8 = [1] # run this cell to submit your answer # import the grader for the exercise 8 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex8 # expected result type: List grade_badge6_ex8(answer8) # build your code here answer9 = [3] # run this cell to submit your answer # import the grader for the exercise 9 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex9 # expected result type: List grade_badge6_ex9(answer9) # build your code here answer10 = [2] # run this cell to submit your answer # import the grader for the exercise 10 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex10 # expected result type: List grade_badge6_ex10(answer10) # build your code here answer11 = [3] # run this cell to submit your answer # import the grader for the exercise 11 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex11 # expected result type: List grade_badge6_ex11(answer11) # build your code here answer12 = [4] # run this cell to submit your answer # import the grader for the exercise 12 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex12 # expected result type: List grade_badge6_ex12(answer12) # cod block for the definition of helper functions # to draw and visualize graph solution # import the PyPlot module from the Matplot Library import matplotlib.pyplot as plt # import the NetworkX Library import networkx as nx # definition of a helper function to draw the graph, # using the NetworkX library's functionalities def draw_graph(G, colors, pos): # retrieve the default axes of the plotting object with a frame-on default_axes = plt.axes(frameon = True) # draw a network representing the graph, with the respective nodes and edges nx.draw_networkx(G, node_color = colors, node_size = 600, alpha = 0.8, ax = default_axes, pos = pos, node_shape = "o") # retrieve the weight labels of the edges of the graph edge_labels = nx.get_edge_attributes(G, "weight") # draw the weight labels of the edges to the resulting graph network nx.draw_networkx_edge_labels(G, pos = pos, edge_labels = edge_labels) # definition of a helper function to draw the solution of # the Traveling Salesman Problem (TSP), in the respective graph representation def draw_tsp_solution(G, order, colors, pos): # convert the structure of the initial given # undirected graph to a directed graph G2 = nx.DiGraph() # add the nodes from the initial given # undirected graph to the created directed graph G2.add_nodes_from(G) # retrieves the number of edges of the directed graph representation n = len(order) # for any edge for the directed graph representing the solution # for the given Traveling Salesman Problem (TSP) for i in range(n): # retrieve the destination node for the current directed edge j = (i + 1) % n # add the current directed edge to # the directed graph representing the solution # for the given Traveling Salesman Problem (TSP) G2.add_edge(order[i], order[j], weight = G[order[i]][order[j]]["weight"]) # retrieve the default axes of the plotting object with a frame-on default_axes = plt.axes(frameon = True) # draw a network representing the new directed graph, # with the respective nodes and edges, representing # the solution for the given Traveling Salesman Problem (TSP) nx.draw_networkx(G2, node_color = colors, edge_color = "b", node_size = 600, alpha = 0.8, ax = default_axes, pos = pos) # retrieve the weight labels of the edges of the new directed graph, # representing the solution for the given Traveling Salesman Problem (TSP) edge_labels = nx.get_edge_attributes(G2, "weight") # draw the weight labels of the edges to the resulting new directed graph network, # representing the solution for the given Traveling Salesman Problem (TSP) nx.draw_networkx_edge_labels(G2, pos, font_color = "b", edge_labels = edge_labels) # import the Traveling Salesman Problem (TSP) from # the IBM Qiskit's Optimization Application module from qiskit_optimization.applications import Tsp # create a random instance of the Traveling Salesman Problem (TSP), # with 4 nodes and a fixed pseudo-random seed tsp = Tsp.create_random_instance(4, seed=43) # retrieve the adjoint matrix for the graph representation of # the instance of the Traveling Salesman Problem (TSP) previously created adj_matrix = nx.to_numpy_array(tsp.graph) # print the adjoint matrix for the graph representation of # the instance of the Traveling Salesman Problem (TSP) previously created, # as the distances (edges' weigths) between the respective nodes print("Distances:\n", adj_matrix) # set the color of the nodes of # the instance of the Traveling Salesman Problem (TSP) # previously created, with the red color colors = ["r"] * len(tsp.graph.nodes) # retrieve the positions of the nodes of # the instance of the Traveling Salesman Problem (TSP) pos = [tsp.graph.nodes[node]["pos"] for node in tsp.graph.nodes] # draw the graph representation of # the instance of the Traveling Salesman Problem (TSP), # using the NetworkX library's functionalities draw_graph(tsp.graph, colors, pos) # import the Quandratic Program to # Quadratic Unconstrained Binary Optimization (QUBO) converter, # from the IBM Qiskit's Optimization Convertes module from qiskit_optimization.converters import QuadraticProgramToQubo # convert the original optimization formulation of # the Traveling Salesman Problem (TSP) created before, # to a Quadratic Program, to solve it using a quantum computer qp = tsp.to_quadratic_program() # initialize the Quandratic Program to # Quadratic Unconstrained Binary Optimization (QUBO) converter qp2qubo = QuadraticProgramToQubo() # convert the Quadratic Program formulation of # the Traveling Salesman Problem (TSP) created before, # to a Quadratic Unconstrained Binary Optimization (QUBO) Program, # to solve it using a quantum computer qubo = qp2qubo.convert(qp) # convert the Quadratic Unconstrained Binary Optimization (QUBO) # formulation of the Traveling Salesman Problem (TSP) created before, # to an Ising Hamiltonian, to solve it using a quantum computer, # retrieving the respective qubit operations qubitOp, offset = qubo.to_ising() # import the Sampling Variational Quantum Eigensolver (VQE) algorithm # from the IBM Qiskit's Minimum Eigesolvers Algorithms module from qiskit.algorithms.minimum_eigensolvers import SamplingVQE # import the Nakanishi-Fujii-Todo (NFT) Optimizer # from the IBM Qiskit's Optimizers Algorithms module from qiskit.algorithms.optimizers import NFT # import the parametrized two-local quantum circuits # from the IBM Qiskit's Circuit Library module from qiskit.circuit.library import TwoLocal # import the Aer Sample from # the IBM Qiskit's Aer Primitives module from qiskit_aer.primitives import Sampler as AerSampler # import the Algorithm's Global Parameters from # the IBM Qiskit's Utilities module from qiskit.utils import algorithm_globals # set a fixed pseudo-random seed # as an Algorithm's Global Parameter algorithm_globals.random_seed = 123 # create a Nakanishi-Fujii-Todo (NFT) Optimizer instance, # with a maximum number of 100 iterations optimizer = NFT(maxiter=100) # create a Parametrized Two-Local Ansatz Quantum Circuit, # for the parametrized y-axis rotations for the qubits, # aiming a linear quantum entanglement ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps = 2, entanglement = "linear") ####### build your code below ######### # build a Variational Quantum Eigensolver (VQE) algorithm instance, # with the respective Aer Sample, Parametrized Two-Local Ansatz # Quantum Circuit, and Nakanishi-Fujii-Todo (NFT) Optimizer, # to solve the Traveling Salesman Problem (TSP) created before vqe = SamplingVQE(sampler=AerSampler(), ansatz=ry, optimizer=optimizer) ####### build your code above ######### # compute the minimum eigenvalue for # the Variational Quantum Eigensolver (VQE) algorithm instance # created before to solve the Traveling Salesman Problem (TSP) # created before, using the Qubit Operations retrieved before result = vqe.compute_minimum_eigenvalue(qubitOp) # print the energy values from minimum eigenvalue computed before # from Variational Quantum Eigensolver (VQE) algorithm instance # that solved the Traveling Salesman Problem (TSP) print("Energy:", result.eigenvalue.real) # print the elepsed time to compute minimum eigenvalue # from Variational Quantum Eigensolver (VQE) algorithm instance # that solved the Traveling Salesman Problem (TSP) print("Elapsed Time (secs):", result.optimizer_time) # retrieve the most likely saple from the eigenstate # from the minimum eigenvalue computed before # from Variational Quantum Eigensolver (VQE) algorithm instance # that solved the Traveling Salesman Problem (TSP), # as one the possible solutions for it x = tsp.sample_most_likely(result.eigenstate) # retrieve the boolean flag with respect to # the fact that the solution achieved is feasible # for the Quadratic Unconstrained Binary Optimization (QUBO) Program # formulating the pretended Traveling Salesman Problem (TSP) print("Feasible:", qubo.is_feasible(x)) # retrieves (and interprets) the solution result as a list of # nodes' indices corresponding to the real solution # for the pretended Traveling Salesman Problem (TSP) z = tsp.interpret(x) # print the list of nodes' indices # corresponding to the real solution (nodes' sequence) # for the pretended Traveling Salesman Problem (TSP) print("Solution:", z) # print solution to the objective function # corresponding to the real solution (nodes' sequence) # for the pretended Traveling Salesman Problem (TSP) print("Solution Objective:", tsp.tsp_value(z, adj_matrix)) # draw the solution of the pretended Traveling Salesman Problem (TSP) # solution, in the respective graph representation draw_tsp_solution(tsp.graph, z, colors, pos) # run this cell to submit your answer # import the grader for the coding exercise of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_code # expected result type: ( tsp: Tsp, qubo: QuadraticProgram, # result: SamplingVQEResult ) grade_badge6_code(tsp, qubo, result) # import the Qiskit Runtime Service, Session, and Sampler, # from the Qiksit's IBM Runtime module from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler # create a Qiskit's Runtime Service object, # using the IBM Quantum channel service = QiskitRuntimeService( channel="ibm_quantum" ) # retrieve the least-busy backend # with a minimum number of qubits # corresponding to the number of qubits # required for the retrieved Qubit Operations # (this step can take a while) real_backend = service.least_busy( min_num_qubits=qubitOp.num_qubits, simulator=False ) # print the information about the best (i.e., the least-busy) # backend with a minimum number of two qubits, and an informative # message about the job submission on this backend print(f"The least busy backend is {real_backend.name}!") # within the context of a Session configured # with the Qiskit's Runtime Service object, # created before, using the IBM Quantum channel, # and also using the backend defined before # with Session( service=service, backend=real_backend ) as session: ###### add your answers from the above code cell here ####### ###### before running this code cell itself ####### # build a Variational Quantum Eigensolver (VQE) algorithm instance, # with the respective Aer Sample, Parametrized Two-Local Ansatz # Quantum Circuit, and Nakanishi-Fujii-Todo (NFT) Optimizer, # to solve the Traveling Salesman Problem (TSP) created before #vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer) # compute the minimum eigenvalue for # the Variational Quantum Eigensolver (VQE) algorithm instance # created before to solve the Traveling Salesman Problem (TSP) # created before, using the Qubit Operations retrieved before #result = vqe.compute_minimum_eigenvalue(qubitOp) # compute the minimum eigenvalue for # the Variational Quantum Eigensolver (VQE) algorithm instance # created before to solve the Traveling Salesman Problem (TSP) # created before, using the Qubit Operations retrieved before #result = vqe.compute_minimum_eigenvalue(qubitOp) # print the energy values from minimum eigenvalue computed before # from Variational Quantum Eigensolver (VQE) algorithm instance # that solved the Traveling Salesman Problem (TSP) #print("Energy:", result.eigenvalue.real) # print the elepsed time to compute minimum eigenvalue # from Variational Quantum Eigensolver (VQE) algorithm instance # that solved the Traveling Salesman Problem (TSP) #print("Elapsed Time (secs):", result.optimizer_time) # retrieve the most likely saple from the eigenstate # from the minimum eigenvalue computed before # from Variational Quantum Eigensolver (VQE) algorithm instance # that solved the Traveling Salesman Problem (TSP), # as one the possible solutions for it #x = tsp.sample_most_likely(result.eigenstate) # retrieve the boolean flag with respect to # the fact that the solution achieved is feasible # for the Quadratic Unconstrained Binary Optimization (QUBO) Program # formulating the pretended Traveling Salesman Problem (TSP) #print("Feasible:", qubo.is_feasible(x)) # retrieves (and interprets) the solution result as a list of # nodes' indices corresponding to the real solution # for the pretended Traveling Salesman Problem (TSP) #z = tsp.interpret(x) # print the list of nodes' indices # corresponding to the real solution (nodes' sequence) # for the pretended Traveling Salesman Problem (TSP) #print("Solution:", z) # print solution to the objective function # corresponding to the real solution (nodes' sequence) # for the pretended Traveling Salesman Problem (TSP) #print("Solution Objective:", tsp.tsp_value(z, adj_matrix)) # draw the solution of the pretended Traveling Salesman Problem (TSP) # solution, in the respective graph representation #draw_tsp_solution(tsp.graph, z, colors, pos) # build your code here answer13 = [1] # run this cell to submit your answer # import the grader for the exercise 13 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex13 # expected result type: List grade_badge6_ex13(answer13) # build your code here answer14 = [1] # run this cell to submit your answer # import the grader for the exercise 14 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex14 # expected result type: List grade_badge6_ex14(answer14) # build your code here answer15 = [4] # run this cell to submit your answer # import the grader for the exercise 15 of the lab/badge 6 from qc_grader.challenges.quantum_explorers23 import grade_badge6_ex15 # expected result type: List grade_badge6_ex15(answer15) # run this cell to check whether you have passed # import the grader for the badge 6 of # the IBM Qiskit's Quantum Explorers 2023-2024 from qc_grader.challenges.quantum_explorers23 import grade_badge6_score # grade the score of the quiz of the lab for the badge 6 grade_badge6_score("en")
https://github.com/Harcipan/QAI_GroverSim
Harcipan
# 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://docs.quantum-computing.ibm.com/run/primitives # result = Sampler().run(circuits).result() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, transpile, assemble # considering our bit string to be ‘101’ b = '101' n = len(b) # creating two quantum registers of ’n’ qubits and 1 classical register of ’n’ qubits q_reg1 = QuantumRegister(n, 'reg1') q_reg2 = QuantumRegister(n, 'reg2') c_reg = ClassicalRegister(n) circuit = QuantumCircuit(q_reg1, q_reg2, c_reg) # applying H-gate on qubits of the first register circuit.h(q_reg1) circuit.barrier() # copying the data of the first register to the second register circuit.cx(q_reg1, q_reg2) circuit.barrier() # applying bit-wise X-OR from register 1 to register 2 where qubits of the first register are 1 circuit.cx(q_reg1[0], q_reg2[0]) circuit.cx(q_reg1[0], q_reg2[2]) circuit.barrier() # measuring qubits of the second register circuit.measure(q_reg2, c_reg) # applying H-gate to qubits of the first register circuit.h(q_reg1) circuit.barrier() # measuring qubits of the first register circuit.measure(q_reg1, c_reg) circuit.draw() # running the circuit using "qasm simulator" qasm_sim = Aer.get_backend("qasm_simulator") job = assemble(circuit,qasm_sim) result = qasm_sim.run(job).result() counts = result.get_counts() plot_histogram(counts)
https://github.com/Gopal-Dahale/qiskit-qulacs
Gopal-Dahale
"""Tests for qulacs sampler.""" from unittest import TestCase import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, UnitaryGate from qiskit.primitives import SamplerResult from qiskit.providers import JobStatus from qiskit_qulacs.qulacs_sampler import QulacsSampler from tests.utils import dicts_almost_equal class TestQulacsSampler(TestCase): """Test QulacsSampler""" def setUp(self): super().setUp() hadamard = QuantumCircuit(1, 1, name="Hadamard") hadamard.h(0) hadamard.measure(0, 0) bell = QuantumCircuit(2, name="Bell") bell.h(0) bell.cx(0, 1) bell.measure_all() self._circuit = [hadamard, bell] self._target = [ {0: 0.5, 1: 0.5}, {0: 0.5, 3: 0.5, 1: 0, 2: 0}, ] self._pqc = RealAmplitudes(num_qubits=2, reps=2).decompose() self._pqc.measure_all() self._pqc2 = RealAmplitudes(num_qubits=2, reps=3).decompose() self._pqc2.measure_all() self._pqc_params = [[0.0] * 6, [1.0] * 6] self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}] self._theta = [ [0, 1, 1, 2, 3, 5], [1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], ] def _generate_circuits_target(self, indices): if isinstance(indices, list): circuits = [self._circuit[j] for j in indices] target = [self._target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return circuits, target def _generate_params_target(self, indices): if isinstance(indices, int): params = self._pqc_params[indices] target = self._pqc_target[indices] elif isinstance(indices, list): params = [self._pqc_params[j] for j in indices] target = [self._pqc_target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return params, target def _compare_probs(self, prob, target): if not isinstance(prob, list): prob = [prob] if not isinstance(target, list): target = [target] self.assertEqual(len(prob), len(target)) for p, targ in zip(prob, target): for key, t_val in targ.items(): if key in p: self.assertAlmostEqual(p[key], t_val, places=1) else: self.assertAlmostEqual(t_val, 0, places=1) def test_sampler_run(self): """Test Sampler.run().""" bell = self._circuit[1] sampler = QulacsSampler() job = sampler.run(circuits=[bell]) result = job.result() self.assertIsInstance(result, SamplerResult) self._compare_probs(result.quasi_dists, self._target[1]) def test_sample_run_multiple_circuits(self): """Test Sampler.run() with multiple circuits.""" # executes three Bell circuits # Argument `parameters` is optional. bell = self._circuit[1] sampler = QulacsSampler() result = sampler.run([bell, bell, bell]).result() self._compare_probs(result.quasi_dists[0], self._target[1]) self._compare_probs(result.quasi_dists[1], self._target[1]) self._compare_probs(result.quasi_dists[2], self._target[1]) def test_sampler_run_with_parameterized_circuits(self): """Test Sampler.run() with parameterized circuits.""" # parameterized circuit pqc = self._pqc pqc2 = self._pqc2 theta1, theta2, theta3 = self._theta sampler = QulacsSampler() result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() # result of pqc(theta1) prob1 = { "00": 0.1309248462975777, "01": 0.3608720796028448, "10": 0.09324865232050054, "11": 0.41495442177907715, } error_msg = dicts_almost_equal( result.quasi_dists[0].binary_probabilities(), prob1 ) if error_msg: msg = self._formatMessage(None, error_msg) raise self.failureException(msg) # result of pqc(theta2) prob2 = { "00": 0.06282290651933871, "01": 0.02877144385576705, "10": 0.606654494132085, "11": 0.3017511554928094, } error_msg = dicts_almost_equal( result.quasi_dists[1].binary_probabilities(), prob2 ) if error_msg: msg = self._formatMessage(None, error_msg) raise self.failureException(msg) # result of pqc2(theta3) prob3 = { "00": 0.1880263994380416, "01": 0.6881971261189544, "10": 0.09326232720582443, "11": 0.030514147237179892, } error_msg = dicts_almost_equal( result.quasi_dists[2].binary_probabilities(), prob3 ) if error_msg: msg = self._formatMessage(None, error_msg) raise self.failureException(msg) def test_run_1qubit(self): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = QulacsSampler() result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) for i in range(2): keys, values = zip(*sorted(result.quasi_dists[i].items())) self.assertTupleEqual(keys, (i,)) np.testing.assert_allclose(values, [1]) def test_run_2qubit(self): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.x(0) qc1.measure_all() qc2 = QuantumCircuit(2) qc2.x(1) qc2.measure_all() qc3 = QuantumCircuit(2) qc3.x([0, 1]) qc3.measure_all() sampler = QulacsSampler() result = sampler.run([qc0, qc1, qc2, qc3]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) for i in range(4): keys, values = zip(*sorted(result.quasi_dists[i].items())) self.assertTupleEqual(keys, (i,)) np.testing.assert_allclose(values, [1]) def test_run_single_circuit(self): """Test for single circuit case.""" sampler = QulacsSampler() with self.subTest("No parameter"): circuit = self._circuit[1] target = self._target[1] param_vals = [None, [], [[]], np.array([]), np.array([[]])] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) with self.subTest("One parameter"): circuit = QuantumCircuit(1, 1, name="X gate") param = Parameter("x") circuit.ry(param, 0) circuit.measure(0, 0) target = [{1: 1}] param_vals = [ [np.pi], [[np.pi]], np.array([np.pi]), np.array([[np.pi]]), [np.array([np.pi])], ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) with self.subTest("More than one parameter"): circuit = self._pqc target = [self._pqc_target[0]] param_vals = [ self._pqc_params[0], [self._pqc_params[0]], np.array(self._pqc_params[0]), np.array([self._pqc_params[0]]), [np.array(self._pqc_params[0])], ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) def test_run_reverse_meas_order(self): """test for sampler with reverse measurement order""" x = Parameter("x") y = Parameter("y") qc = QuantumCircuit(3, 3) qc.rx(x, 0) qc.rx(y, 1) qc.x(2) qc.measure(0, 2) qc.measure(1, 1) qc.measure(2, 0) sampler = QulacsSampler() result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) # qc({x: 0, y: 0}) keys, values = zip(*sorted(result.quasi_dists[0].items())) self.assertTupleEqual(keys, (1,)) np.testing.assert_allclose(values, [1]) # qc({x: pi/2, y: 0}) keys, values = zip(*sorted(result.quasi_dists[1].items())) self.assertTupleEqual(keys, (1, 5)) np.testing.assert_allclose(values, [0.5, 0.5]) def test_run_errors(self): """Test for errors with run method""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1).decompose() qc2.measure_all() qc3 = QuantumCircuit(1) qc4 = QuantumCircuit(1, 1) qc5 = QuantumCircuit(1, 1) with qc5.for_loop(range(5)): qc5.h(0) sampler = QulacsSampler() with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc1], [[1e2]]) with self.subTest("missing all parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[]]) with self.subTest("missing some parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[1e2]]) with self.subTest("too many parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[1e2]] * 100) with self.subTest("no classical bits"): with self.assertRaises(ValueError): _ = sampler.run([qc3], [[]]) with self.subTest("no measurement"): with self.assertRaises(ValueError): _ = sampler.run([qc4], [[]]) with self.subTest("no measurement in control flow"): with self.assertRaises(ValueError): _ = sampler.run([qc5], [[]]) def test_run_empty_parameter(self): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) sampler = QulacsSampler() with self.subTest("one circuit"): result = sampler.run([qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 1) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictEqual(quasi_dist, {0: 1.0}) self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictEqual(quasi_dist, {0: 1.0}) self.assertEqual(len(result.metadata), 2) def test_run_numpy_params(self): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2).decompose() qc.measure_all() k = 5 rng = np.random.default_rng(12) params_array = rng.random((k, qc.num_parameters)) params_list = params_array.tolist() params_list_array = list(params_array) sampler = QulacsSampler() target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) with self.subTest("list of ndarray"): result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) def test_run_with_shots_option(self): """test with shots option.""" params, target = self._generate_params_target([1]) sampler = QulacsSampler() result = sampler.run( circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 ).result() self._compare_probs(result.quasi_dists, target) def test_run_with_shots_option_none(self): """test with shots=None option. Seed is ignored then.""" sampler = QulacsSampler() result_42 = sampler.run( [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=42 ).result() result_15 = sampler.run( [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=15 ).result() error_msg = dicts_almost_equal(result_42.quasi_dists, result_15.quasi_dists) if error_msg: msg = self._formatMessage(None, error_msg) raise self.failureException(msg) def test_run_shots_result_size(self): """test with shots option to validate the result size""" n = 10 shots = 100 qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() sampler = QulacsSampler() result = sampler.run(qc, [], shots=shots, seed=42).result() self.assertEqual(len(result.quasi_dists), 1) self.assertLessEqual(len(result.quasi_dists[0]), shots) self.assertAlmostEqual(sum(result.quasi_dists[0].values()), 1.0) def test_primitive_job_status_done(self): """test primitive job's status""" bell = self._circuit[1] sampler = QulacsSampler() job = sampler.run(circuits=[bell]) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_options(self): """Test for options""" with self.subTest("init"): sampler = QulacsSampler(options={"shots": 3000}) self.assertEqual(sampler.options.get("shots"), 3000) with self.subTest("set_options"): sampler.set_options(shots=1024, seed=15) self.assertEqual(sampler.options.get("shots"), 1024) self.assertEqual(sampler.options.get("seed"), 15) with self.subTest("run"): params, target = self._generate_params_target([1]) result = sampler.run([self._pqc], parameter_values=params).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(result.quasi_dists[0].shots, 1024) def test_circuit_with_unitary(self): """Test for circuit with unitary gate.""" gate = UnitaryGate(np.eye(2)) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = QulacsSampler() sampler_result = sampler.run([circuit]).result() error_msg = dicts_almost_equal(sampler_result.quasi_dists[0], {0: 1, 1: 0}) if error_msg: msg = self._formatMessage(None, error_msg) raise self.failureException(msg)
https://github.com/arian-code/nptel_quantum_assignments
arian-code
from sympy import * import numpy as np init_printing(use_unicode=True) a, b, d, f = symbols('alpha beta theta phi') a, b, d, f p1=exp(I*f) p2=Matrix([[exp(-I*a/2), 0],[0, exp(I*a/2)]]) p3=Matrix([[cos (d/2), -I*sin (d/2)],[-I*sin (d/2), cos (d/2)]]) p4=Matrix([[exp(-I*b/2), 0],[0, exp(I*b/2)]]) p1, p2, p3, p4 out=p1*p2*p3*p4 out H=Matrix([[1/sqrt(2), 1/sqrt(2)],[1/sqrt(2), -1/sqrt(2)]]) lhs=H lhs #option A rhs=out.subs([(f, 0), (a, 0), (b, 0), (d, pi/2)]) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option B lhs=out.subs([(f, pi/2), (a, pi/2), (b, pi/2), (d, pi/2)]) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option C lhs=out.subs([(f, 0), (a, pi/2), (b, pi/2), (d, pi/4)]) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option D lhs=out.subs([(f, pi/4), (a, pi/2), (b, pi/2), (d, pi/4)]) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Create circuit to test transpiler on from qiskit import QuantumCircuit from qiskit.circuit.library import GroverOperator, Diagonal oracle = Diagonal([1]*7 + [-1]) qc = QuantumCircuit(3) qc.h([0,1,2]) qc = qc.compose(GroverOperator(oracle)) # Use Statevector object to calculate the ideal output from qiskit.quantum_info import Statevector ideal_distribution = Statevector.from_instruction(qc).probabilities_dict() from qiskit.visualization import plot_histogram plot_histogram(ideal_distribution) from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = service.backend('ibm_algiers') # Need to add measurements to the circuit qc.measure_all() from qiskit import transpile circuits = [] for optimization_level in [0, 3]: t_qc = transpile(qc, backend, optimization_level=optimization_level, seed_transpiler=0) print(f'CNOTs (optimization_level={optimization_level}): ', t_qc.count_ops()['cx']) circuits.append(t_qc) from qiskit.transpiler import PassManager, InstructionDurations from qiskit.transpiler.passes import ASAPSchedule, DynamicalDecoupling from qiskit.circuit.library import XGate # Get gate durations so the transpiler knows how long each operation takes durations = InstructionDurations.from_backend(backend) # This is the sequence we'll apply to idling qubits dd_sequence = [XGate(), XGate()] # Run scheduling and dynamic decoupling passes on circuit pm = PassManager([ASAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence)] ) circ_dd = pm.run(circuits[1]) # Add this new circuit to our list circuits.append(circ_dd) from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run( circuits=circuits, # sample all three circuits skip_transpilation=True, shots=8000) result = job.result() from qiskit.visualization import plot_histogram binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob+[ideal_distribution], bar_labels=False, legend=['optimization_level=0', 'optimization_level=3', 'optimization_level=3 + dd', 'ideal distribution']) from qiskit.quantum_info import hellinger_fidelity for counts in result.quasi_dists: print( f"{hellinger_fidelity(counts.binary_probabilities(), ideal_distribution):.3f}" ) import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table %qiskit_copyright
https://github.com/JackHidary/quantumcomputingbook
JackHidary
# install cirq !pip install cirq==0.5 --quiet import cirq import numpy as np import random print(cirq.google.Bristlecone) def make_quantum_teleportation_circuit(gate): circuit = cirq.Circuit() msg, alice, bob = cirq.LineQubit.range(3) # Creates Bell state to be shared between Alice and Bob circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)]) # Creates a random state for the Message circuit.append(gate(msg)) # Bell measurement of the Message and Alice's entangled qubit circuit.append([cirq.CNOT(msg, alice), cirq.H(msg)]) circuit.append(cirq.measure(msg, alice)) # Uses the two classical bits from the Bell measurement to recover the # original quantum Message on Bob's entangled qubit circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)]) return circuit gate = cirq.SingleQubitMatrixGate(cirq.testing.random_unitary(2)) circuit = make_quantum_teleportation_circuit(gate) print("Circuit:") print(circuit) sim = cirq.Simulator() # Create qubits. q0 = cirq.LineQubit # Produces the message using random unitary message = sim.simulate(cirq.Circuit.from_ops(gate(q0))) print("Bloch Vector of Message After Random Unitary:") # Prints the Bloch vector of the Message after the random gate b0X, b0Y, b0Z = cirq.bloch_vector_from_state_vector( message.final_state, 0) print("x: ", np.around(b0X, 4), "y: ", np.around(b0Y, 4), "z: ", np.around(b0Z, 4)) # Records the final state of the simulation final_results = sim.simulate(circuit) print("Bloch Sphere of Qubit 2 at Final State:") # Prints the Bloch Sphere of Bob's entangled qubit at the final state b2X, b2Y, b2Z = cirq.bloch_vector_from_state_vector( final_results.final_state, 2) print("x: ", np.around(b2X, 4), "y: ", np.around(b2Y, 4), "z: ", np.around(b2Z, 4)) def make_oracle(q0, q1, secret_function): """ Gates implementing the secret function f(x).""" # coverage: ignore if secret_function[0]: yield [cirq.CNOT(q0, q1), cirq.X(q1)] if secret_function[1]: yield cirq.CNOT(q0, q1) def make_deutsch_circuit(q0, q1, oracle): c = cirq.Circuit() # Initialize qubits. c.append([cirq.X(q1), cirq.H(q1), cirq.H(q0)]) # Query oracle. c.append(oracle) # Measure in X basis. c.append([cirq.H(q0), cirq.measure(q0, key='result')]) return c # Choose qubits to use. q0, q1 = cirq.LineQubit.range(2) # Pick a secret 2-bit function and create a circuit to query the oracle. secret_function = [random.randint(0,1) for _ in range(2)] oracle = make_oracle(q0, q1, secret_function) print('Secret function:\nf(x) = <{}>'.format( ', '.join(str(e) for e in secret_function))) # Embed the oracle into a quantum circuit querying it exactly once. circuit = make_deutsch_circuit(q0, q1, oracle) print('Circuit:') print(circuit) # Simulate the circuit. simulator = cirq.Simulator() result = simulator.run(circuit) print('Result of f(0)⊕f(1):') print(result) def make_qft(qubits): """Generator for the QFT on an arbitrary number of qubits. With four qubits the answer is ---H--@-------@--------@--------------------------------------------- | | | ------@^0.5---+--------+---------H--@-------@------------------------ | | | | --------------@^0.25---+------------@^0.5---+---------H--@----------- | | | -----------------------@^0.125--------------@^0.25-------@^0.5---H--- """ # YOUR CODE HERE def make_qft(qubits): """Generator for the QFT on an arbitrary number of qubits. With four qubits the answer is ---H--@-------@--------@--------------------------------------------- | | | ------@^0.5---+--------+---------H--@-------@------------------------ | | | | --------------@^0.25---+------------@^0.5---+---------H--@----------- | | | -----------------------@^0.125--------------@^0.25-------@^0.5---H--- """ qubits = list(qubits) while len(qubits) > 0: q_head = qubits.pop(0) yield cirq.H(q_head) for i, qubit in enumerate(qubits): yield (cirq.CZ**(1/2**(i+1)))(qubit, q_head) num_qubits = 4 qubits = cirq.LineQubit.range(num_qubits) qft = cirq.Circuit.from_ops(make_qft(qubits)) print(qft) class QFT(cirq.Gate): """Gate for the Quantum Fourier Transformation """ def __init__(self, n_qubits): self.n_qubits = n_qubits def num_qubits(self): return self.n_qubits def _decompose_(self, qubits): # YOUR CODE HERE # How should the gate look in ASCII diagrams? def _circuit_diagram_info_(self, args): return tuple('QFT{}'.format(i) for i in range(self.n_qubits)) class QFT(cirq.Gate): """Gate for the Quantum Fourier Transformation """ def __init__(self, n_qubits): self.n_qubits = n_qubits def num_qubits(self): return self.n_qubits def _decompose_(self, qubits): """Implements the QFT on an arbitrary number of qubits. The circuit for num_qubits = 4 is given by ---H--@-------@--------@--------------------------------------------- | | | ------@^0.5---+--------+---------H--@-------@------------------------ | | | | --------------@^0.25---+------------@^0.5---+---------H--@----------- | | | -----------------------@^0.125--------------@^0.25-------@^0.5---H--- """ qubits = list(qubits) while len(qubits) > 0: q_head = qubits.pop(0) yield cirq.H(q_head) for i, qubit in enumerate(qubits): yield (cirq.CZ**(1/2**(i+1)))(qubit, q_head) # How should the gate look in ASCII diagrams? def _circuit_diagram_info_(self, args): return tuple('QFT{}'.format(i) for i in range(self.n_qubits)) num_qubits = 4 qubits = cirq.LineQubit.range(num_qubits) circuit = cirq.Circuit.from_ops(QFT(num_qubits).on(*qubits)) print(circuit) qft_test = cirq.Circuit.from_ops(make_qft(qubits)) print(qft_test) np.testing.assert_allclose(cirq.unitary(qft_test), cirq.unitary(circuit)) class QFT_inv(cirq.Gate): """Gate for the inverse Quantum Fourier Transformation """ # YOUR CODE HERE class QFT_inv(cirq.Gate): """Gate for the inverse Quantum Fourier Transformation """ def __init__(self, n_qubits): self.n_qubits = n_qubits def num_qubits(self): return self.n_qubits def _decompose_(self, qubits): """Implements the inverse QFT on an arbitrary number of qubits. The circuit for num_qubits = 4 is given by ---H--@-------@--------@--------------------------------------------- | | | ------@^-0.5--+--------+---------H--@-------@------------------------ | | | | --------------@^-0.25--+------------@^-0.5--+---------H--@----------- | | | -----------------------@^-0.125-------------@^-0.25------@^-0.5--H--- """ qubits = list(qubits) while len(qubits) > 0: q_head = qubits.pop(0) yield cirq.H(q_head) for i, qubit in enumerate(qubits): yield (cirq.CZ**(-1/2**(i+1)))(qubit, q_head) def _circuit_diagram_info_(self, args): return tuple('QFT{}^-1'.format(i) for i in range(self.n_qubits)) num_qubits = 2 qubits = cirq.LineQubit.range(num_qubits) circuit = cirq.Circuit.from_ops(QFT(num_qubits).on(*qubits), QFT_inv(num_qubits).on(*qubits)) print(circuit) cirq.unitary(circuit).round(2) num_qubits = 2 qubits = cirq.LineQubit.range(num_qubits) circuit = cirq.Circuit.from_ops(QFT(num_qubits).on(*qubits), QFT_inv(num_qubits).on(*qubits[::-1])) # qubit order reversed print(circuit) cirq.unitary(circuit) theta = 0.234 # Try your own n_bits = 3 # Accuracy of the estimate for theta. Try different values. qubits = cirq.LineQubit.range(n_bits) u_bit = cirq.NamedQubit('u') U = cirq.Z**(2*theta) phase_estimator = cirq.Circuit() phase_estimator.append(cirq.H.on_each(*qubits)) for i, bit in enumerate(qubits): phase_estimator.append(cirq.ControlledGate(U).on(bit,u_bit)**(2**(n_bits-1-i))) print(phase_estimator) phase_estimator.append(QFT_inv(n_bits).on(*qubits)) print(phase_estimator) # Add measurements to the end of the circuit phase_estimator.append(cirq.measure(*qubits, key='m')) # Add gate to change initial state to |1> phase_estimator.insert(0,cirq.X(u_bit)) print(phase_estimator) sim = cirq.Simulator() result = sim.run(phase_estimator, repetitions=10) theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits print(theta_estimates) def phase_estimation(theta, n_bits, n_reps=10): # YOUR CODE HERE return theta_estimates def phase_estimation(theta, n_bits, n_reps=10): qubits = cirq.LineQubit.range(n_bits) u_bit = cirq.NamedQubit('u') U = cirq.Z**(2*theta) # Try out a different gate if you like phase_estimator = cirq.Circuit() phase_estimator.append(cirq.H.on_each(*qubits)) for i, bit in enumerate(qubits): phase_estimator.append(cirq.ControlledGate(U).on(bit,u_bit)**(2**(n_bits-1-i))) phase_estimator.append(QFT_inv(n_bits).on(*qubits)) # Measurement gates phase_estimator.append(cirq.measure(*qubits, key='m')) # Gates to choose initial state for the u_bit. Placing X here chooses the |1> state phase_estimator.insert(0,cirq.X(u_bit)) # Code to simulate measurements sim = cirq.Simulator() result = sim.run(phase_estimator, repetitions=n_reps) # Convert measurements into estimates of theta theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits return theta_estimates phase_estimation(0.234, 10) def phase_estimation(theta, n_bits, n_reps=10): qubits = cirq.LineQubit.range(n_bits) u_bit = cirq.NamedQubit('u') U = cirq.Z**(2*theta) phase_estimator = cirq.Circuit() phase_estimator.append(cirq.H.on_each(*qubits)) for i, bit in enumerate(qubits): phase_estimator.append(cirq.ControlledGate(U).on(bit,u_bit)**(2**(n_bits-1-i))) # Could have used CZ in this example phase_estimator.append(QFT_inv(n_bits).on(*qubits)) phase_estimator.append(cirq.measure(*qubits, key='m')) # Changed the X gate here to an H phase_estimator.insert(0,cirq.H(u_bit)) sim = cirq.Simulator() result = sim.run(phase_estimator, repetitions=n_reps) theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits return theta_estimates phase_estimation(0.234,10) def set_io_qubits(qubit_count): """Add the specified number of input and output qubits.""" input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] output_qubit = cirq.GridQubit(qubit_count, 0) return (input_qubits, output_qubit) def make_oracle(input_qubits, output_qubit, x_bits): """Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}.""" # Make oracle. # for (1, 1) it's just a Toffoli gate # otherwise negate the zero-bits. yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit) yield(cirq.TOFFOLI(input_qubits[0], input_qubits[1], output_qubit)) yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit) def make_grover_circuit(input_qubits, output_qubit, oracle): """Find the value recognized by the oracle in sqrt(N) attempts.""" # For 2 input qubits, that means using Grover operator only once. c = cirq.Circuit() # Initialize qubits. c.append([ cirq.X(output_qubit), cirq.H(output_qubit), cirq.H.on_each(*input_qubits), ]) # Query oracle. c.append(oracle) # Construct Grover operator. c.append(cirq.H.on_each(*input_qubits)) c.append(cirq.X.on_each(*input_qubits)) c.append(cirq.H.on(input_qubits[1])) c.append(cirq.CNOT(input_qubits[0], input_qubits[1])) c.append(cirq.H.on(input_qubits[1])) c.append(cirq.X.on_each(*input_qubits)) c.append(cirq.H.on_each(*input_qubits)) # Measure the result. c.append(cirq.measure(*input_qubits, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) qubit_count = 2 circuit_sample_count = 10 #Set up input and output qubits. (input_qubits, output_qubit) = set_io_qubits(qubit_count) #Choose the x' and make an oracle which can recognize it. x_bits = [random.randint(0, 1) for _ in range(qubit_count)] print('Secret bit sequence: {}'.format(x_bits)) # Make oracle (black box) oracle = make_oracle(input_qubits, output_qubit, x_bits) # Embed the oracle into a quantum circuit implementing Grover's algorithm. circuit = make_grover_circuit(input_qubits, output_qubit, oracle) print('Circuit:') print(circuit) # Sample from the circuit a couple times. simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) print('Sampled results:\n{}'.format(frequencies)) # Check if we actually found the secret value. most_common_bitstring = frequencies.most_common(1)[0][0] print('Most common bitstring: {}'.format(most_common_bitstring)) print('Found a match: {}'.format( most_common_bitstring == bitstring(x_bits)))
https://github.com/divyanshchoubisa/Quantum-Computing-Dynamic-Circuits
divyanshchoubisa
# 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/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#from qiskit_textbook.widgets import dj_widget #dj_widget(size="small", case="balanced") # initialization ####################################################################################################################### qiskit_edit_1 from qiskit import QuantumCircuit, execute, BasicAer from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### import numpy as np options = { 'plot': True, "rotation_error": {'rx':[0.7, 0.5], 'ry':[0.7, 0.4], 'rz':[0.5, 0.5]}, "tsp_model_error": [0.5, 0.8], "thermal_factor": 0.7, "decoherence_factor": 0.8, "depolarization_factor": 0.5, "bell_depolarization_factor": 0.4, "decay_factor": 0.6, } # importing Qiskit #from qiskit import IBMQ, Aer #from qiskit.providers.ibmq import least_busy #from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') # Display circuit dj_circuit.draw() # use local simulator #backend = qiskit.BasicAer.get_backend('qasm_simulator') print('Qasm simulator') sim_backend = BasicAer.get_backend('qasm_simulator') # without noise job = execute(dj_circuit, backend=sim_backend, shots=1024) job_result = job.result() #print(job_result['results'][0]['data']['densitymatrix']) #job_result['results'][0]['data']['ensemble_probability'] job_result print(job_result.get_counts(dj_circuit)) #with noise job1 = execute(dj_circuit, backend=sim_backend, backend_options=options, shots=1024) job_result1 = job1.result() job_result1 print(job_result1.get_counts(dj_circuit)) #print(job_result1['results'][0]['data']['densitymatrix']) #job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result.get_counts(dj_circuit) x= no_noise.keys() y = no_noise.values() plt.bar(x, y, width=0.6, label='No Noise') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities') plt.show() noisy=job_result1.get_counts(dj_circuit) x1 = noisy.keys() y1 = noisy.values() plt.bar(x1, y1, width=0.6, label='Noisy', color='coral') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities Over Noisy data') plt.show() def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() backend = qiskit.BasicAer.get_backend('dm_simulator') job = execute(dj_circuit, backend=backend, shots=1) job_result = job.result() print(job_result['results'][0]['data']['densitymatrix']) ##plot_histogram(answer) ###no histrogram because of single shot in DM simulator # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qiskit-device-benchmarking
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Mirror RB analysis class. """ from typing import List, Union import numpy as np from uncertainties import unumpy as unp from scipy.spatial.distance import hamming import qiskit_experiments.curve_analysis as curve from qiskit_experiments.framework import AnalysisResultData, ExperimentData from qiskit_experiments.data_processing import DataProcessor from qiskit_experiments.data_processing.data_action import DataAction from qiskit_experiments.library.randomized_benchmarking.rb_analysis import RBAnalysis class MirrorRBAnalysis(RBAnalysis): r"""A class to analyze mirror randomized benchmarking experiment. # section: overview This analysis takes a series for Mirror RB curve fitting. From the fit :math:`\alpha` value this analysis estimates the mean entanglement infidelity (EI) and the error per Clifford (EPC), also known as the average gate infidelity (AGI). The EPC (AGI) estimate is obtained using the equation .. math:: EPC = \frac{2^n - 1}{2^n}\left(1 - \alpha\right) where :math:`n` is the number of qubits (width of the circuit). The EI is obtained using the equation .. math:: EI = \frac{4^n - 1}{4^n}\left(1 - \alpha\right) The fit :math:`\alpha` parameter can be fit using one of the following three quantities plotted on the y-axis: Success Probabilities (:math:`p`): The proportion of shots that return the correct bitstring Adjusted Success Probabilities (:math:`p_0`): .. math:: p_0 = \sum_{k = 0}^n \left(-\frac{1}{2}\right)^k h_k where :math:`h_k` is the probability of observing a bitstring of Hamming distance of k from the correct bitstring Effective Polarizations (:math:`S`): .. math:: S = \frac{4^n}{4^n-1}\left(\sum_{k=0}^n\left(-\frac{1}{2}\right)^k h_k\right)-\frac{1}{4^n-1} # section: fit_model The fit is based on the following decay functions: .. math:: F(x) = a \alpha^{x} + b # section: fit_parameters defpar a: desc: Height of decay curve. init_guess: Determined by :math:`1 - b`. bounds: [0, 1] defpar b: desc: Base line. init_guess: Determined by :math:`(1/2)^n` (for success probability) or :math:`(1/4)^n` (for adjusted success probability and effective polarization). bounds: [0, 1] defpar \alpha: desc: Depolarizing parameter. init_guess: Determined by :func:`~rb_decay` with standard RB curve. bounds: [0, 1] # section: reference .. ref_arxiv:: 1 2112.09853 """ @classmethod def _default_options(cls): """Default analysis options. Analysis Options: analyzed_quantity (str): Set the metric to plot on the y-axis. Must be one of "Effective Polarization" (default), "Success Probability", or "Adjusted Success Probability". gate_error_ratio (Optional[Dict[str, float]]): A dictionary with gate name keys and error ratio values used when calculating EPG from the estimated EPC. The default value will use standard gate error ratios. If you don't know accurate error ratio between your basis gates, you can skip analysis of EPGs by setting this options to ``None``. epg_1_qubit (List[AnalysisResult]): Analysis results from previous RB experiments for individual single qubit gates. If this is provided, EPC of 2Q RB is corrected to exclude the depolarization of underlying 1Q channels. """ default_options = super()._default_options() # Set labels of axes default_options.plotter.set_figure_options( xlabel="Clifford Length", ylabel="Effective Polarization", ) # Plot all (adjusted) success probabilities default_options.plot_raw_data = True # Exponential decay parameter default_options.result_parameters = ["alpha"] # Default gate error ratio for calculating EPG default_options.gate_error_ratio = "default" # By default, EPG for single qubits aren't set default_options.epg_1_qubit = None # By default, effective polarization is plotted (see arXiv:2112.09853). We can # also plot success probability or adjusted success probability (see PyGSTi). # Do this by setting options to "Success Probability" or "Adjusted Success Probability" default_options.analyzed_quantity = "Effective Polarization" default_options.set_validator( field="analyzed_quantity", validator_value=[ "Success Probability", "Adjusted Success Probability", "Effective Polarization", ], ) return default_options def _generate_fit_guesses( self, user_opt: curve.FitOptions, curve_data: curve.ScatterTable, ) -> Union[curve.FitOptions, List[curve.FitOptions]]: """Create algorithmic guess with analysis options and curve data. Args: user_opt: Fit options filled with user provided guess and bounds. curve_data: Formatted data collection to fit. Returns: List of fit options that are passed to the fitter function. """ user_opt.bounds.set_if_empty(a=(0, 1), alpha=(0, 1), b=(0, 1)) num_qubits = len(self._physical_qubits) # Initialize guess for baseline and amplitude based on infidelity type b_guess = 1 / 4**num_qubits if self.options.analyzed_quantity == "Success Probability": b_guess = 1 / 2**num_qubits mirror_curve = curve_data.get_subset_of("rb_decay") alpha_mirror = curve.guess.rb_decay(mirror_curve.x, mirror_curve.y, b=b_guess) a_guess = (curve_data.y[0] - b_guess) / (alpha_mirror ** curve_data.x[0]) user_opt.p0.set_if_empty(b=b_guess, a=a_guess, alpha=alpha_mirror) return user_opt def _create_analysis_results( self, fit_data: curve.CurveFitResult, quality: str, **metadata, ) -> List[AnalysisResultData]: """Create analysis results for important fit parameters. Besides the default standard RB parameters, Entanglement Infidelity (EI) is also calculated. Args: fit_data: Fit outcome. quality: Quality of fit outcome. Returns: List of analysis result data. """ outcomes = super()._create_analysis_results(fit_data, quality, **metadata) num_qubits = len(self._physical_qubits) # nrb is calculated for both EPC and EI per the equations in the docstring ei_nrb = 4**num_qubits ei_scale = (ei_nrb - 1) / ei_nrb ei = ei_scale * (1 - fit_data.ufloat_params["alpha"]) outcomes.append( AnalysisResultData( name="EI", value=ei, chisq=fit_data.reduced_chisq, quality=quality, extra=metadata ) ) return outcomes def _initialize(self, experiment_data: ExperimentData): """Initialize curve analysis by setting up the data processor for Mirror RB data. Args: experiment_data: Experiment data to analyze. """ super()._initialize(experiment_data) num_qubits = len(self._physical_qubits) target_bs = [] for circ_result in experiment_data.data(): if circ_result["metadata"]["inverting_pauli_layer"] is True: target_bs.append("0" * num_qubits) else: target_bs.append(circ_result["metadata"]["target"]) self.set_options( data_processor=DataProcessor( input_key="counts", data_actions=[ _ComputeQuantities( analyzed_quantity=self.options.analyzed_quantity, num_qubits=num_qubits, target_bs=target_bs, ) ], ) ) class _ComputeQuantities(DataAction): """Data processing node for computing useful mirror RB quantities from raw results.""" def __init__( self, num_qubits, target_bs, analyzed_quantity: str = "Effective Polarization", validate: bool = True, ): """ Args: num_qubits: Number of qubits. quantity: The quantity to calculate. validate: If set to False the DataAction will not validate its input. """ super().__init__(validate) self._num_qubits = num_qubits self._analyzed_quantity = analyzed_quantity self._target_bs = target_bs def _process(self, data: np.ndarray): # Arrays to store the y-axis data and uncertainties y_data = [] y_data_unc = [] for i, circ_result in enumerate(data): target_bs = self._target_bs[i] # h[k] = proportion of shots that are Hamming distance k away from target bitstring hamming_dists = np.zeros(self._num_qubits + 1) success_prob = 0.0 success_prob_unc = 0.0 for bitstring, count in circ_result.items(): # Compute success probability if self._analyzed_quantity == "Success Probability": if bitstring == target_bs: success_prob = count / sum(circ_result.values()) success_prob_unc = np.sqrt(success_prob * (1 - success_prob)) break else: # Compute hamming distance proportions target_bs_to_list = [int(char) for char in target_bs] actual_bs_to_list = [int(char) for char in bitstring] k = int(round(hamming(target_bs_to_list, actual_bs_to_list) * self._num_qubits)) hamming_dists[k] += count / sum(circ_result.values()) if self._analyzed_quantity == "Success Probability": y_data.append(success_prob) y_data_unc.append(success_prob_unc) continue # Compute hamming distance uncertainties hamming_dist_unc = np.sqrt(hamming_dists * (1 - hamming_dists)) # Compute adjusted success probability and standard deviation adjusted_success_prob = 0.0 adjusted_success_prob_unc = 0.0 for k in range(self._num_qubits + 1): adjusted_success_prob += (-0.5) ** k * hamming_dists[k] adjusted_success_prob_unc += (0.5) ** k * hamming_dist_unc[k] ** 2 adjusted_success_prob_unc = np.sqrt(adjusted_success_prob_unc) if self._analyzed_quantity == "Adjusted Success Probability": y_data.append(adjusted_success_prob) y_data_unc.append(adjusted_success_prob_unc) # Compute effective polarization and standard deviation (arXiv:2112.09853v1) pol_factor = 4**self._num_qubits pol = pol_factor / (pol_factor - 1) * adjusted_success_prob - 1 / (pol_factor - 1) pol_unc = np.sqrt(pol_factor / (pol_factor - 1)) * adjusted_success_prob_unc if self._analyzed_quantity == "Effective Polarization": y_data.append(pol) y_data_unc.append(pol_unc) return unp.uarray(y_data, y_data_unc)
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 import qiskit.tools.apps.optimization num_of_qubits = 2 circuit_depth = 6 num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz ## Previously used for Hydrogen VQE in QISKit implementation # def universal_ansatz(current_params, entangler_map=None): if entangler_map==None: # Which qubits to use (0 to 1 best to avoid qiskit bugs) entangler_map = {1: [0]} return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit_aqua_chemistry import AquaChemistry from qiskit import IBMQ IBMQ.load_accounts() # Input dictionary to configure Qiskit AQUA Chemistry for the chemistry problem. aqua_chemistry_dict = { 'driver': {'name': 'HDF5'}, 'HDF5': {'hdf5_input': '0.7_sto-3g.hdf5'}, 'operator': {'name': 'hamiltonian'}, 'algorithm': {'name': 'VQE'}, 'optimizer': {'name': 'COBYLA'}, 'variational_form': {'name': 'UCCSD'}, 'initial_state': {'name': 'HartreeFock'}, 'backend': {'name': 'statevector_simulator'} } solver = AquaChemistry() result = solver.run(aqua_chemistry_dict) print('Ground state energy: {}'.format(result['energy'])) for line in result['printable']: print(line)
https://github.com/josejad42/quantum_algorithms_and_protocols
josejad42
pip install qiskit pylatexenc qiskit-aer --quiet from qiskit import QuantumCircuit, Aer, transpile from qiskit.visualization import plot_histogram, plot_bloch_multivector from numpy.random import randint from qiskit.visualization import visualize_transition import numpy as np import matplotlib.pyplot as plt qc = QuantumCircuit(1, 1) # Alice prepara o qubit no estado |-> (1 na base de Hadamard) qc.x(0) qc.h(0) qc.s(0) qc.barrier() # Alice envia o qubit para Bob # Bob mede o qubit na base X qc.sdg(0) qc.h(0) qc.measure(0, 0) # Backend display(qc.draw('mpl')) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(qc) plot_h1 = plot_histogram(job.result().get_counts()) plot_h1 qc = QuantumCircuit(1, 1) # Alice prepara o qubit no estado |-> (1 na base de Hadamard) qc.x(0) qc.h(0) qc.barrier() # Alice envia o qubit para Bob # Bob mede o qubit na base X qc.h(0) qc.measure(0, 0) # Backend display(qc.draw('mpl')) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(qc) plot_h1 = plot_histogram(job.result().get_counts()) plot_h1 qc = QuantumCircuit(1,1) # Alice prepara o qubit no estado |-> e envia para Bob qc.x(0) qc.h(0) # Eve intersepta e tenta ler o qubit qc.barrier() qc.measure(0, 0) qc.barrier() # Eve manda a mensagem para Bob # Bob mede o qubit na base X qc.h(0) qc.measure(0,0) # Backend display(qc.draw('mpl')) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(qc) plot_h2 = plot_histogram(job.result().get_counts()) plot_h2 n = 100 alice_bits = randint(2, size=n) print(alice_bits) #Lista representando a base escolhida para encodar cada bit de alice_bits. #0 significa preparar na base Z e 1 significa preparar na base X alice_bases = randint(2, size=n) print(alice_bases) #Função que cria uma lista de QuantumCircuits #Cada um representa um bit da mensagem de Alice def encode_message(bits, bases): message = [] for i in range(n): qc = QuantumCircuit(1,1) if bases[i] == 0: # Prepara qubit na base Z if bits[i] == 0: pass else: qc.x(0) else: # Prepara qubit na base X if bits[i] == 0: qc.h(0) else: qc.x(0) qc.h(0) qc.barrier() message.append(qc) return message #Estamos agora codificando a mensagem de Alice message = encode_message(alice_bits, alice_bases) #Exemplo para o primeiro bit print('bit = %i' % alice_bits[0]) print('basis = %i' % alice_bases[0]) message[0].draw('mpl') #Array representando a base escolhida para medir cada bit de alice_bits. bob_bases = randint(2, size=n) print(bob_bases) #Função que mede cada qubit da mensagem def measure_message(message, bases): backend = Aer.get_backend('aer_simulator') measurements = [] for q in range(n): if bases[q] == 0: # mede na base Z message[q].measure(0,0) if bases[q] == 1: # mede na base X message[q].h(0) message[q].measure(0,0) aer_sim = Aer.get_backend('aer_simulator') result = aer_sim.run(message[q], shots=1, memory=True).result() measured_bit = int(result.get_memory()[0]) measurements.append(measured_bit) return measurements #Estamos agora medindo cada qubit da mensagem de Alice bob_results = measure_message(message, bob_bases) print(bob_results) #primeiro bit message[0].draw('mpl') #segundo bit message[1].draw('mpl') #Função que retorna apenas os qubits em que as bases foram iguais def remove_garbage(a_bases, b_bases, bits): good_bits = [] for q in range(n): if a_bases[q] == b_bases[q]: # If both used the same basis, add # this to the list of 'good' bits good_bits.append(bits[q]) return good_bits #Chave da Alice alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) print(alice_key) #Chave do Bob bob_key = remove_garbage(alice_bases, bob_bases, bob_results) print(bob_key) def sample_bits(bits, selection): sample = [] for i in selection: #usamos o np.mod para garantir que o bit i = np.mod(i, len(bits)) # pop(i) remove o elemento da lista sample.append(bits.pop(i)) return sample sample_size = 15 bit_selection = randint(n, size=sample_size) bob_sample = sample_bits(bob_key, bit_selection) print(" bob_sample = " + str(bob_sample)) alice_sample = sample_bits(alice_key, bit_selection) print("alice_sample = "+ str(alice_sample)) #Verificamos se o protocolo funcionou corretamente sem interferências bob_sample == alice_sample np.random.seed() n = 100 # PASSO 1 alice_bits = randint(2, size=n) # PASSO 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) # PASSO 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) # PASSO 4 alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) # PASSO 5 sample_size = 15 bit_selection = randint(n, size=sample_size) bob_sample = sample_bits(bob_key, bit_selection) print(" bob_sample = " + str(bob_sample)) alice_sample = sample_bits(alice_key, bit_selection) print("alice_sample = "+ str(alice_sample)) # PASSO 1 np.random.seed(seed=3) alice_bits = randint(2, size=n) print(alice_bits) # PASSO 1 np.random.seed(seed=3) alice_bits = randint(2, size=n) # PASSO 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) print(alice_bases) message[0].draw('mpl') # PASSO 1 np.random.seed(seed=3) alice_bits = randint(2, size=n) # PASSO 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) # Interceptação eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) print(intercepted_message) message[0].draw('mpl') # PASSO 1 np.random.seed(seed=3) alice_bits = randint(2, size=n) # PASSO 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interceptação eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) # PASSO 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) message[0].draw('mpl') # PASSO 1 np.random.seed(seed=3) alice_bits = randint(2, size=n) # PASSO 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interceptação eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) # PASSO 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) # PASSO 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) # PASSO 1 np.random.seed(seed=3) alice_bits = randint(2, size=n) # PASSO 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) # Interceptação! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) # PASSO 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) # PASSO 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) # PASSO 5 sample_size = 15 bit_selection = randint(n, size=sample_size) bob_sample = sample_bits(bob_key, bit_selection) print(" bob_sample = " + str(bob_sample)) alice_sample = sample_bits(alice_key, bit_selection) print("alice_sample = "+ str(alice_sample)) #Ao comparar as seleções arbitrárias de qubits de Alice e Bob #Percebemos que elas não são iguais bob_sample == alice_sample
https://github.com/daimurat/qiskit-implementation
daimurat
import matplotlib as plt import numpy import math from qiskit import QuantumCircuit, QuantumRegister, assemble, Aer, BasicAer, execute from qiskit.quantum_info import Statevector, state_fidelity, average_gate_fidelity, process_fidelity, hellinger_fidelity from qiskit.quantum_info.operators import Operator from qiskit.visualization import plot_histogram from qiskit.extensions import XGate import qiskit.tools.jupyter %qiskit_version_table qc = QuantumCircuit(4, 4) qc.draw('mpl') qc = QuantumCircuit(4) qc.draw('mpl') qc = QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(4, 'crl')) qc.draw('mpl') qc = QuantumCircuit([4, 4]) qc.draw('mpl') qc = QuantumCircuit(1,1) qc.ry(3 * math.pi/4, 0) qc.measure(0,0) qc.draw('mpl') qasmsim = Aer.get_backend('qasm_simulator') qobj = assemble(qc) # Assemble circuit into a Qobj that can be run counts = qasmsim.run(qobj).result().get_counts() # Do the simulation, returning the state vector plot_histogram(counts) # Display the output state vector inp_reg = QuantumRegister(2, name='inp') ancilla = QuantumRegister(1, name='anc') qc = QuantumCircuit(inp_reg, ancilla) qc.h(inp_reg[0:2]) qc.x(ancilla[0]) qc.draw('mpl') qc = QuantumCircuit(3, 3) qc.measure([0,1,2], [0,1,2]) qc.draw('mpl') qc = QuantumCircuit(3, 3) qc.measure_all() qc.draw('mpl') bell = QuantumCircuit(2) bell.h(0) bell.x(1) bell.cx(0, 1) bell.draw('mpl') qc = QuantumCircuit(2) v = [1/math.sqrt(2), 0, 0, 1/math.sqrt(2)] qc.initialize(v, [0,1]) simulator = Aer.get_backend('statevector_simulator') result = execute(qc, simulator).result() statevector = result.get_statevector() print(statevector) qc= QuantumCircuit(3, 3) qc.barrier() qc.draw('mpl') qc= QuantumCircuit(3, 3) qc.barrier(qc) qc.draw('mpl') qc= QuantumCircuit(3, 3) qc.barrier(3) qc.draw('mpl') qc = QuantumCircuit(2, 2) qc.h(0) qc.barrier(0) qc.cx(0,1) qc.barrier([0,1]) qc.draw('mpl') print("Circuit depth: ", qc.depth()) qc = QuantumCircuit(3) # Insert code fragment here qasm_sim = Aer.get_backend('qasm_simulator') couple_map = [[0, 1], [1, 2]] job = execute(qc, backend=qasm_sim, shots=1024, coupling_map=couple_map) result = job.result() print(result) qc = QuantumCircuit(3) # Insert code fragment here qasm_sim = Aer.get_backend('ibmq_simulator') couple_map = [[0, 1], [0, 2]] job = execute(qc, loop=1024, coupling_map=couple_map) result = job.result() print(result) qc = QuantumCircuit(3) # Insert code fragment here qasm_sim = Aer.get_backend('qasm_simulator') couple_map = [[0, 1], [1, 2]] job = execute(qc, backend=qasm_sim, repeat=1024, coupling_map=couple_map) result = job.result() print(result) qc = QuantumCircuit(3) # Insert code fragment here qasm_sim = Aer.get_backend('qasm_simulator') couple_map = [[0, 1], [1, 2]] job = execute(backend=qasm_sim, qc, shot=1024, coupling_map=couple_map) result = job.result() print(result) backend = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(3) # insert code here execute(qc, backend, shots=1024, coupling_map=[[0, 1], [1, 2]]) backend = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(3) # insert code here execute(qc, backend, shots=1024, custom_topology=[[0, 1], [2, 3]]) backend = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(3) # insert code here execute(qc, backend, shots=1024, device="qasm_simulator", mode="custom") backend = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(3) # insert code here execute(qc, backend, mode="custom") op = Operator.Xop(0) qc = QuantumCircuit(1) op = Operator([[0, 1]]) qc.append(op) qc_a = QuantumCircuit(1) op_a = Operator(XGate()) qc_a.append(op_a, [0]) state_a = Statevector.from_instruction(qc_a) qc_b = QuantumCircuit(1) op_b = numpy.exp(1j * 0.5) * Operator(XGate()) qc_b.append(op_b, [0]) state_b = Statevector.from_instruction(qc_b) state_fidelity(state_a, state_b) process_fidelity(op_a, op_b) average_gate_fidelity(op_a, op_b) qc = QuantumCircuit(2, 2) qc.x(0) qc.measure([0,1], [0,1]) simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=1000).result() counts = result.get_counts(qc) print(counts)
https://github.com/martian17/qiskit-graph-coloring-hamiltonian
martian17
""" This file is a prototype. Not used. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram import math def multi_toffoli_q(qc, q_controls, q_target, q_ancillas=None): """ N = number of qubits controls = control qubits target = target qubit ancillas = ancilla qubits, len(ancillas) = len(controls) - 2 """ # q_controls = register_to_list(q_controls) # q_ancillas = register_to_list(q_ancillas) if len(q_controls) == 1: qc.cx(q_controls[0], q_target) elif len(q_controls) == 2: qc.ccx(q_controls[0], q_controls[1], q_target) elif len(q_controls) > 2 and (q_ancillas is None or len(q_ancillas) < len(q_controls) - 2): raise Exception('ERROR: need more ancillas for multi_toffoli!') else: multi_toffoli_q(qc, q_controls[:-1], q_ancillas[-1], q_ancillas[:-1]) qc.ccx(q_controls[-1], q_ancillas[-1], q_target) multi_toffoli_q(qc, q_controls[:-1], q_ancillas[-1], q_ancillas[:-1]) def m_gate_for_special_case(): qr = QuantumRegister(7) cr = ClassicalRegister(7) circuit = QuantumCircuit(qr, cr) circuit.x(0) multi_toffoli_q(circuit, [0,1], 6) circuit.x(0) circuit.barrier() circuit.x(1) multi_toffoli_q(circuit, [0,1], 6) circuit.barrier() multi_toffoli_q(circuit, [0,1], 3) circuit.barrier() circuit.x([0,1]) multi_toffoli_q(circuit, [0,1], 2) circuit.x(0) circuit.barrier() circuit.measure(qr, cr) print(circuit) execute_circuit((circuit)) def exists_one_in_column(m, column): for i in range(len(m)): if m[i][column] > 0: return (True, i) return (False, 0) def int_to_bin(num, digit): num_bin = bin(num)[2:] if len(num_bin) < digit: num_bin = '0'* (digit - len(num_bin)) + num_bin return num_bin def one_bits_list(num_bin, b): ''' :param num_bin: binary :param b: '0' or '1' :return: the positions where characters equals b ''' ret = [] for iter, c in enumerate(num_bin[::-1]): if c == b: ret.append(iter) return ret def m_gate_for_general_case(q1, q2, q3, hamiltonian, q_ancilla=None): n = len(q1) c1 = ClassicalRegister(n) c2 = ClassicalRegister(n) c3 = ClassicalRegister(n) m_circuit = QuantumCircuit(q1,q2,q3,q_ancilla,c1,c2,c3) q_ancilla_idx = [i for i in range(3*n+1,4*n-1)] print(m_circuit) for i in range(2**n): exists_nonzero, nonzero_idx = exists_one_in_column(hamiltonian, i) if exists_nonzero: num_bin = int_to_bin(i, n) ones_idx = one_bits_list(num_bin, '0') for idx in ones_idx: m_circuit.x(idx) multi_toffoli_q(m_circuit, [i for i in range(n)], 2*n, q_ancilla_idx) for idx in ones_idx: m_circuit.x(idx) m_circuit.barrier() if exists_nonzero: num_bin = int_to_bin(i, n) ones_idx = one_bits_list(num_bin, '0') nonzero_idx_bin = int_to_bin(nonzero_idx, n) for idx in ones_idx: m_circuit.x(idx) target_list = one_bits_list(nonzero_idx_bin, '1') print(num_bin, ones_idx, nonzero_idx_bin, target_list) for t in target_list: multi_toffoli_q(m_circuit, [i for i in range(n)], n+t, q_ancilla_idx) for idx in ones_idx: m_circuit.x(idx) m_circuit.barrier() m_circuit.measure(q1, c1) m_circuit.measure(q2, c2) m_circuit.measure(q3, c3) def execute_circuit(circuit): backend = Aer.get_backend('qasm_simulator') shots = 1024 results = execute(circuit, backend=backend, shots=shots).results() answer = results.get_counts() r = plot_histogram(answer) r.show() if __name__ == "__main__": hamil = [[0,0,1,0],[0,0,0,1],[1,0,0,0],[0,1,0,0]] # hamil = [ # [0, 2, 0, 0], # [2, 0, 0, 0], # [0, 0, 0, 1], # [0, 0, 1, 0] # ] hamil = [ [0,2,0,0,0,0,0,0], [2,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], ] n = int(math.log2(len(hamil))) q1 = QuantumRegister(n) q2 = QuantumRegister(n) q3 = QuantumRegister(n) q_ancilla = None if n > 2: q_ancilla = QuantumRegister(n-2) m_gate_for_general_case(q1,q2,q3,hamil, q_ancilla)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) 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 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's controlled gate operation.""" import unittest from test import combine import numpy as np from numpy import pi from ddt import ddt, data, unpack from qiskit import QuantumRegister, QuantumCircuit, execute, BasicAer, QiskitError from qiskit.test import QiskitTestCase from qiskit.circuit import ControlledGate, Parameter, Gate from qiskit.circuit.exceptions import CircuitError from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.states import Statevector import qiskit.circuit.add_control as ac from qiskit.transpiler.passes import Unroller from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit from qiskit.quantum_info import Operator from qiskit.circuit.library import ( CXGate, XGate, YGate, ZGate, U1Gate, CYGate, CZGate, CU1Gate, SwapGate, PhaseGate, CCXGate, HGate, RZGate, RXGate, CPhaseGate, RYGate, CRYGate, CRXGate, CSwapGate, UGate, U3Gate, CHGate, CRZGate, CU3Gate, CUGate, SXGate, CSXGate, MSGate, Barrier, RCCXGate, RC3XGate, MCU1Gate, MCXGate, MCXGrayCode, MCXRecursive, MCXVChain, C3XGate, C3SXGate, C4XGate, MCPhaseGate, GlobalPhaseGate, ) from qiskit.circuit._utils import _compute_control_matrix import qiskit.circuit.library.standard_gates as allGates from qiskit.extensions import UnitaryGate from qiskit.circuit.library.standard_gates.multi_control_rotation_gates import _mcsu2_real_diagonal from .gate_utils import _get_free_params @ddt class TestControlledGate(QiskitTestCase): """Tests for controlled gates and the ControlledGate class.""" def test_controlled_x(self): """Test creation of controlled x gate""" self.assertEqual(XGate().control(), CXGate()) def test_controlled_y(self): """Test creation of controlled y gate""" self.assertEqual(YGate().control(), CYGate()) def test_controlled_z(self): """Test creation of controlled z gate""" self.assertEqual(ZGate().control(), CZGate()) def test_controlled_h(self): """Test the creation of a controlled H gate.""" self.assertEqual(HGate().control(), CHGate()) def test_controlled_phase(self): """Test the creation of a controlled U1 gate.""" theta = 0.5 self.assertEqual(PhaseGate(theta).control(), CPhaseGate(theta)) def test_double_controlled_phase(self): """Test the creation of a controlled phase gate.""" theta = 0.5 self.assertEqual(PhaseGate(theta).control(2), MCPhaseGate(theta, 2)) def test_controlled_u1(self): """Test the creation of a controlled U1 gate.""" theta = 0.5 self.assertEqual(U1Gate(theta).control(), CU1Gate(theta)) circ = QuantumCircuit(1) circ.append(U1Gate(theta), circ.qregs[0]) unroller = Unroller(["cx", "u", "p"]) ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control() ctrl_circ = QuantumCircuit(2) ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0]) ctrl_circ = ctrl_circ.decompose().decompose() self.assertEqual(ctrl_circ.size(), 1) def test_controlled_rz(self): """Test the creation of a controlled RZ gate.""" theta = 0.5 self.assertEqual(RZGate(theta).control(), CRZGate(theta)) def test_control_parameters(self): """Test different ctrl_state formats for control function.""" theta = 0.5 self.assertEqual( CRYGate(theta).control(2, ctrl_state="01"), CRYGate(theta).control(2, ctrl_state=1) ) self.assertEqual( CRYGate(theta).control(2, ctrl_state=None), CRYGate(theta).control(2, ctrl_state=3) ) self.assertEqual(CCXGate().control(2, ctrl_state="01"), CCXGate().control(2, ctrl_state=1)) self.assertEqual(CCXGate().control(2, ctrl_state=None), CCXGate().control(2, ctrl_state=3)) def test_controlled_ry(self): """Test the creation of a controlled RY gate.""" theta = 0.5 self.assertEqual(RYGate(theta).control(), CRYGate(theta)) def test_controlled_rx(self): """Test the creation of a controlled RX gate.""" theta = 0.5 self.assertEqual(RXGate(theta).control(), CRXGate(theta)) def test_controlled_u(self): """Test the creation of a controlled U gate.""" theta, phi, lamb = 0.1, 0.2, 0.3 self.assertEqual(UGate(theta, phi, lamb).control(), CUGate(theta, phi, lamb, 0)) def test_controlled_u3(self): """Test the creation of a controlled U3 gate.""" theta, phi, lamb = 0.1, 0.2, 0.3 self.assertEqual(U3Gate(theta, phi, lamb).control(), CU3Gate(theta, phi, lamb)) circ = QuantumCircuit(1) circ.append(U3Gate(theta, phi, lamb), circ.qregs[0]) unroller = Unroller(["cx", "u", "p"]) ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control() ctrl_circ = QuantumCircuit(2) ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0]) ctrl_circ = ctrl_circ.decompose().decompose() self.assertEqual(ctrl_circ.size(), 1) def test_controlled_cx(self): """Test creation of controlled cx gate""" self.assertEqual(CXGate().control(), CCXGate()) def test_controlled_swap(self): """Test creation of controlled swap gate""" self.assertEqual(SwapGate().control(), CSwapGate()) def test_special_cases_equivalent_to_controlled_base_gate(self): """Test that ``ControlledGate`` subclasses for more efficient representations give equivalent matrices and definitions to the naive ``base_gate.control(n)``.""" # Angles used here are not important, we just pick slightly strange values to ensure that # there are no coincidental equivalences. tests = [ (CXGate(), 1), (CCXGate(), 2), (C3XGate(), 3), (C4XGate(), 4), (MCXGate(5), 5), (CYGate(), 1), (CZGate(), 1), (CPhaseGate(np.pi / 7), 1), (MCPhaseGate(np.pi / 7, 2), 2), (CSwapGate(), 1), (CSXGate(), 1), (C3SXGate(), 3), (CHGate(), 1), (CU1Gate(np.pi / 7), 1), (MCU1Gate(np.pi / 7, 2), 2), # `CUGate` takes an extra "global" phase parameter compared to `UGate`, and consequently # is only equal to `base_gate.control()` when this extra phase is 0. (CUGate(np.pi / 7, np.pi / 5, np.pi / 3, 0), 1), (CU3Gate(np.pi / 7, np.pi / 5, np.pi / 3), 1), (CRXGate(np.pi / 7), 1), (CRYGate(np.pi / 7), 1), (CRZGate(np.pi / 7), 1), ] for special_case_gate, n_controls in tests: with self.subTest(gate=special_case_gate.name): naive_operator = Operator(special_case_gate.base_gate.control(n_controls)) # Ensure that both the array form (if the gate overrides `__array__`) and the # circuit-definition form are tested. self.assertTrue(Operator(special_case_gate).equiv(naive_operator)) if not isinstance(special_case_gate, CXGate): # CX is treated like a primitive within Terra, and doesn't have a definition. self.assertTrue(Operator(special_case_gate.definition).equiv(naive_operator)) def test_global_phase_control(self): """Test creation of a GlobalPhaseGate.""" base = GlobalPhaseGate(np.pi / 7) expected_1q = PhaseGate(np.pi / 7) self.assertEqual(Operator(base.control()), Operator(expected_1q)) expected_2q = PhaseGate(np.pi / 7).control() self.assertEqual(Operator(base.control(2)), Operator(expected_2q)) expected_open = QuantumCircuit(1) expected_open.x(0) expected_open.p(np.pi / 7, 0) expected_open.x(0) self.assertEqual(Operator(base.control(ctrl_state=0)), Operator(expected_open)) def test_circuit_append(self): """Test appending a controlled gate to a quantum circuit.""" circ = QuantumCircuit(5) inst = CXGate() circ.append(inst.control(), qargs=[0, 2, 1]) circ.append(inst.control(2), qargs=[0, 3, 1, 2]) circ.append(inst.control().control(), qargs=[0, 3, 1, 2]) # should be same as above self.assertEqual(circ[1].operation, circ[2].operation) self.assertEqual(circ.depth(), 3) self.assertEqual(circ[0].operation.num_ctrl_qubits, 2) self.assertEqual(circ[1].operation.num_ctrl_qubits, 3) self.assertEqual(circ[2].operation.num_ctrl_qubits, 3) self.assertEqual(circ[0].operation.num_qubits, 3) self.assertEqual(circ[1].operation.num_qubits, 4) self.assertEqual(circ[2].operation.num_qubits, 4) for instr in circ: self.assertTrue(isinstance(instr.operation, ControlledGate)) def test_swap_definition_specification(self): """Test the instantiation of a controlled swap gate with explicit definition.""" swap = SwapGate() cswap = ControlledGate( "cswap", 3, [], num_ctrl_qubits=1, definition=swap.definition, base_gate=swap ) self.assertEqual(swap.definition, cswap.definition) def test_multi_controlled_composite_gate(self): """Test a multi controlled composite gate.""" num_ctrl = 3 # create composite gate sub_q = QuantumRegister(2) cgate = QuantumCircuit(sub_q, name="cgate") cgate.h(sub_q[0]) cgate.crz(pi / 2, sub_q[0], sub_q[1]) cgate.swap(sub_q[0], sub_q[1]) cgate.u(0.1, 0.2, 0.3, sub_q[1]) cgate.t(sub_q[0]) num_target = cgate.width() gate = cgate.to_gate() cont_gate = gate.control(num_ctrl_qubits=num_ctrl) control = QuantumRegister(num_ctrl) target = QuantumRegister(num_target) qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat)) def test_single_controlled_composite_gate(self): """Test a singly controlled composite gate.""" num_ctrl = 1 # create composite gate sub_q = QuantumRegister(2) cgate = QuantumCircuit(sub_q, name="cgate") cgate.h(sub_q[0]) cgate.cx(sub_q[0], sub_q[1]) num_target = cgate.width() gate = cgate.to_gate() cont_gate = gate.control(num_ctrl_qubits=num_ctrl) control = QuantumRegister(num_ctrl, "control") target = QuantumRegister(num_target, "target") qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat)) def test_control_open_controlled_gate(self): """Test control(2) vs control.control where inner gate has open controls.""" gate1pre = ZGate().control(1, ctrl_state=0) gate1 = gate1pre.control(1, ctrl_state=1) gate2 = ZGate().control(2, ctrl_state=1) expected = Operator(_compute_control_matrix(ZGate().to_matrix(), 2, ctrl_state=1)) self.assertEqual(expected, Operator(gate1)) self.assertEqual(expected, Operator(gate2)) def test_multi_control_z(self): """Test a multi controlled Z gate.""" qc = QuantumCircuit(1) qc.z(0) ctr_gate = qc.to_gate().control(2) ctr_circ = QuantumCircuit(3) ctr_circ.append(ctr_gate, range(3)) ref_circ = QuantumCircuit(3) ref_circ.h(2) ref_circ.ccx(0, 1, 2) ref_circ.h(2) self.assertEqual(ctr_circ.decompose(), ref_circ) def test_multi_control_u3(self): """Test the matrix representation of the controlled and controlled-controlled U3 gate.""" from qiskit.circuit.library.standard_gates import u3 num_ctrl = 3 # U3 gate params alpha, beta, gamma = 0.2, 0.3, 0.4 u3gate = u3.U3Gate(alpha, beta, gamma) cu3gate = u3.CU3Gate(alpha, beta, gamma) # cnu3 gate cnu3 = u3gate.control(num_ctrl) width = cnu3.num_qubits qr = QuantumRegister(width) qcnu3 = QuantumCircuit(qr) qcnu3.append(cnu3, qr, []) # U3 gate qu3 = QuantumCircuit(1) qu3.append(u3gate, [0]) # CU3 gate qcu3 = QuantumCircuit(2) qcu3.append(cu3gate, [0, 1]) # c-cu3 gate width = 3 qr = QuantumRegister(width) qc_cu3 = QuantumCircuit(qr) c_cu3 = cu3gate.control(1) qc_cu3.append(c_cu3, qr, []) # Circuit unitaries mat_cnu3 = Operator(qcnu3).data mat_u3 = Operator(qu3).data mat_cu3 = Operator(qcu3).data mat_c_cu3 = Operator(qc_cu3).data # Target Controlled-U3 unitary target_cnu3 = _compute_control_matrix(mat_u3, num_ctrl) target_cu3 = np.kron(mat_u3, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) target_c_cu3 = np.kron(mat_cu3, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) tests = [ ("check unitary of u3.control against tensored unitary of u3", target_cu3, mat_cu3), ( "check unitary of cu3.control against tensored unitary of cu3", target_c_cu3, mat_c_cu3, ), ("check unitary of cnu3 against tensored unitary of u3", target_cnu3, mat_cnu3), ] for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): self.assertTrue(matrix_equal(target, decomp, atol=1e-8, rtol=1e-5)) def test_multi_control_u1(self): """Test the matrix representation of the controlled and controlled-controlled U1 gate.""" from qiskit.circuit.library.standard_gates import u1 num_ctrl = 3 # U1 gate params theta = 0.2 u1gate = u1.U1Gate(theta) cu1gate = u1.CU1Gate(theta) # cnu1 gate cnu1 = u1gate.control(num_ctrl) width = cnu1.num_qubits qr = QuantumRegister(width) qcnu1 = QuantumCircuit(qr) qcnu1.append(cnu1, qr, []) # U1 gate qu1 = QuantumCircuit(1) qu1.append(u1gate, [0]) # CU1 gate qcu1 = QuantumCircuit(2) qcu1.append(cu1gate, [0, 1]) # c-cu1 gate width = 3 qr = QuantumRegister(width) qc_cu1 = QuantumCircuit(qr) c_cu1 = cu1gate.control(1) qc_cu1.append(c_cu1, qr, []) job = execute( [qcnu1, qu1, qcu1, qc_cu1], BasicAer.get_backend("unitary_simulator"), basis_gates=["u1", "u2", "u3", "id", "cx"], ) result = job.result() # Circuit unitaries mat_cnu1 = result.get_unitary(0) # trace out ancillae mat_u1 = result.get_unitary(1) mat_cu1 = result.get_unitary(2) mat_c_cu1 = result.get_unitary(3) # Target Controlled-U1 unitary target_cnu1 = _compute_control_matrix(mat_u1, num_ctrl) target_cu1 = np.kron(mat_u1, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) target_c_cu1 = np.kron(mat_cu1, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) tests = [ ("check unitary of u1.control against tensored unitary of u1", target_cu1, mat_cu1), ( "check unitary of cu1.control against tensored unitary of cu1", target_c_cu1, mat_c_cu1, ), ("check unitary of cnu1 against tensored unitary of u1", target_cnu1, mat_cnu1), ] for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): self.log.info(info) self.assertTrue(matrix_equal(target, decomp)) @data(1, 2, 3, 4) def test_multi_controlled_u1_matrix(self, num_controls): """Test the matrix representation of the multi-controlled CU1 gate. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcu1.py """ # registers for the circuit q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] lam = 0.3165354 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) qc.mcp(lam, q_controls, q_target[0]) # for idx in subset: for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) base = PhaseGate(lam).to_matrix() expected = _compute_control_matrix(base, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) @data(1, 2, 3, 4) def test_multi_control_toffoli_matrix_clean_ancillas(self, num_controls): """Test the multi-control Toffoli gate with clean ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ # set up circuit q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) if num_controls > 2: num_ancillas = num_controls - 2 q_ancillas = QuantumRegister(num_controls) qc.add_register(q_ancillas) else: num_ancillas = 0 q_ancillas = None # apply hadamard on control qubits and toffoli gate qc.mct(q_controls, q_target[0], q_ancillas, mode="basic") # execute the circuit and obtain statevector result backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) # compare to expectation if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected)) @data(1, 2, 3, 4, 5) def test_multi_control_toffoli_matrix_basic_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (basic-dirty-ancilla). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) q_ancillas = None if num_controls <= 2: num_ancillas = 0 else: num_ancillas = num_controls - 2 q_ancillas = QuantumRegister(num_ancillas) qc.add_register(q_ancillas) qc.mct(q_controls, q_target[0], q_ancillas, mode="basic-dirty-ancilla") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) @data(1, 2, 3, 4, 5) def test_multi_control_toffoli_matrix_advanced_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (advanced). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) q_ancillas = None if num_controls <= 4: num_ancillas = 0 else: num_ancillas = 1 q_ancillas = QuantumRegister(num_ancillas) qc.add_register(q_ancillas) qc.mct(q_controls, q_target[0], q_ancillas, mode="advanced") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) @data(1, 2, 3) def test_multi_control_toffoli_matrix_noancilla_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (noancilla). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) qc.mct(q_controls, q_target[0], None, mode="noancilla") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) def test_mcsu2_real_diagonal(self): """Test mcsu2_real_diagonal""" num_ctrls = 6 theta = 0.3 ry_matrix = RYGate(theta).to_matrix() qc = _mcsu2_real_diagonal(ry_matrix, num_ctrls) mcry_matrix = _compute_control_matrix(ry_matrix, 6) self.assertTrue(np.allclose(mcry_matrix, Operator(qc).to_matrix())) @combine(num_controls=[1, 2, 4], base_gate_name=["x", "y", "z"], use_basis_gates=[True, False]) def test_multi_controlled_rotation_gate_matrices( self, num_controls, base_gate_name, use_basis_gates ): """Test the multi controlled rotation gates without ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) # call mcrx/mcry/mcrz if base_gate_name == "y": qc.mcry( theta, q_controls, q_target[0], None, mode="noancilla", use_basis_gates=use_basis_gates, ) else: # case 'x' or 'z' only support the noancilla mode and do not have this keyword getattr(qc, "mcr" + base_gate_name)( theta, q_controls, q_target[0], use_basis_gates=use_basis_gates ) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) if use_basis_gates: with self.subTest(msg="check only basis gates used"): gates_used = set(qc.count_ops().keys()) self.assertTrue(gates_used.issubset({"x", "u", "p", "cx"})) backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) if base_gate_name == "x": rot_mat = RXGate(theta).to_matrix() elif base_gate_name == "y": rot_mat = RYGate(theta).to_matrix() else: # case 'z' rot_mat = RZGate(theta).to_matrix() expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) @combine(num_controls=[1, 2, 4], use_basis_gates=[True, False]) def test_multi_controlled_y_rotation_matrix_basic_mode(self, num_controls, use_basis_gates): """Test the multi controlled Y rotation using the mode 'basic'. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ # get the number of required ancilla qubits if num_controls <= 2: num_ancillas = 0 else: num_ancillas = num_controls - 2 q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi if num_ancillas > 0: q_ancillas = QuantumRegister(num_ancillas) qc = QuantumCircuit(q_controls, q_target, q_ancillas) else: qc = QuantumCircuit(q_controls, q_target) q_ancillas = None for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) qc.mcry( theta, q_controls, q_target[0], q_ancillas, mode="basic", use_basis_gates=use_basis_gates, ) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) rot_mat = RYGate(theta).to_matrix() backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) def test_mcry_defaults_to_vchain(self): """Test mcry defaults to the v-chain mode if sufficient work qubits are provided.""" circuit = QuantumCircuit(5) control_qubits = circuit.qubits[:3] target_qubit = circuit.qubits[3] additional_qubits = circuit.qubits[4:] circuit.mcry(0.2, control_qubits, target_qubit, additional_qubits) # If the v-chain mode is selected, all qubits are used. If the noancilla mode would be # selected, the bottom qubit would remain unused. dag = circuit_to_dag(circuit) self.assertEqual(len(list(dag.idle_wires())), 0) @data(1, 2) def test_mcx_gates_yield_explicit_gates(self, num_ctrl_qubits): """Test the creating a MCX gate yields the explicit definition if we know it.""" cls = MCXGate(num_ctrl_qubits).__class__ explicit = {1: CXGate, 2: CCXGate} self.assertEqual(cls, explicit[num_ctrl_qubits]) @data(1, 2, 3, 4) def test_mcxgraycode_gates_yield_explicit_gates(self, num_ctrl_qubits): """Test creating an mcx gate calls MCXGrayCode and yeilds explicit definition.""" qc = QuantumCircuit(num_ctrl_qubits + 1) qc.mcx(list(range(num_ctrl_qubits)), [num_ctrl_qubits]) explicit = {1: CXGate, 2: CCXGate, 3: C3XGate, 4: C4XGate} self.assertEqual(type(qc[0].operation), explicit[num_ctrl_qubits]) @data(3, 4, 5, 8) def test_mcx_gates(self, num_ctrl_qubits): """Test the mcx gates.""" backend = BasicAer.get_backend("statevector_simulator") reference = np.zeros(2 ** (num_ctrl_qubits + 1)) reference[-1] = 1 for gate in [ MCXGrayCode(num_ctrl_qubits), MCXRecursive(num_ctrl_qubits), MCXVChain(num_ctrl_qubits, False), MCXVChain(num_ctrl_qubits, True), ]: with self.subTest(gate=gate): circuit = QuantumCircuit(gate.num_qubits) if num_ctrl_qubits > 0: circuit.x(list(range(num_ctrl_qubits))) circuit.append(gate, list(range(gate.num_qubits)), []) statevector = execute(circuit, backend).result().get_statevector() # account for ancillas if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: corrected = np.zeros(2 ** (num_ctrl_qubits + 1), dtype=complex) for i, statevector_amplitude in enumerate(statevector): i = int(bin(i)[2:].zfill(circuit.num_qubits)[gate.num_ancilla_qubits :], 2) corrected[i] += statevector_amplitude statevector = corrected np.testing.assert_array_almost_equal(statevector.real, reference) @data(1, 2, 3, 4) def test_inverse_x(self, num_ctrl_qubits): """Test inverting the controlled X gate.""" cnx = XGate().control(num_ctrl_qubits) inv_cnx = cnx.inverse() result = Operator(cnx).compose(Operator(inv_cnx)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3) def test_inverse_gate(self, num_ctrl_qubits): """Test inverting a controlled gate based on a circuit definition.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.rx(np.pi / 4, [0, 1, 2]) gate = qc.to_gate() cgate = gate.control(num_ctrl_qubits) inv_cgate = cgate.inverse() result = Operator(cgate).compose(Operator(inv_cgate)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3) def test_inverse_circuit(self, num_ctrl_qubits): """Test inverting a controlled gate based on a circuit definition.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.rx(np.pi / 4, [0, 1, 2]) cqc = qc.control(num_ctrl_qubits) cqc_inv = cqc.inverse() result = Operator(cqc).compose(Operator(cqc_inv)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3, 4, 5) def test_controlled_unitary(self, num_ctrl_qubits): """Test the matrix data of an Operator, which is based on a controlled gate.""" num_target = 1 q_target = QuantumRegister(num_target) qc1 = QuantumCircuit(q_target) # for h-rx(pi/2) theta, phi, lamb = 1.57079632679490, 0.0, 4.71238898038469 qc1.u(theta, phi, lamb, q_target[0]) base_gate = qc1.to_gate() # get UnitaryGate version of circuit base_op = Operator(qc1) base_mat = base_op.data cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(is_unitary_matrix(base_mat)) self.assertTrue(matrix_equal(cop_mat, test_op.data)) @data(1, 2, 3, 4, 5) def test_controlled_random_unitary(self, num_ctrl_qubits): """Test the matrix data of an Operator based on a random UnitaryGate.""" num_target = 2 base_gate = random_unitary(2**num_target).to_instruction() base_mat = base_gate.to_matrix() cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(matrix_equal(cop_mat, test_op.data)) @combine(num_ctrl_qubits=[1, 2, 3], ctrl_state=[0, None]) def test_open_controlled_unitary_z(self, num_ctrl_qubits, ctrl_state): """Test that UnitaryGate with control returns params.""" umat = np.array([[1, 0], [0, -1]]) ugate = UnitaryGate(umat) cugate = ugate.control(num_ctrl_qubits, ctrl_state=ctrl_state) ref_mat = _compute_control_matrix(umat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cugate), Operator(ref_mat)) def test_controlled_controlled_rz(self): """Test that UnitaryGate with control returns params.""" qc = QuantumCircuit(1) qc.rz(0.2, 0) controlled = QuantumCircuit(2) controlled.compose(qc.control(), inplace=True) self.assertEqual(Operator(controlled), Operator(CRZGate(0.2))) self.assertEqual(Operator(controlled), Operator(RZGate(0.2).control())) def test_controlled_controlled_unitary(self): """Test that global phase in iso decomposition of unitary is handled.""" umat = np.array([[1, 0], [0, -1]]) ugate = UnitaryGate(umat) cugate = ugate.control() ccugate = cugate.control() ccugate2 = ugate.control(2) ref_mat = _compute_control_matrix(umat, 2) self.assertTrue(Operator(ccugate2).equiv(Operator(ref_mat))) self.assertTrue(Operator(ccugate).equiv(Operator(ccugate2))) @data(1, 2, 3) def test_open_controlled_unitary_matrix(self, num_ctrl_qubits): """test open controlled unitary matrix""" # verify truth table num_target_qubits = 2 num_qubits = num_ctrl_qubits + num_target_qubits target_op = Operator(XGate()) for i in range(num_target_qubits - 1): target_op = target_op.tensor(XGate()) for i in range(2**num_qubits): input_bitstring = bin(i)[2:].zfill(num_qubits) input_target = input_bitstring[0:num_target_qubits] input_ctrl = input_bitstring[-num_ctrl_qubits:] phi = Statevector.from_label(input_bitstring) cop = Operator( _compute_control_matrix(target_op.data, num_ctrl_qubits, ctrl_state=input_ctrl) ) for j in range(2**num_qubits): output_bitstring = bin(j)[2:].zfill(num_qubits) output_target = output_bitstring[0:num_target_qubits] output_ctrl = output_bitstring[-num_ctrl_qubits:] psi = Statevector.from_label(output_bitstring) cxout = np.dot(phi.data, psi.evolve(cop).data) if input_ctrl == output_ctrl: # flip the target bits cond_output = "".join([str(int(not int(a))) for a in input_target]) else: cond_output = input_target if cxout == 1: self.assertTrue((output_ctrl == input_ctrl) and (output_target == cond_output)) else: self.assertTrue( ((output_ctrl == input_ctrl) and (output_target != cond_output)) or output_ctrl != input_ctrl ) def test_open_control_cx_unrolling(self): """test unrolling of open control gates when gate is in basis""" qc = QuantumCircuit(2) qc.cx(0, 1, ctrl_state=0) dag = circuit_to_dag(qc) unroller = Unroller(["u3", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) ref_circuit = QuantumCircuit(2) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) ref_circuit.cx(0, 1) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) self.assertEqual(uqc, ref_circuit) def test_open_control_cy_unrolling(self): """test unrolling of open control gates when gate is in basis""" qc = QuantumCircuit(2) qc.cy(0, 1, ctrl_state=0) dag = circuit_to_dag(qc) unroller = Unroller(["u3", "cy"]) uqc = dag_to_circuit(unroller.run(dag)) ref_circuit = QuantumCircuit(2) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) ref_circuit.cy(0, 1) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) self.assertEqual(uqc, ref_circuit) def test_open_control_ccx_unrolling(self): """test unrolling of open control gates when gate is in basis""" qreg = QuantumRegister(3) qc = QuantumCircuit(qreg) ccx = CCXGate(ctrl_state=0) qc.append(ccx, [0, 1, 2]) dag = circuit_to_dag(qc) unroller = Unroller(["x", "ccx"]) unrolled_dag = unroller.run(dag) # ┌───┐ ┌───┐ # q0_0: ┤ X ├──■──┤ X ├ # ├───┤ │ ├───┤ # q0_1: ┤ X ├──■──┤ X ├ # └───┘┌─┴─┐└───┘ # q0_2: ─────┤ X ├───── # └───┘ ref_circuit = QuantumCircuit(qreg) ref_circuit.x(qreg[0]) ref_circuit.x(qreg[1]) ref_circuit.ccx(qreg[0], qreg[1], qreg[2]) ref_circuit.x(qreg[0]) ref_circuit.x(qreg[1]) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_ccx_ctrl_state_consistency(self): """Test the consistency of parameters ctrl_state in CCX See issue: https://github.com/Qiskit/qiskit-terra/issues/6465 """ qreg = QuantumRegister(3) qc = QuantumCircuit(qreg) qc.ccx(qreg[0], qreg[1], qreg[2], ctrl_state=0) ref_circuit = QuantumCircuit(qreg) ccx = CCXGate(ctrl_state=0) ref_circuit.append(ccx, [qreg[0], qreg[1], qreg[2]]) self.assertEqual(qc, ref_circuit) def test_open_control_composite_unrolling(self): """test unrolling of open control gates when gate is in basis""" # create composite gate qreg = QuantumRegister(2) qcomp = QuantumCircuit(qreg, name="bell") qcomp.h(qreg[0]) qcomp.cx(qreg[0], qreg[1]) bell = qcomp.to_gate() # create controlled composite gate cqreg = QuantumRegister(3) qc = QuantumCircuit(cqreg) qc.append(bell.control(ctrl_state=0), qc.qregs[0][:]) dag = circuit_to_dag(qc) unroller = Unroller(["x", "u1", "cbell"]) unrolled_dag = unroller.run(dag) # create reference circuit ref_circuit = QuantumCircuit(cqreg) ref_circuit.x(cqreg[0]) ref_circuit.append(bell.control(), [cqreg[0], cqreg[1], cqreg[2]]) ref_circuit.x(cqreg[0]) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) @data(*ControlledGate.__subclasses__()) def test_standard_base_gate_setting(self, gate_class): """Test all gates in standard extensions which are of type ControlledGate and have a base gate setting. """ num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * i for i in range(num_free_params)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 base_gate = gate_class(*free_params) cgate = base_gate.control() # the base gate of CU is U (3 params), the base gate of CCU is CU (4 params) if gate_class == CUGate: self.assertListEqual(cgate.base_gate.params[:3], base_gate.base_gate.params[:3]) else: self.assertEqual(base_gate.base_gate, cgate.base_gate) @combine( gate=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)], num_ctrl_qubits=[1, 2], ctrl_state=[None, 0, 1], ) def test_all_inverses(self, gate, num_ctrl_qubits, ctrl_state): """Test all gates in standard extensions except those that cannot be controlled or are being deprecated. """ if not (issubclass(gate, ControlledGate) or issubclass(gate, allGates.IGate)): # only verify basic gates right now, as already controlled ones # will generate differing definitions try: numargs = len(_get_free_params(gate)) args = [2] * numargs gate = gate(*args) self.assertEqual( gate.inverse().control(num_ctrl_qubits, ctrl_state=ctrl_state), gate.control(num_ctrl_qubits, ctrl_state=ctrl_state).inverse(), ) except AttributeError: # skip gates that do not have a control attribute (e.g. barrier) pass @data(2, 3) def test_relative_phase_toffoli_gates(self, num_ctrl_qubits): """Test the relative phase Toffoli gates. This test compares the matrix representation of the relative phase gate classes (i.e. RCCXGate().to_matrix()), the matrix obtained from the unitary simulator, and the exact version of the gate as obtained through `_compute_control_matrix`. """ # get target matrix (w/o relative phase) base_mat = XGate().to_matrix() target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) # build the matrix for the relative phase toffoli using the unitary simulator circuit = QuantumCircuit(num_ctrl_qubits + 1) if num_ctrl_qubits == 2: circuit.rccx(0, 1, 2) else: # num_ctrl_qubits == 3: circuit.rcccx(0, 1, 2, 3) simulator = BasicAer.get_backend("unitary_simulator") simulated_mat = execute(circuit, simulator).result().get_unitary() # get the matrix representation from the class itself if num_ctrl_qubits == 2: repr_mat = RCCXGate().to_matrix() else: # num_ctrl_qubits == 3: repr_mat = RC3XGate().to_matrix() # test up to phase # note, that all entries may have an individual phase! (as opposed to a global phase) self.assertTrue(matrix_equal(np.abs(simulated_mat), target_mat)) # compare simulated matrix with the matrix representation provided by the class self.assertTrue(matrix_equal(simulated_mat, repr_mat)) def test_open_controlled_gate(self): """ Test controlled gates with control on '0' """ base_gate = XGate() base_mat = base_gate.to_matrix() num_ctrl_qubits = 3 ctrl_state = 5 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = None cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = 0 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = 7 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = "110" cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) def test_open_controlled_gate_raises(self): """ Test controlled gates with open controls raises if ctrl_state isn't allowed. """ base_gate = XGate() num_ctrl_qubits = 3 with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state=-1) with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state=2**num_ctrl_qubits) with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state="201") def test_base_gate_params_reference(self): """ Test all gates in standard extensions which are of type ControlledGate and have a base gate setting have params which reference the one in their base gate. """ num_ctrl_qubits = 1 for gate_class in ControlledGate.__subclasses__(): with self.subTest(i=repr(gate_class)): num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * (i + 1) for i in range(num_free_params)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 base_gate = gate_class(*free_params) if base_gate.params: cgate = base_gate.control(num_ctrl_qubits) self.assertIs(cgate.base_gate.params, cgate.params) def test_assign_parameters(self): """Test assigning parameters to quantum circuit with controlled gate.""" qc = QuantumCircuit(2, name="assign") ptest = Parameter("p") gate = CRYGate(ptest) qc.append(gate, [0, 1]) subs1, subs2 = {ptest: Parameter("a")}, {ptest: Parameter("b")} bound1 = qc.assign_parameters(subs1, inplace=False) bound2 = qc.assign_parameters(subs2, inplace=False) self.assertEqual(qc.parameters, {ptest}) self.assertEqual(bound1.parameters, {subs1[ptest]}) self.assertEqual(bound2.parameters, {subs2[ptest]}) @data(-1, 0, 1.4, "1", 4, 10) def test_improper_num_ctrl_qubits(self, num_ctrl_qubits): """ Test improperly specified num_ctrl_qubits. """ num_qubits = 4 with self.assertRaises(CircuitError): ControlledGate( name="cgate", num_qubits=num_qubits, params=[], num_ctrl_qubits=num_ctrl_qubits ) def test_improper_num_ctrl_qubits_base_gate(self): """Test that the allowed number of control qubits takes the base gate into account.""" with self.assertRaises(CircuitError): ControlledGate( name="cx?", num_qubits=2, params=[], num_ctrl_qubits=2, base_gate=XGate() ) self.assertIsInstance( ControlledGate( name="cx?", num_qubits=2, params=[], num_ctrl_qubits=1, base_gate=XGate() ), ControlledGate, ) self.assertIsInstance( ControlledGate( name="p", num_qubits=1, params=[np.pi], num_ctrl_qubits=1, base_gate=Gate("gphase", 0, [np.pi]), ), ControlledGate, ) def test_open_controlled_equality(self): """ Test open controlled gates are equal if their base gates and control states are equal. """ self.assertEqual(XGate().control(1), XGate().control(1)) self.assertNotEqual(XGate().control(1), YGate().control(1)) self.assertNotEqual(XGate().control(1), XGate().control(2)) self.assertEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="0")) self.assertNotEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="1")) def test_cx_global_phase(self): """ Test controlling CX with global phase """ theta = pi / 2 circ = QuantumCircuit(2, global_phase=theta) circ.cx(0, 1) cx = circ.to_gate() self.assertNotEqual(Operator(CXGate()), Operator(cx)) ccx = cx.control(1) base_mat = Operator(cx).data target = _compute_control_matrix(base_mat, 1) self.assertEqual(Operator(ccx), Operator(target)) expected = QuantumCircuit(*ccx.definition.qregs) expected.ccx(0, 1, 2) expected.p(theta, 0) self.assertEqual(ccx.definition, expected) @data(1, 2) def test_controlled_global_phase(self, num_ctrl_qubits): """ Test controlled global phase on base gate. """ theta = pi / 4 circ = QuantumCircuit(2, global_phase=theta) base_gate = circ.to_gate() base_mat = Operator(base_gate).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) cgate = base_gate.control(num_ctrl_qubits) ccirc = circ.control(num_ctrl_qubits) self.assertEqual(Operator(cgate), Operator(target)) self.assertEqual(Operator(ccirc), Operator(target)) @data(1, 2) def test_rz_composite_global_phase(self, num_ctrl_qubits): """ Test controlling CX with global phase """ theta = pi / 4 circ = QuantumCircuit(2, global_phase=theta) circ.rz(0.1, 0) circ.rz(0.2, 1) ccirc = circ.control(num_ctrl_qubits) base_gate = circ.to_gate() cgate = base_gate.control(num_ctrl_qubits) base_mat = Operator(base_gate).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertEqual(Operator(cgate), Operator(target)) self.assertEqual(Operator(ccirc), Operator(target)) @data(1, 2) def test_nested_global_phase(self, num_ctrl_qubits): """ Test controlling a gate with nested global phase. """ theta = pi / 4 circ = QuantumCircuit(1, global_phase=theta) circ.z(0) v = circ.to_gate() qc = QuantumCircuit(1) qc.append(v, [0]) ctrl_qc = qc.control(num_ctrl_qubits) base_mat = Operator(qc).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertEqual(Operator(ctrl_qc), Operator(target)) @data(1, 2) def test_control_zero_operand_gate(self, num_ctrl_qubits): """Test that a zero-operand gate (such as a make-shift global-phase gate) can be controlled.""" gate = QuantumCircuit(global_phase=np.pi).to_gate() controlled = gate.control(num_ctrl_qubits) self.assertIsInstance(controlled, ControlledGate) self.assertEqual(controlled.num_ctrl_qubits, num_ctrl_qubits) self.assertEqual(controlled.num_qubits, num_ctrl_qubits) target = np.eye(2**num_ctrl_qubits, dtype=np.complex128) target.flat[-1] = -1 self.assertEqual(Operator(controlled), Operator(target)) @ddt class TestOpenControlledToMatrix(QiskitTestCase): """Test controlled_gates implementing to_matrix work with ctrl_state""" @combine(gate_class=ControlledGate.__subclasses__(), ctrl_state=[0, None]) def test_open_controlled_to_matrix(self, gate_class, ctrl_state): """Test open controlled to_matrix.""" num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * i for i in range(1, num_free_params + 1)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 cgate = gate_class(*free_params) cgate.ctrl_state = ctrl_state base_mat = Operator(cgate.base_gate).data if gate_class == CUGate: # account for global phase base_mat = np.array(base_mat) * np.exp(1j * cgate.params[3]) target = _compute_control_matrix(base_mat, cgate.num_ctrl_qubits, ctrl_state=ctrl_state) try: actual = cgate.to_matrix() except CircuitError as cerr: self.skipTest(str(cerr)) self.assertTrue(np.allclose(actual, target)) @ddt class TestSingleControlledRotationGates(QiskitTestCase): """Test the controlled rotation gates controlled on one qubit.""" from qiskit.circuit.library.standard_gates import u1, rx, ry, rz num_ctrl = 2 num_target = 1 theta = pi / 2 gu1 = u1.U1Gate(theta) grx = rx.RXGate(theta) gry = ry.RYGate(theta) grz = rz.RZGate(theta) ugu1 = ac._unroll_gate(gu1, ["p", "u", "cx"]) ugrx = ac._unroll_gate(grx, ["p", "u", "cx"]) ugry = ac._unroll_gate(gry, ["p", "u", "cx"]) ugrz = ac._unroll_gate(grz, ["p", "u", "cx"]) ugrz.params = grz.params cgu1 = ugu1.control(num_ctrl) cgrx = ugrx.control(num_ctrl) cgry = ugry.control(num_ctrl) cgrz = ugrz.control(num_ctrl) @data((gu1, cgu1), (grx, cgrx), (gry, cgry), (grz, cgrz)) @unpack def test_single_controlled_rotation_gates(self, gate, cgate): """Test the controlled rotation gates controlled on one qubit.""" if gate.name == "rz": iden = Operator.from_label("I") zgen = Operator.from_label("Z") op_mat = (np.cos(0.5 * self.theta) * iden - 1j * np.sin(0.5 * self.theta) * zgen).data else: op_mat = Operator(gate).data ref_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, self.num_ctrl) self.assertTrue(matrix_equal(cop_mat, ref_mat)) cqc = QuantumCircuit(self.num_ctrl + self.num_target) cqc.append(cgate, cqc.qregs[0]) dag = circuit_to_dag(cqc) unroller = Unroller(["u", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) self.log.info("%s gate count: %d", cgate.name, uqc.size()) self.log.info("\n%s", str(uqc)) # these limits could be changed if gate.name == "ry": self.assertLessEqual(uqc.size(), 32, f"\n{uqc}") elif gate.name == "rz": self.assertLessEqual(uqc.size(), 43, f"\n{uqc}") else: self.assertLessEqual(uqc.size(), 20, f"\n{uqc}") def test_composite(self): """Test composite gate count.""" qreg = QuantumRegister(self.num_ctrl + self.num_target) qc = QuantumCircuit(qreg, name="composite") qc.append(self.grx.control(self.num_ctrl), qreg) qc.append(self.gry.control(self.num_ctrl), qreg) qc.append(self.gry, qreg[0 : self.gry.num_qubits]) qc.append(self.grz.control(self.num_ctrl), qreg) dag = circuit_to_dag(qc) unroller = Unroller(["u", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) self.log.info("%s gate count: %d", uqc.name, uqc.size()) self.assertLessEqual(uqc.size(), 96, f"\n{uqc}") # this limit could be changed @ddt class TestControlledStandardGates(QiskitTestCase): """Tests for control standard gates.""" @combine( num_ctrl_qubits=[1, 2, 3], gate_class=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)], ) def test_controlled_standard_gates(self, num_ctrl_qubits, gate_class): """Test controlled versions of all standard gates.""" theta = pi / 2 ctrl_state_ones = 2**num_ctrl_qubits - 1 ctrl_state_zeros = 0 ctrl_state_mixed = ctrl_state_ones >> int(num_ctrl_qubits / 2) numargs = len(_get_free_params(gate_class)) args = [theta] * numargs if gate_class in [MSGate, Barrier]: args[0] = 2 elif gate_class in [MCU1Gate, MCPhaseGate]: args[1] = 2 elif issubclass(gate_class, MCXGate): args = [5] gate = gate_class(*args) for ctrl_state in (ctrl_state_ones, ctrl_state_zeros, ctrl_state_mixed): with self.subTest(i=f"{gate_class.__name__}, ctrl_state={ctrl_state}"): if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: # skip matrices that include ancilla qubits continue try: cgate = gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) except (AttributeError, QiskitError): # 'object has no attribute "control"' # skipping Id and Barrier continue base_mat = Operator(gate).data target_mat = _compute_control_matrix( base_mat, num_ctrl_qubits, ctrl_state=ctrl_state ) self.assertEqual(Operator(cgate), Operator(target_mat)) @ddt class TestParameterCtrlState(QiskitTestCase): """Test gate equality with ctrl_state parameter.""" @data( (RXGate(0.5), CRXGate(0.5)), (RYGate(0.5), CRYGate(0.5)), (RZGate(0.5), CRZGate(0.5)), (XGate(), CXGate()), (YGate(), CYGate()), (ZGate(), CZGate()), (U1Gate(0.5), CU1Gate(0.5)), (PhaseGate(0.5), CPhaseGate(0.5)), (SwapGate(), CSwapGate()), (HGate(), CHGate()), (U3Gate(0.1, 0.2, 0.3), CU3Gate(0.1, 0.2, 0.3)), (UGate(0.1, 0.2, 0.3), CUGate(0.1, 0.2, 0.3, 0)), ) @unpack def test_ctrl_state_one(self, gate, controlled_gate): """Test controlled gates with ctrl_state See https://github.com/Qiskit/qiskit-terra/pull/4025 """ self.assertEqual( Operator(gate.control(1, ctrl_state="1")), Operator(controlled_gate.to_matrix()) ) @ddt class TestControlledGateLabel(QiskitTestCase): """Tests for controlled gate labels.""" gates_and_args = [ (XGate, []), (YGate, []), (ZGate, []), (HGate, []), (CXGate, []), (CCXGate, []), (C3XGate, []), (C3SXGate, []), (C4XGate, []), (MCXGate, [5]), (PhaseGate, [0.1]), (U1Gate, [0.1]), (CYGate, []), (CZGate, []), (CPhaseGate, [0.1]), (CU1Gate, [0.1]), (SwapGate, []), (SXGate, []), (CSXGate, []), (CCXGate, []), (RZGate, [0.1]), (RXGate, [0.1]), (RYGate, [0.1]), (CRYGate, [0.1]), (CRXGate, [0.1]), (CSwapGate, []), (UGate, [0.1, 0.2, 0.3]), (U3Gate, [0.1, 0.2, 0.3]), (CHGate, []), (CRZGate, [0.1]), (CUGate, [0.1, 0.2, 0.3, 0.4]), (CU3Gate, [0.1, 0.2, 0.3]), (MSGate, [5, 0.1]), (RCCXGate, []), (RC3XGate, []), (MCU1Gate, [0.1, 1]), (MCXGate, [5]), ] @data(*gates_and_args) @unpack def test_control_label(self, gate, args): """Test gate(label=...).control(label=...)""" cgate = gate(*args, label="a gate").control(label="a controlled gate") self.assertEqual(cgate.label, "a controlled gate") self.assertEqual(cgate.base_gate.label, "a gate") @data(*gates_and_args) @unpack def test_control_label_1(self, gate, args): """Test gate(label=...).control(1, label=...)""" cgate = gate(*args, label="a gate").control(1, label="a controlled gate") self.assertEqual(cgate.label, "a controlled gate") self.assertEqual(cgate.base_gate.label, "a gate") if __name__ == "__main__": unittest.main()
https://github.com/mballarin97/mps_qnn
mballarin97
import sys sys.path.append('../') from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\ sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\ sampleCircuitF from entanglement import Ent import warnings warnings.filterwarnings('ignore') labels = [ 'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3', 'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F' ] samplers = [ sampleCircuitA, sampleCircuitB1, sampleCircuitB2, sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE, sampleCircuitF ] q = 4 for layer in range(1, 4): print(f'qubtis: {q}') print('-' * 25) for (label, sampler) in zip(labels, samplers): expr = Ent(sampler, layer=layer, epoch=3000) print(f'{label}(layer={layer}): {expr}') print()
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute,IBMQ from qiskit.tools.monitor import job_monitor from qiskit.circuit.library import Diagonal import numpy as np pi = np.pi IBMQ.enable_account('ENTER API KEY HERE') provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') diagonals = [-1,-1,-1,-1] q = QuantumRegister(2,'q') c = ClassicalRegister(2,'c') circuit = QuantumCircuit(q,c) circuit.h(q[0]) circuit.h(q[1]) circuit += Diagonal(diagonals) circuit.h(q[0]) circuit.h(q[1]) circuit.measure(q,c) # Qubit Measurment print(circuit) job = execute(circuit, backend, shots=8192) job_monitor(job) counts = job.result().get_counts() print(counts)
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute,IBMQ from qiskit.tools.monitor import job_monitor IBMQ.enable_account('ENTER API KEY HERE') provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') q = QuantumRegister(2,'q') c = ClassicalRegister(2,'c') def firstBellState(): circuit = QuantumCircuit(q,c) circuit.h(q[0]) # Hadamard gate circuit.cx(q[0],q[1]) # CNOT gate circuit.measure(q,c) # Qubit Measurment print(circuit) job = execute(circuit, backend, shots=8192) job_monitor(job) counts = job.result().get_counts() print(counts) def secondBellState(): circuit = QuantumCircuit(q,c) circuit.x(q[0]) # Pauli-X gate circuit.h(q[0]) # Hadamard gate circuit.cx(q[0],q[1]) # CNOT gate circuit.measure(q,c) # Qubit Measurment print(circuit) job = execute(circuit, backend, shots=8192) job_monitor(job) counts = job.result().get_counts() print(counts) def thirdBellState(): circuit = QuantumCircuit(q,c) circuit.x(q[1]) # Pauli-X gate circuit.h(q[0]) # Hadamard gate circuit.cx(q[0],q[1]) # CNOT gate circuit.measure(q,c) # Qubit Measurment print(circuit) job = execute(circuit, backend, shots=8192) job_monitor(job) counts = job.result().get_counts() print(counts) def fourthBellState(): circuit = QuantumCircuit(q,c) circuit.x(q[1]) # Pauli-X gate circuit.h(q[0]) # Hadamard gate circuit.z(q[0]) # Pauli-Z gate circuit.z(q[1]) # Pauli-Z gate circuit.cx(q[0],q[1]) # CNOT gate circuit.measure(q,c) # Qubit Measurment print(circuit) job = execute(circuit, backend, shots=8192) job_monitor(job) counts = job.result().get_counts() print(counts) print("Creating first Bell State:\n") firstBellState() print("\nCreating second Bell State:\n") secondBellState() print("\nCreating third Bell State:\n") thirdBellState() print("\nCreating fourth Bell State:\n") fourthBellState()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw()
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/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ResourceEstimation pass testing""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import ResourceEstimation from qiskit.test import QiskitTestCase class TestResourceEstimationPass(QiskitTestCase): """Tests for PropertySet methods.""" def test_empty_dag(self): """Empty DAG.""" circuit = QuantumCircuit() passmanager = PassManager() passmanager.append(ResourceEstimation()) passmanager.run(circuit) self.assertEqual(passmanager.property_set["size"], 0) self.assertEqual(passmanager.property_set["depth"], 0) self.assertEqual(passmanager.property_set["width"], 0) self.assertDictEqual(passmanager.property_set["count_ops"], {}) def test_just_qubits(self): """A dag with 8 operations and no classic bits""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) passmanager = PassManager() passmanager.append(ResourceEstimation()) passmanager.run(circuit) self.assertEqual(passmanager.property_set["size"], 8) self.assertEqual(passmanager.property_set["depth"], 7) self.assertEqual(passmanager.property_set["width"], 2) self.assertDictEqual(passmanager.property_set["count_ops"], {"cx": 6, "h": 2}) if __name__ == "__main__": unittest.main()
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * from qiskit.quantum_info import * q1_sv = Statevector.from_label('0') q2_sv = Statevector.from_label('1') prod_sv = q1_sv.tensor(q2_sv) print(prod_sv.data) prod_sv2 = Statevector.from_label('01') print(prod_sv2.data) op1 = Operator.from_label('X') op2 = Operator.from_label('I') prod_op = op1.tensor(op2) print(prod_op.data) prod_op2 = Operator.from_label('XI') print(prod_op2.data) q1_sv_1 = q1_sv.evolve(op1) q2_sv_1 = q2_sv.evolve(op2) prod_sv_1 = q1_sv_1.tensor(q2_sv_1) prod_sv2_1 = prod_sv2.evolve(prod_op2) prod_sv_1.equiv(prod_sv2_1) qc = QuantumCircuit(2) # All qubits start in the |0> state qc.x(0) qc.draw(output='mpl') # qc.measure(0,0) # First argument is the qubit to be measured print(Operator(qc).data) Operator(qc).equiv(prod_op2) qc_rev = qc.reverse_bits() qc_rev.draw(output='mpl') print(Operator(qc_rev).data) Operator(qc_rev).equiv(prod_op2) qc2 = QuantumCircuit(2) qc2.h([0,1]) qc2.measure_all() qc2.draw(output='mpl') job = execute(qc2, backend=QasmSimulator(), shots=8192) result = job.result() result.get_counts() qc2_rev = qc2.reverse_bits() qc2_rev.draw(output='mpl') job = execute(qc2_rev, backend=QasmSimulator(), shots=8192) result = job.result() result.get_counts() qc = QuantumCircuit(2) qc.cx(0,1) qc.draw(output='mpl') cnot_op = Operator(qc) sv = Statevector.from_label('0+') # Little Endian sv2 = sv.evolve(cnot_op) plot_bloch_multivector(sv) plot_bloch_multivector(sv2) sv2.data
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for DensityMatrix quantum state class.""" import logging import unittest import numpy as np from ddt import data, ddt from numpy.testing import assert_allclose from qiskit import QiskitError, QuantumCircuit, QuantumRegister from qiskit.circuit.library import QFT, HGate from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp from qiskit.quantum_info.random import random_density_matrix, random_pauli, random_unitary from qiskit.quantum_info.states import DensityMatrix, Statevector from qiskit.test import QiskitTestCase from qiskit.utils import optionals logger = logging.getLogger(__name__) @ddt class TestDensityMatrix(QiskitTestCase): """Tests for DensityMatrix class.""" @classmethod def rand_vec(cls, n, normalize=False): """Return complex vector or statevector""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_vec default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) vec = rng.random(n) + 1j * rng.random(n) if normalize: vec /= np.sqrt(np.dot(vec, np.conj(vec))) return vec @classmethod def rand_rho(cls, n): """Return random pure state density matrix""" rho = cls.rand_vec(n, normalize=True) return np.outer(rho, np.conjugate(rho)) def test_init_array_qubit(self): """Test subsystem initialization from N-qubit array.""" # Test automatic inference of qubit subsystems rho = self.rand_rho(8) for dims in [None, 8]: state = DensityMatrix(rho, dims=dims) assert_allclose(state.data, rho) self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) self.assertEqual(state.num_qubits, 3) def test_init_array(self): """Test initialization from array.""" rho = self.rand_rho(3) state = DensityMatrix(rho) assert_allclose(state.data, rho) self.assertEqual(state.dim, 3) self.assertEqual(state.dims(), (3,)) self.assertIsNone(state.num_qubits) rho = self.rand_rho(2 * 3 * 4) state = DensityMatrix(rho, dims=[2, 3, 4]) assert_allclose(state.data, rho) self.assertEqual(state.dim, 2 * 3 * 4) self.assertEqual(state.dims(), (2, 3, 4)) self.assertIsNone(state.num_qubits) def test_init_array_except(self): """Test initialization exception from array.""" rho = self.rand_rho(4) self.assertRaises(QiskitError, DensityMatrix, rho, dims=[4, 2]) self.assertRaises(QiskitError, DensityMatrix, rho, dims=[2, 4]) self.assertRaises(QiskitError, DensityMatrix, rho, dims=5) def test_init_densitymatrix(self): """Test initialization from DensityMatrix.""" rho1 = DensityMatrix(self.rand_rho(4)) rho2 = DensityMatrix(rho1) self.assertEqual(rho1, rho2) def test_init_statevector(self): """Test initialization from DensityMatrix.""" vec = self.rand_vec(4) target = DensityMatrix(np.outer(vec, np.conjugate(vec))) rho = DensityMatrix(Statevector(vec)) self.assertEqual(rho, target) def test_init_circuit(self): """Test initialization from a circuit.""" # random unitaries u0 = random_unitary(2).data u1 = random_unitary(2).data # add to circuit qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.unitary(u0, [qr[0]]) circ.unitary(u1, [qr[1]]) target_vec = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0])) target = DensityMatrix(target_vec) rho = DensityMatrix(circ) self.assertEqual(rho, target) # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) target = DensityMatrix.from_label("000").evolve(Operator(circuit)) rho = DensityMatrix(circuit) self.assertEqual(rho, target) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.h(0) circuit.h(1) circuit.cp(lam, 0, 1) target = DensityMatrix.from_label("00").evolve(Operator(circuit)) rho = DensityMatrix(circuit) self.assertEqual(rho, target) def test_from_circuit(self): """Test initialization from a circuit.""" # random unitaries u0 = random_unitary(2).data u1 = random_unitary(2).data # add to circuit qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.unitary(u0, [qr[0]]) circ.unitary(u1, [qr[1]]) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circ.x(0) circuit.ch(0, 1) target = DensityMatrix.from_label("00").evolve(Operator(circuit)) rho = DensityMatrix.from_instruction(circuit) self.assertEqual(rho, target) # Test initialize instruction init = Statevector([1, 0, 0, 1j]) / np.sqrt(2) target = DensityMatrix(init) circuit = QuantumCircuit(2) circuit.initialize(init.data, [0, 1]) rho = DensityMatrix.from_instruction(circuit) self.assertEqual(rho, target) # Test reset instruction target = DensityMatrix([1, 0]) circuit = QuantumCircuit(1) circuit.h(0) circuit.reset(0) rho = DensityMatrix.from_instruction(circuit) self.assertEqual(rho, target) def test_from_instruction(self): """Test initialization from an instruction.""" target_vec = Statevector(np.dot(HGate().to_matrix(), [1, 0])) target = DensityMatrix(target_vec) rho = DensityMatrix.from_instruction(HGate()) self.assertEqual(rho, target) def test_from_label(self): """Test initialization from a label""" x_p = DensityMatrix(np.array([[0.5, 0.5], [0.5, 0.5]])) x_m = DensityMatrix(np.array([[0.5, -0.5], [-0.5, 0.5]])) y_p = DensityMatrix(np.array([[0.5, -0.5j], [0.5j, 0.5]])) y_m = DensityMatrix(np.array([[0.5, 0.5j], [-0.5j, 0.5]])) z_p = DensityMatrix(np.diag([1, 0])) z_m = DensityMatrix(np.diag([0, 1])) label = "0+r" target = z_p.tensor(x_p).tensor(y_p) self.assertEqual(target, DensityMatrix.from_label(label)) label = "-l1" target = x_m.tensor(y_m).tensor(z_m) self.assertEqual(target, DensityMatrix.from_label(label)) def test_equal(self): """Test __eq__ method""" for _ in range(10): rho = self.rand_rho(4) self.assertEqual(DensityMatrix(rho), DensityMatrix(rho.tolist())) def test_copy(self): """Test DensityMatrix copy method""" for _ in range(5): rho = self.rand_rho(4) orig = DensityMatrix(rho) cpy = orig.copy() cpy._data[0] += 1.0 self.assertFalse(cpy == orig) def test_is_valid(self): """Test is_valid method.""" state = DensityMatrix(np.eye(2)) self.assertFalse(state.is_valid()) for _ in range(10): state = DensityMatrix(self.rand_rho(4)) self.assertTrue(state.is_valid()) def test_to_operator(self): """Test to_operator method for returning projector.""" for _ in range(10): rho = self.rand_rho(4) target = Operator(rho) op = DensityMatrix(rho).to_operator() self.assertEqual(op, target) def test_evolve(self): """Test evolve method for operators.""" for _ in range(10): op = random_unitary(4) rho = self.rand_rho(4) target = DensityMatrix(np.dot(op.data, rho).dot(op.adjoint().data)) evolved = DensityMatrix(rho).evolve(op) self.assertEqual(target, evolved) def test_evolve_subsystem(self): """Test subsystem evolve method for operators.""" # Test evolving single-qubit of 3-qubit system for _ in range(5): rho = self.rand_rho(8) state = DensityMatrix(rho) op0 = random_unitary(2) op1 = random_unitary(2) op2 = random_unitary(2) # Test evolve on 1-qubit op = op0 op_full = Operator(np.eye(4)).tensor(op) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0]), target) # Evolve on qubit 1 op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2)) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[1]), target) # Evolve on qubit 2 op_full = op.tensor(np.eye(4)) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2]), target) # Test evolve on 2-qubits op = op1.tensor(op0) # Evolve on qubits [0, 2] op_full = op1.tensor(np.eye(2)).tensor(op0) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0, 2]), target) # Evolve on qubits [2, 0] op_full = op0.tensor(np.eye(2)).tensor(op1) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2, 0]), target) # Test evolve on 3-qubits op = op2.tensor(op1).tensor(op0) # Evolve on qubits [0, 1, 2] op_full = op target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target) # Evolve on qubits [2, 1, 0] op_full = op0.tensor(op1).tensor(op2) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target) def test_evolve_qudit_subsystems(self): """Test nested evolve calls on qudit subsystems.""" dims = (3, 4, 5) init = self.rand_rho(np.prod(dims)) ops = [random_unitary((dim,)) for dim in dims] state = DensityMatrix(init, dims) for i, op in enumerate(ops): state = state.evolve(op, [i]) target_op = np.eye(1) for op in ops: target_op = np.kron(op.data, target_op) target = DensityMatrix(np.dot(target_op, init).dot(target_op.conj().T), dims) self.assertEqual(state, target) def test_conjugate(self): """Test conjugate method.""" for _ in range(10): rho = self.rand_rho(4) target = DensityMatrix(np.conj(rho)) state = DensityMatrix(rho).conjugate() self.assertEqual(state, target) def test_expand(self): """Test expand method.""" for _ in range(10): rho0 = self.rand_rho(2) rho1 = self.rand_rho(3) target = np.kron(rho1, rho0) state = DensityMatrix(rho0).expand(DensityMatrix(rho1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (2, 3)) assert_allclose(state.data, target) def test_tensor(self): """Test tensor method.""" for _ in range(10): rho0 = self.rand_rho(2) rho1 = self.rand_rho(3) target = np.kron(rho0, rho1) state = DensityMatrix(rho0).tensor(DensityMatrix(rho1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (3, 2)) assert_allclose(state.data, target) def test_add(self): """Test add method.""" for _ in range(10): rho0 = self.rand_rho(4) rho1 = self.rand_rho(4) state0 = DensityMatrix(rho0) state1 = DensityMatrix(rho1) self.assertEqual(state0 + state1, DensityMatrix(rho0 + rho1)) def test_add_except(self): """Test add method raises exceptions.""" state1 = DensityMatrix(self.rand_rho(2)) state2 = DensityMatrix(self.rand_rho(3)) self.assertRaises(QiskitError, state1.__add__, state2) def test_subtract(self): """Test subtract method.""" for _ in range(10): rho0 = self.rand_rho(4) rho1 = self.rand_rho(4) state0 = DensityMatrix(rho0) state1 = DensityMatrix(rho1) self.assertEqual(state0 - state1, DensityMatrix(rho0 - rho1)) def test_multiply(self): """Test multiply method.""" for _ in range(10): rho = self.rand_rho(4) state = DensityMatrix(rho) val = np.random.rand() + 1j * np.random.rand() self.assertEqual(val * state, DensityMatrix(val * state)) def test_negate(self): """Test negate method""" for _ in range(10): rho = self.rand_rho(4) state = DensityMatrix(rho) self.assertEqual(-state, DensityMatrix(-1 * rho)) def test_to_dict(self): """Test to_dict method""" with self.subTest(msg="dims = (2, 2)"): rho = DensityMatrix(np.arange(1, 17).reshape(4, 4)) target = { "00|00": 1, "01|00": 2, "10|00": 3, "11|00": 4, "00|01": 5, "01|01": 6, "10|01": 7, "11|01": 8, "00|10": 9, "01|10": 10, "10|10": 11, "11|10": 12, "00|11": 13, "01|11": 14, "10|11": 15, "11|11": 16, } self.assertDictAlmostEqual(target, rho.to_dict()) with self.subTest(msg="dims = (2, 3)"): rho = DensityMatrix(np.diag(np.arange(1, 7)), dims=(2, 3)) target = {} for i in range(2): for j in range(3): key = "{1}{0}|{1}{0}".format(i, j) target[key] = 2 * j + i + 1 self.assertDictAlmostEqual(target, rho.to_dict()) with self.subTest(msg="dims = (2, 11)"): vec = DensityMatrix(np.diag(np.arange(1, 23)), dims=(2, 11)) target = {} for i in range(2): for j in range(11): key = "{1},{0}|{1},{0}".format(i, j) target[key] = 2 * j + i + 1 self.assertDictAlmostEqual(target, vec.to_dict()) def test_densitymatrix_to_statevector_pure(self): """Test converting a pure density matrix to statevector.""" state = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1])) psi = Statevector(state) rho = DensityMatrix(psi) phi = rho.to_statevector() self.assertTrue(psi.equiv(phi)) def test_densitymatrix_to_statevector_mixed(self): """Test converting a pure density matrix to statevector.""" state_1 = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1])) state_2 = 1 / np.sqrt(2) * (np.array([0, 0, 0, 0, 0, 0, 1, 1])) psi = 0.5 * (Statevector(state_1) + Statevector(state_2)) rho = DensityMatrix(psi) self.assertRaises(QiskitError, rho.to_statevector) def test_probabilities_product(self): """Test probabilities method for product state""" state = DensityMatrix.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities() target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([0, 1])"): probs = state.probabilities([0, 1]) target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1, 0]"): probs = state.probabilities([1, 0]) target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities([0]) target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1])"): probs = state.probabilities([1]) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) def test_probabilities_ghz(self): """Test probabilities method for GHZ state""" psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state = DensityMatrix(psi) # 3-qubit qargs target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([0.5, 0, 0, 0.5]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([0.5, 0.5]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_w(self): """Test probabilities method with W state""" psi = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state = DensityMatrix(psi) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([1 / 3, 1 / 3, 1 / 3, 0]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([2 / 3, 1 / 3]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_dict_product(self): """Test probabilities_dict method for product state""" state = DensityMatrix.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities_dict() target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([0, 1])"): probs = state.probabilities_dict([0, 1]) target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1, 0]"): probs = state.probabilities_dict([1, 0]) target = {"00": 0.5, "01": 0.5} self.assertDictAlmostEqual(probs, target) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities_dict([0]) target = {"0": 1} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1])"): probs = state.probabilities_dict([1]) target = {"0": 0.5, "1": 0.5} self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_ghz(self): """Test probabilities_dict method for GHZ state""" psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state = DensityMatrix(psi) # 3-qubit qargs target = {"000": 0.5, "111": 0.5} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 0.5, "11": 0.5} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 0.5, "1": 0.5} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_w(self): """Test probabilities_dict method with W state""" psi = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state = DensityMatrix(psi) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 2 / 3, "1": 1 / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_sample_counts_ghz(self): """Test sample_counts method for GHZ state""" shots = 2000 threshold = 0.02 * shots state = DensityMatrix( (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) ) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_counts_w(self): """Test sample_counts method for W state""" shots = 3000 threshold = 0.02 * shots state = DensityMatrix( ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) ) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_probabilities_dict_unequal_dims(self): """Test probabilities_dict for a state with unequal subsystem dimensions.""" vec = np.zeros(60, dtype=float) vec[15:20] = np.ones(5) vec[40:46] = np.ones(6) state = DensityMatrix(vec / np.sqrt(11.0), dims=[3, 4, 5]) p = 1.0 / 11.0 self.assertDictEqual( state.probabilities_dict(), { s: p for s in [ "110", "111", "112", "120", "121", "311", "312", "320", "321", "322", "330", ] }, ) # differences due to rounding self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 1]), {"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1, 0]), {"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 2]), {"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p}, delta=1e-10, ) def test_sample_counts_qutrit(self): """Test sample_counts method for qutrit state""" p = 0.3 shots = 1000 threshold = 0.03 * shots state = DensityMatrix(np.diag([p, 0, 1 - p])) state.seed(100) with self.subTest(msg="counts"): target = {"0": shots * p, "2": shots * (1 - p)} counts = state.sample_counts(shots=shots) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_memory_ghz(self): """Test sample_memory method for GHZ state""" shots = 2000 state = DensityMatrix( (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) ) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_w(self): """Test sample_memory method for W state""" shots = 3000 state = DensityMatrix( ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) ) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_qutrit(self): """Test sample_memory method for qutrit state""" p = 0.3 shots = 1000 state = DensityMatrix(np.diag([p, 0, 1 - p])) state.seed(100) with self.subTest(msg="memory"): memory = state.sample_memory(shots) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), {"0", "2"}) def test_reset_2qubit(self): """Test reset method for 2-qubit state""" state = DensityMatrix(np.diag([0.5, 0, 0, 0.5])) with self.subTest(msg="reset"): rho = state.copy() value = rho.reset() target = DensityMatrix(np.diag([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset"): rho = state.copy() value = rho.reset([0, 1]) target = DensityMatrix(np.diag([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset [0]"): rho = state.copy() value = rho.reset([0]) target = DensityMatrix(np.diag([0.5, 0, 0.5, 0])) self.assertEqual(value, target) with self.subTest(msg="reset [0]"): rho = state.copy() value = rho.reset([1]) target = DensityMatrix(np.diag([0.5, 0.5, 0, 0])) self.assertEqual(value, target) def test_reset_qutrit(self): """Test reset method for qutrit""" state = DensityMatrix(np.diag([1, 1, 1]) / 3) state.seed(200) value = state.reset() target = DensityMatrix(np.diag([1, 0, 0])) self.assertEqual(value, target) def test_measure_2qubit(self): """Test measure method for 2-qubit state""" state = DensityMatrix.from_label("+0") seed = 200 shots = 100 with self.subTest(msg="measure"): for i in range(shots): rho = state.copy() rho.seed(seed + i) outcome, value = rho.measure() self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0, 1]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([0, 1]) self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [1, 0]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([1, 0]) self.assertIn(outcome, ["00", "01"]) if outcome == "00": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([0]) self.assertEqual(outcome, "0") target = DensityMatrix.from_label("+0") self.assertEqual(value, target) with self.subTest(msg="measure [1]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([1]) self.assertIn(outcome, ["0", "1"]) if outcome == "0": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) def test_measure_qutrit(self): """Test measure method for qutrit""" state = DensityMatrix(np.diag([1, 1, 1]) / 3) seed = 200 shots = 100 for i in range(shots): rho = state.copy() rho.seed(seed + i) outcome, value = rho.measure() self.assertIn(outcome, ["0", "1", "2"]) if outcome == "0": target = DensityMatrix(np.diag([1, 0, 0])) self.assertEqual(value, target) elif outcome == "1": target = DensityMatrix(np.diag([0, 1, 0])) self.assertEqual(value, target) else: target = DensityMatrix(np.diag([0, 0, 1])) self.assertEqual(value, target) def test_from_int(self): """Test from_int method""" with self.subTest(msg="from_int(0, 4)"): target = DensityMatrix([1, 0, 0, 0]) value = DensityMatrix.from_int(0, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(3, 4)"): target = DensityMatrix([0, 0, 0, 1]) value = DensityMatrix.from_int(3, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(8, (3, 3))"): target = DensityMatrix([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3)) value = DensityMatrix.from_int(8, (3, 3)) self.assertEqual(target, value) def test_expval(self): """Test expectation_value method""" psi = Statevector([1, 0, 0, 1]) / np.sqrt(2) rho = DensityMatrix(psi) for label, target in [ ("II", 1), ("XX", 1), ("YY", -1), ("ZZ", 1), ("IX", 0), ("YZ", 0), ("ZX", 0), ("YI", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2 rho = DensityMatrix(psi) for label, target in [ ("XXX", np.sqrt(2) / 2), ("YYY", -np.sqrt(2) / 2), ("ZZZ", 0), ("XYZ", 0), ("YIY", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) labels = ["XXX", "IXI", "YYY", "III"] coeffs = [3.0, 5.5, -1j, 23] spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs))) expval = rho.expectation_value(spp_op) target = 25.121320343559642 + 0.7071067811865476j self.assertAlmostEqual(expval, target) @data( "II", "IX", "IY", "IZ", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", "-II", "-IX", "-IY", "-IZ", "-XI", "-XX", "-XY", "-XZ", "-YI", "-YX", "-YY", "-YZ", "-ZI", "-ZX", "-ZY", "-ZZ", "iII", "iIX", "iIY", "iIZ", "iXI", "iXX", "iXY", "iXZ", "iYI", "iYX", "iYY", "iYZ", "iZI", "iZX", "iZY", "iZZ", "-iII", "-iIX", "-iIY", "-iIZ", "-iXI", "-iXX", "-iXY", "-iXZ", "-iYI", "-iYX", "-iYY", "-iYZ", "-iZI", "-iZX", "-iZY", "-iZZ", ) def test_expval_pauli_f_contiguous(self, pauli): """Test expectation_value method for Pauli op""" seed = 1020 op = Pauli(pauli) rho = random_density_matrix(2**op.num_qubits, seed=seed) rho._data = np.reshape(rho.data.flatten(order="F"), rho.data.shape, order="F") target = rho.expectation_value(op.to_matrix()) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) @data( "II", "IX", "IY", "IZ", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", "-II", "-IX", "-IY", "-IZ", "-XI", "-XX", "-XY", "-XZ", "-YI", "-YX", "-YY", "-YZ", "-ZI", "-ZX", "-ZY", "-ZZ", "iII", "iIX", "iIY", "iIZ", "iXI", "iXX", "iXY", "iXZ", "iYI", "iYX", "iYY", "iYZ", "iZI", "iZX", "iZY", "iZZ", "-iII", "-iIX", "-iIY", "-iIZ", "-iXI", "-iXX", "-iXY", "-iXZ", "-iYI", "-iYX", "-iYY", "-iYZ", "-iZI", "-iZX", "-iZY", "-iZZ", ) def test_expval_pauli_c_contiguous(self, pauli): """Test expectation_value method for Pauli op""" seed = 1020 op = Pauli(pauli) rho = random_density_matrix(2**op.num_qubits, seed=seed) rho._data = np.reshape(rho.data.flatten(order="C"), rho.data.shape, order="C") target = rho.expectation_value(op.to_matrix()) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) @data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]) def test_expval_pauli_qargs(self, qubits): """Test expectation_value method for Pauli op""" seed = 1020 op = random_pauli(2, seed=seed) state = random_density_matrix(2**3, seed=seed) target = state.expectation_value(op.to_matrix(), qubits) expval = state.expectation_value(op, qubits) self.assertAlmostEqual(expval, target) def test_reverse_qargs(self): """Test reverse_qargs method""" circ1 = QFT(5) circ2 = circ1.reverse_bits() state1 = DensityMatrix.from_instruction(circ1) state2 = DensityMatrix.from_instruction(circ2) self.assertEqual(state1.reverse_qargs(), state2) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib") @unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc") def test_drawings(self): """Test draw method""" qc1 = QFT(5) dm = DensityMatrix.from_instruction(qc1) with self.subTest(msg="str(density_matrix)"): str(dm) for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]: with self.subTest(msg=f"draw('{drawtype}')"): dm.draw(drawtype) def test_density_matrix_partial_transpose(self): """Test partial_transpose function on density matrices""" with self.subTest(msg="separable"): rho = DensityMatrix.from_label("10+") rho1 = np.zeros((8, 8), complex) rho1[4, 4] = 0.5 rho1[4, 5] = 0.5 rho1[5, 4] = 0.5 rho1[5, 5] = 0.5 self.assertEqual(rho.partial_transpose([0, 1]), DensityMatrix(rho1)) self.assertEqual(rho.partial_transpose([0, 2]), DensityMatrix(rho1)) with self.subTest(msg="entangled"): rho = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5, 0], [0, -0.5, 0.5, 0], [0, 0, 0, 0]]) rho1 = DensityMatrix([[0, 0, 0, -0.5], [0, 0.5, 0, 0], [0, 0, 0.5, 0], [-0.5, 0, 0, 0]]) self.assertEqual(rho.partial_transpose([0]), DensityMatrix(rho1)) self.assertEqual(rho.partial_transpose([1]), DensityMatrix(rho1)) with self.subTest(msg="dims(3,3)"): mat = np.zeros((9, 9)) mat1 = np.zeros((9, 9)) mat[8, 0] = 1 mat1[0, 8] = 1 rho = DensityMatrix(mat, dims=(3, 3)) rho1 = DensityMatrix(mat1, dims=(3, 3)) self.assertEqual(rho.partial_transpose([0, 1]), rho1) def test_clip_probabilities(self): """Test probabilities are clipped to [0, 1].""" dm = DensityMatrix([[1.1, 0], [0, 0]]) self.assertEqual(list(dm.probabilities()), [1.0, 0.0]) # The "1" key should be exactly zero and therefore omitted. self.assertEqual(dm.probabilities_dict(), {"0": 1.0}) def test_round_probabilities(self): """Test probabilities are correctly rounded. This is good to test to ensure clipping, renormalizing and rounding work together. """ p = np.sqrt(1 / 3) amplitudes = [p, p, p, 0] dm = DensityMatrix(np.outer(amplitudes, amplitudes)) expected = [0.33, 0.33, 0.33, 0] # Exact floating-point check because fixing the rounding should ensure this is exact. self.assertEqual(list(dm.probabilities(decimals=2)), expected) if __name__ == "__main__": unittest.main()
https://github.com/christopherporter1/VQE_with_Runtime
christopherporter1
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ( ElectronicStructureDriverType, ElectronicStructureMoleculeDriver) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer molecule = Molecule([["O",[0.0,0.0,0.0]],["H", [0.757,0.586,0.0]], ["H", [-0.757,0.586,0.0]]], charge = 0, multiplicity = 1) driver = ElectronicStructureMoleculeDriver(molecule, basis = "sto3g", driver_type = ElectronicStructureDriverType.PYSCF) es_problem = ElectronicStructureProblem(driver, transformers=[FreezeCoreTransformer(freeze_core=True, remove_orbitals=[])]) second_q_ops = es_problem.second_q_ops() from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper, ParityMapper mapper = ParityMapper() converter = QubitConverter(mapper = mapper, two_qubit_reduction = True) qubit_op = converter.convert(second_q_ops["ElectronicEnergy"],num_particles = es_problem.num_particles) print(qubit_op) from qiskit.circuit.library import PauliTwoDesign, TwoLocal, EfficientSU2 from qiskit_nature.circuit.library import HartreeFock init_state = HartreeFock(es_problem.num_spin_orbitals, es_problem.num_particles, converter) #init_state = None rotation_blocks = ['ry','rx'] entanglement_blocks = ['crx'] ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, 'sca', insert_barriers = False,initial_state = init_state) from qiskit.algorithms.optimizers import COBYLA, SPSA, SLSQP, NELDER_MEAD optimizer = COBYLA(maxiter=50) from qiskit_ibm_runtime import Estimator, QiskitRuntimeService, Session, Options service = QiskitRuntimeService(channel = "ibm_quantum") options = Options() options.execution.shots = 2000 options.resilience_level = 0 options.optimization_level = 0 estimator = Estimator(session=Session(service, backend = "ibmq_qasm_simulator"), options=options) print(Options._DEFAULT_RESILIENCE_LEVEL,Options._DEFAULT_OPTIMIZATION_LEVEL) counts = [] values = [] def store_intermediate_result(eval_counts, parameters, mean, std): counts.append(eval_counts) values.append(mean) from qiskit.algorithms.minimum_eigensolvers import VQE vqe = VQE(estimator, ansatz, optimizer,callback=store_intermediate_result) result = vqe.compute_minimum_eigenvalue(qubit_op) print(result) from qiskit.algorithms import NumPyEigensolver exact = NumPyEigensolver() exact_run = exact.compute_eigenvalues(qubit_op) print(exact_run) print(es_problem.grouped_property_transformed._properties["ElectronicEnergy"]) result_freeze=result values_freeze = values for i in range(len(values)): values_freeze[i] = values[i]-60.66177520599246 counts_freeze = counts import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # Plot energy and reference value plt.figure(figsize=(12, 6)) plt.plot(counts_freeze, values_freeze, label='spsa') plt.axhline(y=-84.206, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy") plt.show() #Not to be shown in code walkthrough; just for me to have. import numpy f = open("qasm_spsa_H2O", "w+") f.write("# optimization_step Energy\n") # column names numpy.savetxt(f, numpy.array([counts_freeze, values_freeze]).T) #x, y = numpy.loadtxt("trialdata", unpack=True) from qiskit import IBMQ provider = IBMQ.load_account() from qiskit_ibm_runtime import Estimator, QiskitRuntimeService, Session, Options optimizer = SPSA(maxiter = 50) counts = [] values = [] #def store_intermediate_result(eval_counts, parameters, mean, std): # counts.append(eval_counts) # values.append(mean) service = QiskitRuntimeService() backend = "ibm_washington" with Session(service=service, backend=backend) as session: options = Options() options.execution.shots = 2000 options.resilience_level = 1 options.optimization_level = 3 vqe = VQE(Estimator(session=session, options=options), ansatz, optimizer, callback=store_intermediate_result) result = vqe.compute_minimum_eigenvalue(qubit_op) print(result) session.close() result_real=result counts_real=counts values_real=values #Not to be shown in code walkthrough. Just for me to have. f = open("wash_spsa_H2O", "w+") f.write("# optimization_step Energy\n") # column names numpy.savetxt(f, numpy.array([counts_real, values_real]).T) #x, y = numpy.loadtxt("trialdata", unpack=True) for i in range(len(values)): values_real[i] = values[i]-60.66177520599246 plt.rcParams["font.size"] = 14 # Plot energy and reference value plt.figure(figsize=(12, 6)) plt.plot(counts_real, values_real, label='spsa on ibm_washington') plt.axhline(y=-84.206, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy") plt.show() counts = [] values = [] with Session(service=service, backend=backend) as session: options = Options() options.execution.shots = 2000 options.resilience_level = 0 options.optimization_level = 0 vqe = VQE(Estimator(session=session, options=options), ansatz, optimizer, callback=store_intermediate_result) result = vqe.compute_minimum_eigenvalue(qubit_op) print(result) session.close() result_zero=result values_zero = values for i in range(len(values)): values_zero[i] = values[i]-60.66177520599246 counts_zero = counts #Not to be shown in walkthrough. Just for me to have. f = open("qasm_spsa_H2O", "w+") f.write("# optimization_step Energy\n") # column names numpy.savetxt(f, numpy.array([counts_zero, values_zero]).T) plt.rcParams["font.size"] = 14 # Plot energy and reference value plt.figure(figsize=(12, 6)) plt.plot(counts_real, values_real, label='Default') plt.plot(counts_zero, values_zero, label='Res=0,Opt=0') plt.axhline(y=-84.206, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy") plt.show()
https://github.com/RakhshandaMujib/Grover-Search-Algorithm
RakhshandaMujib
import numpy as np # Importing standard Qiskit libraries: from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.providers.ibmq import least_busy def phase_oracle(n, indices_to_mark, name = 'Oracle'): ''' Brief: Generates the orcale matrix to flip the phase of the marked elements. Transforms the matrix to the corresponding unitary gate. In practicality, the phase of the winning state(s) get(s) flipped. Parameters: n = Integer. Number of qubits. indices_to_mark = List of intergs representing the indices of winning elements to search for. name = Name of the QuantumCircuit object returned. Returns: qc = QuantumCircuit object. Has the oracle gate as an element of a circuit. ''' qc = QuantumCircuit(n, name = name) #Initialize a quantum circuit with n qubits. oracle_matrix = np.identity(2**n) #Get an identity matrix of n^2 dimension. for index_to_mark in indices_to_mark: #For each key in the list of keys... oracle_matrix[index_to_mark, index_to_mark] = -1 #flip the sign of the key. qc.unitary(oracle_matrix, range(n)) #Apply the matrix to the circuit as a unitary gate #with range of qubits being [0, ..., n-1]. return qc def diffuser(n, name = 'Diffuser'): ''' Brief: Prepares the diffuser circuit and generates the matrix to flip the state 0. Physically, the diffuser amplifies the amplitudes of the winning states. Parameters: n = Integer. Number of qubits. Returns: qc = QuantumCircuit object. Diffuser circuit. ''' all_num = lsit(range(2 ** n)) #[0, ..., (2**n) -1] except_zero = all_num[1:] #[1, ..., (2**n) -1] qc = QuantumCircuit(n, name = name) #Initialize a quantum circuit with n qubits. qc.h(range(n)) #Prepare the state |s> = H|0>. diffuser_matrix = phase_oracle(n, except_zero) #Generate the diffuser matrix. qc.append(diffuser_matrix, range(n)) #Apply the diffuser matrix=> V|s>. qc.h(range(n)) #Apply the H gate to the cicuit=> HV|s>. return qc def groverSearch(n, marked): ''' Brief: Prpares the entire circuit for the Grover's search algorithm. Searches for the marked elements in the range (0, ..., 2^(n-1)). Parameters: n = Integer. Number of qubits. marked = List of keys. Returns: qc = QuantumCircuit object. Final Grover's search circuit. ''' qc = QuantumCircuit(n, n) #Initialize a quantum circuit with n qubits and classical bits. M = len(marked) #Say, we have M marked element. N = 2 ** n #Total number of elements that can be represented with n qubits. theta = 2 * np.arcsin(np.sqrt(M/N)) #Get the angle of rotation. rounds = int(np.ceil(np.pi / (2 * theta))- (1 / 2)) #Get the number of rounds needed. #Print the information: print(f"Number of qubits: {n}") print(f"Key(s) to search: {marked}") print(f"Number of rounds needed: {rounds}") qc.h(range(n)) #Step 1: Prepare the superposition states of each qubit. for _ in range(rounds): #For all the rounds... qc.append(phase_oracle(n, marked), range(n)) #Step 2: Apply the phase oracle. qc.append(diffuser(n), range(n)) #Step 3: Apply the diffuser. qc.measure(range(n), range(n)) #Final step: Measure the qubits. return qc n = int(input("Enter the number of qubits:")) marked = list(map(int, input('Enter the elements:\n').split())) qc = groverSearch(n, marked) qc.draw() #Run it in the simulator: backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 8192).result() counts = result.get_counts(qc) #Print the results: print(counts) plot_histogram(counts)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ StatePreparation test. """ import unittest import math import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import Statevector, Operator from qiskit.test import QiskitTestCase from qiskit.exceptions import QiskitError from qiskit.circuit.library import StatePreparation @ddt class TestStatePreparation(QiskitTestCase): """Test initialization with StatePreparation class""" def test_prepare_from_label(self): """Prepare state from label.""" desired_sv = Statevector.from_label("01+-lr") qc = QuantumCircuit(6) qc.prepare_state("01+-lr", range(6)) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv) def test_prepare_from_int(self): """Prepare state from int.""" desired_sv = Statevector.from_label("110101") qc = QuantumCircuit(6) qc.prepare_state(53, range(6)) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv) def test_prepare_from_list(self): """Prepare state from list.""" desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) qc = QuantumCircuit(2) qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv) def test_prepare_single_qubit(self): """Prepare state in single qubit.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) circuit.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], qreg[1]) expected = QuantumCircuit(qreg) expected.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], [qreg[1]]) self.assertEqual(circuit, expected) def test_nonzero_state_incorrect(self): """Test final state incorrect if initial state not zero""" desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) qc = QuantumCircuit(2) qc.x(0) qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) actual_sv = Statevector(qc) self.assertFalse(desired_sv == actual_sv) @data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) def test_inverse(self, state): """Test inverse of StatePreparation""" qc = QuantumCircuit(2) stateprep = StatePreparation(state) qc.append(stateprep, [0, 1]) qc.append(stateprep.inverse(), [0, 1]) self.assertTrue(np.allclose(Operator(qc).data, np.identity(2**qc.num_qubits))) def test_double_inverse(self): """Test twice inverse of StatePreparation""" desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) qc = QuantumCircuit(2) stateprep = StatePreparation([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) qc.append(stateprep.inverse().inverse(), [0, 1]) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv) def test_incompatible_state_and_qubit_args(self): """Test error raised if number of qubits not compatible with state arg""" qc = QuantumCircuit(3) with self.assertRaises(QiskitError): qc.prepare_state("11") def test_incompatible_int_state_and_qubit_args(self): """Test error raised if number of qubits not compatible with integer state arg""" # pylint: disable=pointless-statement with self.assertRaises(QiskitError): stateprep = StatePreparation(5, num_qubits=2) stateprep.definition def test_int_state_and_no_qubit_args(self): """Test automatic determination of qubit number""" stateprep = StatePreparation(5) self.assertEqual(stateprep.num_qubits, 3) def test_repeats(self): """Test repeat function repeats correctly""" qc = QuantumCircuit(2) qc.append(StatePreparation("01").repeat(2), [0, 1]) self.assertEqual(qc.decompose().count_ops()["state_preparation"], 2) if __name__ == "__main__": unittest.main()
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/GroenteLepel/qiskit-quantum-knn
GroenteLepel
from typing import Optional import numpy as np import qiskit as qk import qiskit.extensions.quantum_initializer as qi from qiskit.circuit.controlledgate import ControlledGate from qiskit.circuit.gate import Gate """ Extra file containing some decomposed quantum gates to get familiar with them and Qiskit. """ def swap(): """A self-written decomposition of the SWAP-gate. Example: .. jupyter-execute:: from qiskit_quantum_knn.qknn.quantumgates import swap swap_circ = swap() print(swap_circ.definition.draw()) Returns: Instruction: the SWAP-gate. """ swap_circuit = qk.QuantumCircuit(2, name='swap_gate') swap_circuit.cx(0, 1) swap_circuit.cx(1, 0) swap_circuit.cx(0, 1) return swap_circuit.to_instruction() def fidelity_instruction(): r"""A decomposition of the SWAP-measurement. The fidelity between the state on ``q_1`` and the state on ``q_2`` is defined as: .. math:: \mathbb{P}(q_0 = 0) - \mathbb{P}(q_0 = 1) Example: .. jupyter-execute:: from qiskit_quantum_knn.qknn.quantumgates import fidelity_instruction fid_inst = fidelity_instruction() print(fid_inst.definition.draw()) Returns: Instruction: The Fidelity gate (swap measurement). """ fidelity_circ = qk.QuantumCircuit(3, 1) fidelity_circ.h(0) fidelity_circ.cswap(0, 1, 2) fidelity_circ.h(0) fidelity_circ.measure(0, 0) fidelity_instr = fidelity_circ.to_instruction() return fidelity_instr def init_to_state(reg_to_init: qk.QuantumRegister, init_state: np.ndarray, name: Optional[str] = None) -> Gate: """Initialize a :class:`QuantumRegister` to the provided state. Args: reg_to_init (QuantumRegister): register which needs to be initialized. init_state (np.ndarray): state to which the :py:attr:`reg_to_init` must be initialized to. name (str): optional, name for the ``init_gate``. Raises: ValueError: if the register and state do not have the same dimension. Returns: Gate: The initialiser. A gate of size ``reg_to_init.size`` which performs the initialization. """ # check if provided values are correct if len(init_state) != 2 ** len(reg_to_init): raise ValueError( "Dimensionality of the init_state does not coincide with the " "length of the register to initialise to: is {0} and {1}".format( len(init_state), len(reg_to_init) ) ) init_circ = qk.QuantumCircuit(reg_to_init, name=name) # create temp circuit init = qi.Isometry(init_state, 0, 0) # create Isometry for init init_circ.append(init, reg_to_init) # apply init to temp circuit basis_gates = ['u1', 'u2', 'u3', 'cx'] # list basis gates # transpile circuit so that it is decomposed to the basis gates above, # making it unitary and possible to convert from Instruction to Gate transpiled = qk.transpile(init_circ, basis_gates=basis_gates) init_gate = transpiled.to_gate() # convert to Gate return init_gate def controlled_initialize(reg_to_init: qk.QuantumRegister, init_state: np.ndarray, num_ctrl_qubits: Optional[int] = 1, name: Optional[str] = None) -> ControlledGate: """Initialize a register to provided state with control. This method uses :py:func:`init_to_state` to create the initialiser. Args: reg_to_init (QuantumRegister): register which needs to be initialized. init_state (np.ndarray): state to which the ``reg_to_init`` must be initialized to. num_ctrl_qubits (int): optional, number of desired controls. name (str): optional, name for the ``init_gate``. Returns: ControlledGate: The produced controlled initialise. A Gate of size ``reg_to_init.size + num_ctrl_qubits`` which performs the initialize with control. """ # create the init state init_gate = init_to_state(reg_to_init, init_state, name) # make it controlled controlled_init = init_gate.control(num_ctrl_qubits=num_ctrl_qubits) return controlled_init
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
Aman-Agrawal01
# 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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ( ElectronicStructureDriverType, ElectronicStructureMoleculeDriver, PySCFDriver, ) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer from qiskit_nature.settings import settings settings.dict_aux_operators = True molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = ElectronicStructureMoleculeDriver( molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF ) # or equivalently: driver = PySCFDriver.from_molecule(molecule, basis="sto3g") transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so: second_q_ops = problem.second_q_ops() hamiltonian = second_q_ops["ElectronicEnergy"] print(hamiltonian) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo from qiskit_nature.second_q.transformers import FreezeCoreTransformer molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") # this is now done explicitly problem = driver.run() transformer = FreezeCoreTransformer() # and you also apply transformers explicitly problem = transformer.transform(problem) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = PySCFDriver.from_molecule(molecule) result = driver.run() print(type(result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") result = driver.run() print(type(result)) from qiskit_nature.drivers.second_quantization import FCIDumpDriver path_to_fcidump = "aux_files/h2.fcidump" driver = FCIDumpDriver(path_to_fcidump) result = driver.run() print(type(result)) from qiskit_nature.second_q.formats.fcidump import FCIDump path_to_fcidump = "aux_files/h2.fcidump" fcidump = FCIDump.from_file(path_to_fcidump) print(type(fcidump)) from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem problem = fcidump_to_problem(fcidump) print(type(problem)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer driver = PySCFDriver() transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("ElectronicEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer driver = PySCFDriver() problem = driver.run() transformer = FreezeCoreTransformer() problem = transformer.transform(problem) hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the VF2Layout pass""" import rustworkx from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import ControlFlowOp from qiskit.circuit.library import CXGate, XGate from qiskit.transpiler import CouplingMap, Layout, TranspilerError from qiskit.transpiler.passes.layout.vf2_post_layout import VF2PostLayout, VF2PostLayoutStopReason from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeLima, FakeYorktown, FakeLimaV2, FakeYorktownV2 from qiskit.circuit import Qubit from qiskit.compiler.transpiler import transpile from qiskit.transpiler.target import Target, InstructionProperties class TestVF2PostLayout(QiskitTestCase): """Tests the VF2Layout pass""" seed = 42 def assertLayout(self, dag, coupling_map, property_set): """Checks if the circuit in dag was a perfect layout in property_set for the given coupling_map""" self.assertEqual( property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND ) layout = property_set["post_layout"] edges = coupling_map.graph.edge_list() def run(dag, wire_map): for gate in dag.two_qubit_ops(): if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp): continue physical_q0 = wire_map[gate.qargs[0]] physical_q1 = wire_map[gate.qargs[1]] self.assertTrue((physical_q0, physical_q1) in edges) for node in dag.op_nodes(ControlFlowOp): for block in node.op.blocks: inner_wire_map = { inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits) } run(circuit_to_dag(block), inner_wire_map) run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout}) def assertLayoutV2(self, dag, target, property_set): """Checks if the circuit in dag was a perfect layout in property_set for the given coupling_map""" self.assertEqual( property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND ) layout = property_set["post_layout"] def run(dag, wire_map): for gate in dag.two_qubit_ops(): if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp): continue physical_q0 = wire_map[gate.qargs[0]] physical_q1 = wire_map[gate.qargs[1]] qargs = (physical_q0, physical_q1) self.assertTrue(target.instruction_supported(gate.name, qargs)) for node in dag.op_nodes(ControlFlowOp): for block in node.op.blocks: inner_wire_map = { inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits) } run(circuit_to_dag(block), inner_wire_map) run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout}) def test_no_constraints(self): """Test we raise at runtime if no target or coupling graph specified.""" qc = QuantumCircuit(2) empty_pass = VF2PostLayout() with self.assertRaises(TranspilerError): empty_pass.run(circuit_to_dag(qc)) def test_no_backend_properties(self): """Test we raise at runtime if no properties are provided with a coupling graph.""" qc = QuantumCircuit(2) empty_pass = VF2PostLayout(coupling_map=CouplingMap([(0, 1), (1, 2)])) with self.assertRaises(TranspilerError): empty_pass.run(circuit_to_dag(qc)) def test_empty_circuit(self): """Test no solution found for empty circuit""" qc = QuantumCircuit(2, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_empty_circuit_v2(self): """Test no solution found for empty circuit with v2 backend""" qc = QuantumCircuit(2, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_skip_3q_circuit(self): """Test that the pass is a no-op on circuits with >2q gates.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_skip_3q_circuit_control_flow(self): """Test that the pass is a no-op on circuits with >2q gates.""" qc = QuantumCircuit(3) with qc.for_loop((1,)): qc.ccx(0, 1, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_skip_3q_circuit_v2(self): """Test that the pass is a no-op on circuits with >2q gates with a target.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_skip_3q_circuit_control_flow_v2(self): """Test that the pass is a no-op on circuits with >2q gates with a target.""" qc = QuantumCircuit(3) with qc.for_loop((1,)): qc.ccx(0, 1, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_best_mapping_ghz_state_full_device_multiple_qregs(self): """Test best mappings with multiple registers""" backend = FakeLima() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) qc.h(qr_a[0]) qc.cx(qr_a[0], qr_a[1]) qc.cx(qr_a[0], qr_b[0]) qc.cx(qr_a[0], qr_b[1]) qc.cx(qr_a[0], qr_b[2]) qc.measure_all() tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktown() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_controlflow(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktown() circuit = QuantumCircuit(2, 1) with circuit.for_loop((1,)): circuit.cx(1, 0) # qr1 -> qr0 with circuit.if_test((circuit.clbits[0], True)) as else_: pass with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(1, 0) # qr1 -> qr0 initial_layout = Layout(dict(enumerate(circuit.qubits))) circuit._layout = initial_layout dag = circuit_to_dag(circuit) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_max_trials(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ max_trials = 11 backend = FakeYorktown() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout( coupling_map=cmap, properties=props, seed=self.seed, max_trials=max_trials ) with self.assertLogs( "qiskit.transpiler.passes.layout.vf2_post_layout", level="DEBUG" ) as cm: pass_.run(dag) self.assertIn( f"DEBUG:qiskit.transpiler.passes.layout.vf2_post_layout:Trial {max_trials} " f"is >= configured max trials {max_trials}", cm.output, ) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_best_mapping_ghz_state_full_device_multiple_qregs_v2(self): """Test best mappings with multiple registers""" backend = FakeLimaV2() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) qc.h(qr_a[0]) qc.cx(qr_a[0], qr_a[1]) qc.cx(qr_a[0], qr_b[0]) qc.cx(qr_a[0], qr_b[1]) qc.cx(qr_a[0], qr_b[2]) qc.measure_all() tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout dag = circuit_to_dag(tqc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_v2(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktownV2() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_v2_control_flow(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktownV2() circuit = QuantumCircuit(2, 1) with circuit.for_loop((1,)): circuit.cx(1, 0) # qr1 -> qr0 with circuit.if_test((circuit.clbits[0], True)) as else_: pass with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(1, 0) # qr1 -> qr0 initial_layout = Layout(dict(enumerate(circuit.qubits))) circuit._layout = initial_layout dag = circuit_to_dag(circuit) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_target_invalid_2q_gate(self): """Test that we don't find a solution with a gate outside target.""" backend = FakeYorktownV2() qc = QuantumCircuit(2) qc.ecr(0, 1) dag = circuit_to_dag(qc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertEqual( pass_.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_target_invalid_2q_gate_control_flow(self): """Test that we don't find a solution with a gate outside target.""" backend = FakeYorktownV2() qc = QuantumCircuit(2) with qc.for_loop((1,)): qc.ecr(0, 1) dag = circuit_to_dag(qc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed) pass_.run(dag) self.assertEqual( pass_.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_target_no_error(self): """Test that running vf2layout on a pass against a target with no error rates works.""" n_qubits = 15 target = Target() target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)}) vf2_pass = VF2PostLayout(target=target) circuit = QuantumCircuit(2) circuit.cx(0, 1) dag = circuit_to_dag(circuit) vf2_pass.run(dag) self.assertNotIn("post_layout", vf2_pass.property_set) def test_target_some_error(self): """Test that running vf2layout on a pass against a target with some error rates works.""" n_qubits = 15 target = Target() target.add_instruction( XGate(), {(i,): InstructionProperties(error=0.00123) for i in range(n_qubits)} ) target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)}) vf2_pass = VF2PostLayout(target=target, seed=1234, strict_direction=False) circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) dag = circuit_to_dag(circuit) vf2_pass.run(dag) # No layout selected because nothing will beat initial layout self.assertNotIn("post_layout", vf2_pass.property_set) class TestVF2PostLayoutScoring(QiskitTestCase): """Test scoring heuristic function for VF2PostLayout.""" def test_empty_score(self): """Test error rate is 0 for empty circuit.""" bit_map = {} reverse_bit_map = {} im_graph = rustworkx.PyDiGraph() backend = FakeYorktownV2() vf2_pass = VF2PostLayout(target=backend.target) layout = Layout() score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph) self.assertEqual(0, score) def test_all_1q_score(self): """Test error rate for all 1q input.""" bit_map = {Qubit(): 0, Qubit(): 1} reverse_bit_map = {v: k for k, v in bit_map.items()} im_graph = rustworkx.PyDiGraph() im_graph.add_node({"sx": 1}) im_graph.add_node({"sx": 1}) backend = FakeYorktownV2() vf2_pass = VF2PostLayout(target=backend.target) layout = Layout(bit_map) score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph) self.assertAlmostEqual(0.002925, score, places=5) class TestVF2PostLayoutUndirected(QiskitTestCase): """Tests the VF2Layout pass""" seed = 42 def assertLayout(self, dag, coupling_map, property_set): """Checks if the circuit in dag was a perfect layout in property_set for the given coupling_map""" self.assertEqual( property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND ) layout = property_set["post_layout"] for gate in dag.two_qubit_ops(): if dag.has_calibration_for(gate): continue physical_q0 = layout[gate.qargs[0]] physical_q1 = layout[gate.qargs[1]] self.assertTrue(coupling_map.graph.has_edge(physical_q0, physical_q1)) def assertLayoutV2(self, dag, target, property_set): """Checks if the circuit in dag was a perfect layout in property_set for the given coupling_map""" self.assertEqual( property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND ) layout = property_set["post_layout"] for gate in dag.two_qubit_ops(): if dag.has_calibration_for(gate): continue physical_q0 = layout[gate.qargs[0]] physical_q1 = layout[gate.qargs[1]] qargs = (physical_q0, physical_q1) self.assertTrue(target.instruction_supported(gate.name, qargs)) def test_no_constraints(self): """Test we raise at runtime if no target or coupling graph specified.""" qc = QuantumCircuit(2) empty_pass = VF2PostLayout(strict_direction=False) with self.assertRaises(TranspilerError): empty_pass.run(circuit_to_dag(qc)) def test_no_backend_properties(self): """Test we raise at runtime if no properties are provided with a coupling graph.""" qc = QuantumCircuit(2) empty_pass = VF2PostLayout( coupling_map=CouplingMap([(0, 1), (1, 2)]), strict_direction=False ) with self.assertRaises(TranspilerError): empty_pass.run(circuit_to_dag(qc)) def test_empty_circuit(self): """Test no solution found for empty circuit""" qc = QuantumCircuit(2, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_empty_circuit_v2(self): """Test no solution found for empty circuit with v2 backend""" qc = QuantumCircuit(2, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.NO_SOLUTION_FOUND, ) def test_skip_3q_circuit(self): """Test that the pass is a no-op on circuits with >2q gates.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) backend = FakeLima() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_skip_3q_circuit_v2(self): """Test that the pass is a no-op on circuits with >2q gates with a target.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) backend = FakeLimaV2() vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False) vf2_pass.run(circuit_to_dag(qc)) self.assertEqual( vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) def test_best_mapping_ghz_state_full_device_multiple_qregs(self): """Test best mappings with multiple registers""" backend = FakeLima() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) qc.h(qr_a[0]) qc.cx(qr_a[0], qr_a[1]) qc.cx(qr_a[0], qr_b[0]) qc.cx(qr_a[0], qr_b[1]) qc.cx(qr_a[0], qr_b[2]) qc.measure_all() tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout( coupling_map=cmap, properties=props, seed=self.seed, strict_direction=False ) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktown() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() pass_ = VF2PostLayout( coupling_map=cmap, properties=props, seed=self.seed, strict_direction=False ) pass_.run(dag) self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_best_mapping_ghz_state_full_device_multiple_qregs_v2(self): """Test best mappings with multiple registers""" backend = FakeLimaV2() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) qc.h(qr_a[0]) qc.cx(qr_a[0], qr_a[1]) qc.cx(qr_a[0], qr_b[0]) qc.cx(qr_a[0], qr_b[1]) qc.cx(qr_a[0], qr_b[2]) qc.measure_all() tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout dag = circuit_to_dag(tqc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_v2(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 """ backend = FakeYorktownV2() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False) pass_.run(dag) self.assertLayoutV2(dag, backend.target, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Helper function for converting a dag to a circuit.""" import copy from qiskit.circuit import QuantumCircuit, CircuitInstruction def dag_to_circuit(dag, copy_operations=True): """Build a ``QuantumCircuit`` object from a ``DAGCircuit``. Args: dag (DAGCircuit): the input dag. copy_operations (bool): Deep copy the operation objects in the :class:`~.DAGCircuit` for the output :class:`~.QuantumCircuit`. This should only be set to ``False`` if the input :class:`~.DAGCircuit` will not be used anymore as the operations in the output :class:`~.QuantumCircuit` will be shared instances and modifications to operations in the :class:`~.DAGCircuit` will be reflected in the :class:`~.QuantumCircuit` (and vice versa). Return: QuantumCircuit: the circuit representing the input dag. Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl') """ name = dag.name or None circuit = QuantumCircuit( dag.qubits, dag.clbits, *dag.qregs.values(), *dag.cregs.values(), name=name, global_phase=dag.global_phase, ) circuit.metadata = dag.metadata circuit.calibrations = dag.calibrations for node in dag.topological_op_nodes(): op = node.op if copy_operations: op = copy.deepcopy(op) circuit._append(CircuitInstruction(op, node.qargs, node.cargs)) circuit.duration = dag.duration circuit.unit = dag.unit return circuit
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit_textbook.problems import dj_problem_oracle def lab1_ex1(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) return qc state = Statevector.from_instruction(lab1_ex1()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex1 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex1(lab1_ex1()) def lab1_ex2(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) return qc state = Statevector.from_instruction(lab1_ex2()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex2 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex2(lab1_ex2()) def lab1_ex3(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) qc.h(0) return qc state = Statevector.from_instruction(lab1_ex3()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex3 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex3(lab1_ex3()) def lab1_ex4(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.sdg(0) return qc state = Statevector.from_instruction(lab1_ex4()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex4 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex4(lab1_ex4()) def lab1_ex5(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.cx(0,1) qc.x(0) return qc qc = lab1_ex5() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex5 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex5(lab1_ex5()) qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0 qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1 backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def lab1_ex6(): # # # FILL YOUR CODE IN HERE # # qc = QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cx(1,2) qc.y(1) return qc qc = lab1_ex6() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex6 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex6(lab1_ex6()) oraclenr = 4 # determines the oracle (can range from 1 to 5) oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles oracle.name = "DJ-Oracle" def dj_classical(n, input_str): # build a quantum circuit with n qubits and 1 classical readout bit dj_circuit = QuantumCircuit(n+1,1) # Prepare the initial state corresponding to your input bit string for i in range(n): if input_str[i] == '1': dj_circuit.x(i) # append oracle dj_circuit.append(oracle, range(n+1)) # measure the fourth qubit dj_circuit.measure(n,0) return dj_circuit n = 4 # number of qubits input_str = '1111' dj_circuit = dj_classical(n, input_str) dj_circuit.draw() # draw the circuit input_str = '1111' dj_circuit = dj_classical(n, input_str) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit, qasm_sim) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) def lab1_ex7(): min_nr_inputs = 2 max_nr_inputs = 9 return [min_nr_inputs, max_nr_inputs] from qc_grader import grade_lab1_ex7 # Note that the grading function is expecting a list of two integers grade_lab1_ex7(lab1_ex7()) n=4 def psi_0(n): qc = QuantumCircuit(n+1,n) # Build the state (|00000> - |10000>)/sqrt(2) # # # FILL YOUR CODE IN HERE # # qc.x(4) qc.h(4) return qc dj_circuit = psi_0(n) dj_circuit.draw() def psi_1(n): # obtain the |psi_0> = |00001> state qc = psi_0(n) # create the superposition state |psi_1> # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # # qc.barrier() return qc dj_circuit = psi_1(n) dj_circuit.draw() def psi_2(oracle,n): # circuit to obtain psi_1 qc = psi_1(n) # append the oracle qc.append(oracle, range(n+1)) return qc dj_circuit = psi_2(oracle, n) dj_circuit.draw() def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25]) qc = psi_2(oracle, n) # apply n-fold hadamard gate # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # add the measurement by connecting qubits to classical bits # # qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) # # return qc dj_circuit = lab1_ex8(oracle, n) dj_circuit.draw() from qc_grader import grade_lab1_ex8 # Note that the grading function is expecting a quantum circuit with measurements grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n)) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/ShabaniLab/q-camp
ShabaniLab
import numpy as np a = -1 b = 2.3 z = 2 + 3j # type of a variable print(type(a)) print(type(b)) print(type(z)) # real and imaginary parts print(np.real(z)) print(np.imag(z)) # conjugation print(z) print(np.conjugate(z)) # plot the conjugates import matplotlib.pyplot as plt # make figure fig = plt.figure() # get the axes ax = plt.axes() # here we use "scatter" to plot individual points on the 2D plane ax.scatter(0, 0, marker='o', color='gray') ax.scatter(np.real(z), np.imag(z), marker='s', label="$z$") ax.scatter(np.real(np.conjugate(z)), np.imag(np.conjugate(z)), marker='*', label="$z^*$") # fix the axis limit ax.set_xlim([-4, 4]) ax.set_ylim([-4, 4]) # show the grid lines ax.grid() # show the labels ax.legend() # show the plot plt.show() # multiplication print(np.sqrt(np.conjugate(z)*z)) # norm / absolute value print(np.sqrt(2.0*2.0 + 3*3)) print(np.absolute(z)) # in radians print(np.angle(z)) # in angles print(np.angle(z, deg=True)) c = -1 z = 0 # define an array max_iteration = 1000 threshold = 10 A = np.zeros(max_iteration, dtype=np.complex128) r = np.linspace(-2, 2, 201) i = np.linspace(-2, 2, 201) def convergence(z): for index in range(max_iteration): f = z**2 + c # A[index] = f z = f if np.absolute(z) > threshold: return False return True convergence_array = np.zeros((201, 201)) for index_real in range(101): for index_imag in range(101): z = r[index_real] + 1j*i[index_imag] if convergence(z): convergence_array[index_real, index_imag] = np.abs(z) # make figure fig = plt.figure() # get the axes ax = plt.axes() # ax.scatter(np.real(A), np.imag(A)) ax.imshow(convergence_array) plt.show()
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Qiskit runtime service.""" import logging from typing import Dict, Callable, Optional, Union, List, Any, Type import json import warnings from qiskit.providers.exceptions import QiskitBackendNotFoundError from qiskit.providers.ibmq import accountprovider # pylint: disable=unused-import from .runtime_job import RuntimeJob from .runtime_program import RuntimeProgram, ParameterNamespace from .utils import RuntimeDecoder, to_base64_string from .exceptions import (QiskitRuntimeError, RuntimeDuplicateProgramError, RuntimeProgramNotFound, RuntimeJobNotFound) from .program.result_decoder import ResultDecoder from .runtime_options import RuntimeOptions from ..api.clients.runtime import RuntimeClient from ..api.exceptions import RequestsApiError from ..exceptions import IBMQNotAuthorizedError, IBMQInputValueError, IBMQProviderError from ..ibmqbackend import IBMQRetiredBackend from ..credentials import Credentials logger = logging.getLogger(__name__) class IBMRuntimeService: """Class for interacting with the Qiskit Runtime service. Qiskit Runtime is a new architecture offered by IBM Quantum that streamlines computations requiring many iterations. These experiments will execute significantly faster within its improved hybrid quantum/classical process. The Qiskit Runtime Service allows authorized users to upload their Qiskit quantum programs. A Qiskit quantum program, also called a runtime program, is a piece of Python code and its metadata that takes certain inputs, performs quantum and maybe classical processing, and returns the results. The same or other authorized users can invoke these quantum programs by simply passing in parameters. A sample workflow of using the runtime service:: from qiskit import IBMQ, QuantumCircuit from qiskit.providers.ibmq import RunnerResult provider = IBMQ.load_account() backend = provider.backend.ibmq_qasm_simulator # List all available programs. provider.runtime.pprint_programs() # Create a circuit. qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure_all() # Set the "circuit-runner" program parameters params = provider.runtime.program(program_id="circuit-runner").parameters() params.circuits = qc params.measurement_error_mitigation = True # Configure backend options options = {'backend_name': backend.name()} # Execute the circuit using the "circuit-runner" program. job = provider.runtime.run(program_id="circuit-runner", options=options, inputs=params) # Get runtime job result. result = job.result(decoder=RunnerResult) If the program has any interim results, you can use the ``callback`` parameter of the :meth:`run` method to stream the interim results. Alternatively, you can use the :meth:`RuntimeJob.stream_results` method to stream the results at a later time, but before the job finishes. The :meth:`run` method returns a :class:`~qiskit.providers.ibmq.runtime.RuntimeJob` object. You can use its methods to perform tasks like checking job status, getting job result, and canceling job. """ def __init__(self, provider: 'accountprovider.AccountProvider') -> None: """IBMRuntimeService constructor. Args: provider: IBM Quantum account provider. """ self._provider = provider self._api_client = RuntimeClient(provider.credentials) self._access_token = provider.credentials.access_token self._ws_url = provider.credentials.runtime_url.replace('https', 'wss') self._programs = {} # type: Dict def pprint_programs(self, refresh: bool = False, detailed: bool = False, limit: int = 20, skip: int = 0) -> None: """Pretty print information about available runtime programs. Args: refresh: If ``True``, re-query the server for the programs. Otherwise return the cached value. detailed: If ``True`` print all details about available runtime programs. limit: The number of programs returned at a time. Default and maximum value of 20. skip: The number of programs to skip. """ programs = self.programs(refresh, limit, skip) for prog in programs: print("="*50) if detailed: print(str(prog)) else: print(f"{prog.program_id}:",) print(f" Name: {prog.name}") print(f" Description: {prog.description}") def programs(self, refresh: bool = False, limit: int = 20, skip: int = 0) -> List[RuntimeProgram]: """Return available runtime programs. Currently only program metadata is returned. Args: refresh: If ``True``, re-query the server for the programs. Otherwise return the cached value. limit: The number of programs returned at a time. ``None`` means no limit. skip: The number of programs to skip. Returns: A list of runtime programs. """ if skip is None: skip = 0 if not self._programs or refresh: self._programs = {} current_page_limit = 20 offset = 0 while True: response = self._api_client.list_programs(limit=current_page_limit, skip=offset) program_page = response.get("programs", []) # count is the total number of programs that would be returned if # there was no limit or skip count = response.get("count", 0) for prog_dict in program_page: program = self._to_program(prog_dict) self._programs[program.program_id] = program if len(self._programs) == count: # Stop if there are no more programs returned by the server. break offset += len(program_page) if limit is None: limit = len(self._programs) return list(self._programs.values())[skip:limit+skip] def program(self, program_id: str, refresh: bool = False) -> RuntimeProgram: """Retrieve a runtime program. Currently only program metadata is returned. Args: program_id: Program ID. refresh: If ``True``, re-query the server for the program. Otherwise return the cached value. Returns: Runtime program. Raises: RuntimeProgramNotFound: If the program does not exist. QiskitRuntimeError: If the request failed. """ if program_id not in self._programs or refresh: try: response = self._api_client.program_get(program_id) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeProgramNotFound(f"Program not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to get program: {ex}") from None self._programs[program_id] = self._to_program(response) return self._programs[program_id] def _to_program(self, response: Dict) -> RuntimeProgram: """Convert server response to ``RuntimeProgram`` instances. Args: response: Server response. Returns: A ``RuntimeProgram`` instance. """ backend_requirements = {} parameters = {} return_values = {} interim_results = {} if "spec" in response: backend_requirements = response["spec"].get('backend_requirements', {}) parameters = response["spec"].get('parameters', {}) return_values = response["spec"].get('return_values', {}) interim_results = response["spec"].get('interim_results', {}) return RuntimeProgram(program_name=response['name'], program_id=response['id'], description=response.get('description', ""), parameters=parameters, return_values=return_values, interim_results=interim_results, max_execution_time=response.get('cost', 0), creation_date=response.get('creation_date', ""), update_date=response.get('update_date', ""), backend_requirements=backend_requirements, is_public=response.get('is_public', False), data=response.get('data', ""), api_client=self._api_client) def run( self, program_id: str, options: Union[RuntimeOptions, Dict], inputs: Union[Dict, ParameterNamespace], callback: Optional[Callable] = None, result_decoder: Optional[Type[ResultDecoder]] = None, image: Optional[str] = "" ) -> RuntimeJob: """Execute the runtime program. Args: program_id: Program ID. options: Runtime options that control the execution environment. See :class:`RuntimeOptions` for all available options. Currently the only required option is ``backend_name``. inputs: Program input parameters. These input values are passed to the runtime program. callback: Callback function to be invoked for any interim results. The callback function will receive 2 positional parameters: 1. Job ID 2. Job interim result. result_decoder: A :class:`ResultDecoder` subclass used to decode job results. ``ResultDecoder`` is used if not specified. image: (DEPRECATED) The runtime image used to execute the program, specified in the form of image_name:tag. Not all accounts are authorized to select a different image. Returns: A ``RuntimeJob`` instance representing the execution. Raises: IBMQInputValueError: If input is invalid. """ if isinstance(options, dict): options = RuntimeOptions(**options) if image: warnings.warn("Passing the 'image' keyword to IBMRuntimeService.run is " "deprecated and will be removed in a future release. " "Please pass it in as part of 'options'.", DeprecationWarning, stacklevel=2) options.image = image options.validate() # If using params object, extract as dictionary if isinstance(inputs, ParameterNamespace): inputs.validate() inputs = vars(inputs) backend_name = options.backend_name result_decoder = result_decoder or ResultDecoder response = self._api_client.program_run(program_id=program_id, credentials=self._provider.credentials, backend_name=backend_name, params=inputs, image=options.image, log_level=options.log_level) backend = self._provider.get_backend(backend_name) job = RuntimeJob(backend=backend, api_client=self._api_client, credentials=self._provider.credentials, job_id=response['id'], program_id=program_id, params=inputs, user_callback=callback, result_decoder=result_decoder, image=options.image) return job def upload_program( self, data: str, metadata: Optional[Union[Dict, str]] = None ) -> str: """Upload a runtime program. In addition to program data, the following program metadata is also required: - name - max_execution_time - description Program metadata can be specified using the `metadata` parameter or individual parameter (for example, `name` and `description`). If the same metadata field is specified in both places, the individual parameter takes precedence. For example, if you specify:: upload_program(metadata={"name": "name1"}, name="name2") ``name2`` will be used as the program name. Args: data: Program data or path of the file containing program data to upload. metadata: Name of the program metadata file or metadata dictionary. A metadata file needs to be in the JSON format. The ``parameters``, ``return_values``, and ``interim_results`` should be defined as JSON Schema. See :file:`program/program_metadata_sample.json` for an example. The fields in metadata are explained below. * name: Name of the program. Required. * max_execution_time: Maximum execution time in seconds. Required. * description: Program description. Required. * is_public: Whether the runtime program should be visible to the public. The default is ``False``. * spec: Specifications for backend characteristics and input parameters required to run the program, interim results and final result. * backend_requirements: Backend requirements. * parameters: Program input parameters in JSON schema format. * return_values: Program return values in JSON schema format. * interim_results: Program interim results in JSON schema format. Returns: Program ID. Raises: IBMQInputValueError: If required metadata is missing. RuntimeDuplicateProgramError: If a program with the same name already exists. IBMQNotAuthorizedError: If you are not authorized to upload programs. QiskitRuntimeError: If the upload failed. """ program_metadata = self._read_metadata(metadata=metadata) for req in ['name', 'description', 'max_execution_time']: if req not in program_metadata or not program_metadata[req]: raise IBMQInputValueError(f"{req} is a required metadata field.") if "def main(" not in data: # This is the program file with open(data, "r") as file: data = file.read() try: program_data = to_base64_string(data) response = self._api_client.program_create(program_data=program_data, **program_metadata) except RequestsApiError as ex: if ex.status_code == 409: raise RuntimeDuplicateProgramError( "Program with the same name already exists.") from None if ex.status_code == 403: raise IBMQNotAuthorizedError( "You are not authorized to upload programs.") from None raise QiskitRuntimeError(f"Failed to create program: {ex}") from None return response['id'] def _read_metadata( self, metadata: Optional[Union[Dict, str]] = None ) -> Dict: """Read metadata. Args: metadata: Name of the program metadata file or metadata dictionary. Returns: Return metadata. """ upd_metadata: dict = {} if metadata is not None: if isinstance(metadata, str): with open(metadata, 'r') as file: upd_metadata = json.load(file) else: upd_metadata = metadata # TODO validate metadata format metadata_keys = ['name', 'max_execution_time', 'description', 'spec', 'is_public'] return {key: val for key, val in upd_metadata.items() if key in metadata_keys} def update_program( self, program_id: str, data: str = None, metadata: Optional[Union[Dict, str]] = None, name: str = None, description: str = None, max_execution_time: int = None, spec: Optional[Dict] = None ) -> None: """Update a runtime program. Program metadata can be specified using the `metadata` parameter or individual parameters, such as `name` and `description`. If the same metadata field is specified in both places, the individual parameter takes precedence. Args: program_id: Program ID. data: Program data or path of the file containing program data to upload. metadata: Name of the program metadata file or metadata dictionary. name: New program name. description: New program description. max_execution_time: New maximum execution time. spec: New specifications for backend characteristics, input parameters, interim results and final result. Raises: RuntimeProgramNotFound: If the program doesn't exist. QiskitRuntimeError: If the request failed. """ if not any([data, metadata, name, description, max_execution_time, spec]): warnings.warn("None of the 'data', 'metadata', 'name', 'description', " "'max_execution_time', or 'spec' parameters is specified. " "No update is made.") return if data: if "def main(" not in data: # This is the program file with open(data, "r") as file: data = file.read() data = to_base64_string(data) if metadata: metadata = self._read_metadata(metadata=metadata) combined_metadata = self._merge_metadata( metadata=metadata, name=name, description=description, max_execution_time=max_execution_time, spec=spec) try: self._api_client.program_update( program_id, program_data=data, **combined_metadata) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeProgramNotFound(f"Program not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to update program: {ex}") from None if program_id in self._programs: program = self._programs[program_id] program._refresh() def _merge_metadata( self, metadata: Optional[Dict] = None, **kwargs: Any ) -> Dict: """Merge multiple copies of metadata. Args: metadata: Program metadata. **kwargs: Additional metadata fields to overwrite. Returns: Merged metadata. """ merged = {} metadata = metadata or {} metadata_keys = ['name', 'max_execution_time', 'description', 'spec'] for key in metadata_keys: if kwargs.get(key, None) is not None: merged[key] = kwargs[key] elif key in metadata.keys(): merged[key] = metadata[key] return merged def delete_program(self, program_id: str) -> None: """Delete a runtime program. Args: program_id: Program ID. Raises: RuntimeProgramNotFound: If the program doesn't exist. QiskitRuntimeError: If the request failed. """ try: self._api_client.program_delete(program_id=program_id) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeProgramNotFound(f"Program not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to delete program: {ex}") from None if program_id in self._programs: del self._programs[program_id] def set_program_visibility(self, program_id: str, public: bool) -> None: """Sets a program's visibility. Args: program_id: Program ID. public: If ``True``, make the program visible to all. If ``False``, make the program visible to just your account. Raises: RuntimeJobNotFound: if program not found (404) QiskitRuntimeError: if update failed (401, 403) """ try: self._api_client.set_program_visibility(program_id, public) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeJobNotFound(f"Program not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to set program visibility: {ex}") from None if program_id in self._programs: program = self._programs[program_id] program._is_public = public def job(self, job_id: str) -> RuntimeJob: """Retrieve a runtime job. Args: job_id: Job ID. Returns: Runtime job retrieved. Raises: RuntimeJobNotFound: If the job doesn't exist. QiskitRuntimeError: If the request failed. """ try: response = self._api_client.job_get(job_id) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeJobNotFound(f"Job not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to delete job: {ex}") from None return self._decode_job(response) def jobs( self, limit: Optional[int] = 10, skip: int = 0, pending: bool = None, program_id: str = None ) -> List[RuntimeJob]: """Retrieve all runtime jobs, subject to optional filtering. Args: limit: Number of jobs to retrieve. ``None`` means no limit. skip: Starting index for the job retrieval. pending: Filter by job pending state. If ``True``, 'QUEUED' and 'RUNNING' jobs are included. If ``False``, 'DONE', 'CANCELLED' and 'ERROR' jobs are included. program_id: Filter by Program ID. Returns: A list of runtime jobs. """ job_responses = [] # type: List[Dict[str, Any]] current_page_limit = limit or 20 offset = skip while True: jobs_response = self._api_client.jobs_get( limit=current_page_limit, skip=offset, pending=pending, program_id=program_id) job_page = jobs_response["jobs"] # count is the total number of jobs that would be returned if # there was no limit or skip count = jobs_response["count"] job_responses += job_page if len(job_responses) == count - skip: # Stop if there are no more jobs returned by the server. break if limit: if len(job_responses) >= limit: # Stop if we have reached the limit. break current_page_limit = limit - len(job_responses) else: current_page_limit = 20 offset += len(job_page) return [self._decode_job(job) for job in job_responses] def delete_job(self, job_id: str) -> None: """Delete a runtime job. Note that this operation cannot be reversed. Args: job_id: ID of the job to delete. Raises: RuntimeJobNotFound: If the job doesn't exist. QiskitRuntimeError: If the request failed. """ try: self._api_client.job_delete(job_id) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeJobNotFound(f"Job not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to delete job: {ex}") from None def _decode_job(self, raw_data: Dict) -> RuntimeJob: """Decode job data received from the server. Args: raw_data: Raw job data received from the server. Returns: Decoded job data. """ hub = raw_data['hub'] group = raw_data['group'] project = raw_data['project'] if self._provider.credentials.unique_id().to_tuple() != (hub, group, project): # Try to find the right backend try: original_provider = self._provider._factory.get_provider(hub, group, project) backend = original_provider.get_backend(raw_data['backend']) except (IBMQProviderError, QiskitBackendNotFoundError): backend = IBMQRetiredBackend.from_name( backend_name=raw_data['backend'], provider=None, credentials=Credentials(token="", url="", hub=hub, group=group, project=project), api=None ) else: backend = self._provider.get_backend(raw_data['backend']) params = raw_data.get('params', {}) if isinstance(params, list): if len(params) > 0: params = params[0] else: params = {} if not isinstance(params, str): params = json.dumps(params) decoded = json.loads(params, cls=RuntimeDecoder) return RuntimeJob(backend=backend, api_client=self._api_client, credentials=self._provider.credentials, job_id=raw_data['id'], program_id=raw_data.get('program', {}).get('id', ""), params=decoded, creation_date=raw_data.get('created', None)) def logout(self) -> None: """Clears authorization cache on the server. For better performance, the runtime server caches each user's authorization information. This method is used to force the server to clear its cache. Note: Invoke this method ONLY when your access level to the runtime service has changed - for example, the first time your account is given the authority to upload a program. """ self._api_client.logout()
https://github.com/carstenblank/dc-qiskit-stochastics
carstenblank
# Copyright 2018-2022 Carsten Blank # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import bisect import logging from multiprocessing import Pool from numpy.random import random import sys from typing import List, Union, Optional, Dict, Tuple import numpy as np import qiskit from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.providers.backend import BackendV1 from qiskit.providers.ibmq import IBMQBackend from qiskit.providers.models import QasmBackendConfiguration from qiskit.qobj import Qobj from qiskit.result import Result from qiskit.transpiler import PassManager from qiskit.utils.mitigation import CompleteMeasFitter from . import qobj_mapping from dc_quantum_scheduling import FinishedExperiment LOG = logging.getLogger(__name__) def _bind(qc, parameter, v): return qc.bind_parameters({parameter: v}) def create_qobj(qc_cos: QuantumCircuit, qc_sin: QuantumCircuit, parameter: Parameter, evaluations: np.ndarray, qobj_id: str, pass_manager: PassManager, other_arguments: dict, transpiler_target_backend: Union[BackendV1, IBMQBackend], pre_pass_manager: Optional[PassManager] = None) -> List[Qobj]: LOG.info(f'Transpiling {len(evaluations)} cosine and {len(evaluations)} sine circuits with id={qobj_id}.') # We have the same number of circuits for the cosine and sine experiments other_arguments = {} if other_arguments is None else other_arguments if pre_pass_manager: LOG.info(f'Pre running cicuits...') qc_cos = pre_pass_manager.run(qc_cos) qc_sin = pre_pass_manager.run(qc_sin) LOG.info(f'Main run of cicuits...') qc_transpiled_cos_param = pass_manager.run(qc_cos) qc_transpiled_sin_param = pass_manager.run(qc_sin) with Pool() as pool: circuits_cos = pool.starmap(_bind, [(qc_transpiled_cos_param, parameter, v) for v in evaluations]) circuits_sin = pool.starmap(_bind, [(qc_transpiled_sin_param, parameter, v) for v in evaluations]) # circuits_cos = [qc_transpiled_cos_param.bind_parameters({parameter: v}) for v in evaluations] # circuits_sin = [qc_transpiled_sin_param.bind_parameters({parameter: v}) for v in evaluations] config: QasmBackendConfiguration = transpiler_target_backend.configuration() max_shots = config.max_shots max_experiments = config.max_experiments if hasattr(config, 'max_experiments') else sys.maxsize shots = other_arguments.get('shots', max_shots) other_arguments['shots'] = shots mapping_matrix: np.array = qobj_mapping(shots, max_shots, max_experiments, 2*len(evaluations)) shots_per_experiment = int(shots / mapping_matrix.shape[1]) LOG.debug(mapping_matrix) number_of_qobj: int = np.max(mapping_matrix) + 1 LOG.info(f'For #{len(evaluations)} evaluations each {shots} on the device {transpiler_target_backend.name()} ' f'with max shots {max_shots} and max no. of experiments per Qobj {max_experiments} ' f'there are #{number_of_qobj} of Qobj needed. Assembling the circuits now.') all_circuits = list(zip(circuits_cos, circuits_sin)) qobj_list: List[Qobj] = [] circuit_list: List[List[QuantumCircuit]] = [[] for i in range(number_of_qobj)] for row_no, (ccos, csin) in enumerate(all_circuits): # cosine indices = mapping_matrix[2 * row_no] for i, qobj_id in enumerate(indices): qobj_circuits = circuit_list[qobj_id] qobj_circuits.append(ccos) # sine indices = mapping_matrix[2 * row_no + 1] for i, qobj_id in enumerate(indices): qobj_circuits = circuit_list[qobj_id] qobj_circuits.append(csin) LOG.info(f'Assembled circuits, now building a list of Qobj.') for i, cc in enumerate(circuit_list): qobj_id_i = f'{qobj_id}--{i}' LOG.info(f'Assembling circuits for Qobj #{i} with shots {shots_per_experiment} and id {qobj_id_i}.') qobj = qiskit.compiler.assemble(cc, shots=shots_per_experiment, max_credits=shots_per_experiment * 5, qobj_id=qobj_id_i) qobj_list.append(qobj) return qobj_list def get_row_colums_of_qobj_index(qobj_index: int, mapping: np.array): indices: List[Tuple[int, int]] = [] for row_no, row in enumerate(mapping): for column_no, entry in enumerate(row): if entry == qobj_index: indices.append((row_no, column_no)) if entry > qobj_index: break return indices def _get_expval_proposition_one(counts: Dict[str, int]): return (counts.get('0', 0) - counts.get('1', 0)) / (counts.get('0', 0) + counts.get('1', 0)) def extract_evaluations(finished_experiment: FinishedExperiment, meas_fitter: Optional[CompleteMeasFitter] = None) -> np.ndarray: backend: BackendV1 = finished_experiment.transpiler_backend config: QasmBackendConfiguration = backend.configuration() max_shots = config.max_shots max_experiments = config.max_experiments if hasattr(config, 'max_experiments') else sys.maxsize shots = finished_experiment.parameters.get('shots', max_shots) mapping_matrix = qobj_mapping(shots, max_shots, max_experiments, 2*len(finished_experiment.arguments)) number_of_qobj: int = np.max(mapping_matrix) + 1 counts_cos: List[Dict[str, int]] = [{'0': 0, '1': 0} for a in finished_experiment.arguments] counts_sin: List[Dict[str, int]] = [{'0': 0, '1': 0} for a in finished_experiment.arguments] for qobj_index in range(number_of_qobj): indices = get_row_colums_of_qobj_index(qobj_index, mapping_matrix) result: Result = finished_experiment.to_result(qobj_index) measured_qubits = [e.instructions[-1].qubits for e in finished_experiment.qobj_list[qobj_index].experiments] def mitigate_counts(counts: Dict[str, int], q_no: List[int]): if meas_fitter is not None: # build a fitter from the subset meas_fitter_sub = meas_fitter.subset_fitter(qubit_sublist=q_no) # Get the filter object meas_filter = meas_fitter_sub.filter # Results with mitigation mitigated_counts = meas_filter.apply(counts, method='pseudo_inverse') return mitigated_counts else: return counts count: Dict[str, int] for count, (row_no, _), measured_q_no in zip(result.get_counts(), indices, measured_qubits): count = mitigate_counts(count, measured_q_no) if row_no % 2 == 1: argument_no = int((row_no - 1) / 2) counts = counts_sin else: argument_no = int(row_no / 2) counts = counts_cos old_counts = counts[argument_no] counts[argument_no]['0'] = old_counts.get('0', 0) + count.get('0', 0) counts[argument_no]['1'] = old_counts.get('1', 0) + count.get('1', 0) cosine_expvals = [_get_expval_proposition_one(c) for c in counts_cos] sine_expvals = [_get_expval_proposition_one(c) for c in counts_sin] return np.asarray([cos + 1.0j * sin for cos, sin in zip(cosine_expvals, sine_expvals)]) def cdf(weights): """ From https://stackoverflow.com/questions/4113307/pythonic-way-to-select-list-elements-with-different-probability :param weights: :return: """ total = sum(weights) result = [] cumsum = 0 for w in weights: cumsum += w result.append(cumsum / total) return result def choice(population, weights, size=None): """ From https://stackoverflow.com/questions/4113307/pythonic-way-to-select-list-elements-with-different-probability :param population: :param weights: :return: Args: size: """ assert len(population) == len(weights) cdf_vals = cdf(weights) x = random(size=size) if not size: x = [x] for e in x: idx = bisect.bisect(cdf_vals, e) yield population[idx]
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.extensions import * from qiskit.quantum_info import Statevector,Operator from math import pi from qiskit.visualization import * qc = QuantumCircuit(1) qc.u(pi/2,pi/2,pi/2,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for U gate Ugate_unitary=result.get_unitary(qc, decimals=3) print(Ugate_unitary) Ugate_unitary.data array_to_latex(Ugate_unitary) array_to_latex(Operator(UGate(pi/2,pi/2,pi/2)).data) qc = QuantumCircuit(1) qc.u(pi/2,0,pi,0) qc.draw(output="mpl") job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for U gate Ugate_unitary=result.get_unitary(qc, decimals=3) print(Ugate_unitary) array_to_latex(Ugate_unitary) array_to_latex(Operator(UGate(pi/2,0,pi)).data) array_to_latex(Operator(HGate()).data) qc = QuantumCircuit(1) qc.u(0,0,pi/2,0) qc.draw(output="mpl") job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for U gate Ugate_unitary=result.get_unitary(qc, decimals=3) print(Ugate_unitary) array_to_latex(Ugate_unitary) array_to_latex(Operator(UGate(0,0,pi/2)).data) array_to_latex(Operator(PhaseGate(pi/2)).data) array_to_latex(Operator(UGate(pi/2,0,0)).data) array_to_latex(Operator(RYGate(pi/2)).data) array_to_latex(Operator(UGate(0,pi/2,-pi/2)).data) array_to_latex(Operator(RXGate(0)).data)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit import Parameter from qiskit import QuantumCircuit theta = Parameter('$\\theta$') chsh_circuits_no_meas = QuantumCircuit(2) chsh_circuits_no_meas.h(0) chsh_circuits_no_meas.cx(0, 1) chsh_circuits_no_meas.ry(theta, 0) chsh_circuits_no_meas.draw('mpl') import numpy as np number_of_phases = 21 phases = np.linspace(0, 2*np.pi, number_of_phases) # Phases need to be expressed as list of lists in order to work individual_phases = [[ph] for ph in phases] from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] # Simulator with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) est_result = job.result() chsh_est_sim.append(est_result) # <CHSH1> = <AB> - <Ab> + <aB> + <ab> chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values # <CHSH2> = <AB> + <Ab> - <aB> + <ab> chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values import matplotlib.pyplot as plt import matplotlib.ticker as tck fig, ax = plt.subplots(figsize=(10, 6)) # results from a simulator ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation') ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation') # classical bound +-2 ax.axhline(y=2, color='r', linestyle='--') ax.axhline(y=-2, color='r', linestyle='--') # quantum bound, +-2√2 ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.') ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.') # set x tick labels to the unit of pi ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$')) ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5)) # set title, labels, and legend plt.title('Violation of CHSH Inequality') plt.xlabel('Theta') plt.ylabel('CHSH witness') plt.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/we-taper/qiskit-pyzx
we-taper
from functools import singledispatch from itertools import chain from math import pi from typing import Dict import pyzx import pyzx.circuit.gates as zx_g import qiskit.extensions.standard as qk_g from qiskit.circuit import Qubit from qiskit.dagcircuit import DAGCircuit @singledispatch def get_op_qargs_from_pyzx( gate: pyzx.gates.Gate, pyreg_to_qubit: Dict[int, Qubit]): """Append the right qiskit op and qargs from the gate. The return is a list of such op and qargs. """ raise NotImplementedError( f"Conversion from {type(gate)} to qiskit has not been implemented.") @get_op_qargs_from_pyzx.register(zx_g.ZPhase) def _f(gate: zx_g.ZPhase, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.RZGate(float(gate.phase) * pi), [pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.Z) def _f(gate: zx_g.Z, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.ZGate(), [pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.S) def _f(gate: zx_g.ZPhase, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.SGate(), [pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.T) def _f(gate: zx_g.T, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.TGate(), [pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.XPhase) def _f(gate: zx_g.XPhase, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.RXGate(float(gate.phase) * pi), [pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.NOT) def _f(gate: zx_g.NOT, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.XGate(), [pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.HAD) def _f(gate: zx_g.HAD, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.HGate(), [pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.CNOT) def _f(gate: zx_g.CNOT, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.CnotGate(), [pyreg_to_qubit[gate.control], pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.CZ) def _f(gate: zx_g.CZ, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.CzGate(), [pyreg_to_qubit[gate.control], pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.CX) def _f(gate: zx_g.CZ, pyreg_to_qubit: Dict[int, Qubit]): raise NotImplementedError("CX in PyZX is not the CNOT we know.") @get_op_qargs_from_pyzx.register(zx_g.SWAP) def _f(gate: zx_g.SWAP, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.SwapGate(), [pyreg_to_qubit[gate.control], pyreg_to_qubit[gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.Tofolli) def _f(gate: zx_g.Tofolli, pyreg_to_qubit: Dict[int, Qubit]): return [( qk_g.ToffoliGate(), [pyreg_to_qubit[gate.ctrl1], pyreg_to_qubit[gate.ctrl2], [gate.target]] )] @get_op_qargs_from_pyzx.register(zx_g.CCZ) def _f(gate: zx_g.CCZ, pyreg_to_qubit: Dict[int, Qubit]): basic_gates = gate.to_basic_gates() basic_gates = [ get_op_qargs_from_pyzx(bg, pyreg_to_qubit) for bg in basic_gates ] return list(chain.from_iterable(basic_gates)) def add_normal_gate( gate: pyzx.gates.Gate, pyreg_to_qubit: Dict[int, Qubit], dagcircuit: DAGCircuit): op_qargs_list = get_op_qargs_from_pyzx(gate, pyreg_to_qubit) for op, qarg in op_qargs_list: dagcircuit.apply_operation_back( op=op, qargs=qarg, cargs=[], condition=None )
https://github.com/bibscore/qiskit_kindergarten
bibscore
import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile from qiskit.quantum_info import Statevector from qiskit.providers.aer import QasmSimulator from qiskit.visualization import plot_histogram %matplotlib inline import matplotlib.pyplot as plt from itertools import chain simulator = QasmSimulator() qreg = QuantumRegister(1, 'q') creg = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qreg, creg) circuit.reset(qreg[0]) circuit.h(qreg[0]) circuit.measure(qreg[0], creg[0]) circuit.draw(output='mpl') y0 = [] y1 = [] cont_zero = 0 cont_one = 0 for i in range(0, 100): circuit.measure(qreg[0], creg[0]) compiled_circuit = transpile(circuit, simulator) job = simulator.run(compiled_circuit, shots=1000) result = job.result() if(i == 0): counts0 = result.get_counts(compiled_circuit) counts = result.get_counts(compiled_circuit) y0.append(counts['0']/1000) y1.append(counts['1']/1000) cont_zero = cont_zero + counts['0']/1000.0 cont_one = cont_one + counts['1']/1000.0 print("\nTotal count for 0 and 1 are: ", counts) print("\naverage probability value of obtaining a 0 qubit state is: ", cont_zero/100.0) print("average probability value of obtaining a 1 qubit state is: ", cont_one/100.0) values = [counts0, counts] legend = ["first execution", "second execution"] color =["#625BF5", "#39D4D0"] plot_histogram(values, legend=legend, color=color, title="Hadamard gate measurement probability") fig, ax = plt.subplots(figsize=(10, 7)) x = np.arange(0, len(y0)) ax.plot(x, y0, "--*", color="#625BF5", label="collapsing into |0>") ax.plot(x, y1, "--*", color="#64CCC3", label="collapsing into |1>") plt.title("Hadamard gate measurement per iteration") plt.xlabel("Iterations") plt.ylabel("H gate measurement probability") plt.legend() plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
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/erinaldi/bmn2-qiskit
erinaldi
import numpy as np from scipy.sparse import diags from scipy.sparse import identity from scipy.sparse import kron L = 2 # cutoff for Fock space -> can not go larger than 2 in qiskit without having problems for minimal BMN a_b = diags(np.sqrt(np.linspace(1,L-1,L-1)),offsets=1) a_b.todense() i_b = identity(L) i_b.todense() a_f = diags(np.sqrt(np.linspace(1,1,1)),offsets=1) a_f.todense() sz = diags([1.0,-1.0]) sz.todense() i_f = identity(2) i_f.todense() N_bos = 6 # number of boson sites -> fixed for mini-BMN 2 product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times a_b_list = [] # this will contain a1...a6 for i in np.arange(0,N_bos): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[i] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append(operator_list[0]) # start taking tensor products from first element for a in operator_list[1:]: a_b_list[i] = kron(a_b_list[i],a) # do the outer product between each operator_list element len(a_b_list) N_f = 3 # number of fermionic sites -> fixed for the supersymmetric model mini-BMN with 2 matrices product_list = [i_f] * N_f # only the identity for fermions repeated N_f times a_f_list = [] # this will contain f1...f3 for i in np.arange(0,N_f): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[i] = a_f # the i^th element is now the annihilation operator for a single fermion for j in np.arange(0,i): # the 0:(i-1) elements are replaced by sigma_Z operator_list[j] = sz a_f_list.append(operator_list[0]) # start taking tensor products from the first operator for a in operator_list[1:]: a_f_list[i] = kron(a_f_list[i],a) # do the outer product i_b_tot = identity(L**N_bos) i_f_tot = identity(2**N_f) op_list = [] for a in a_b_list: op_list.append(kron(a,i_f_tot)) for a in a_f_list: op_list.append(kron(i_b_tot,a)) len(op_list) op_list[0] x_list = [] # only use the bosonic operators bosons = op_list[:N_bos] for op in bosons: x_list.append(1/np.sqrt(2)*(op.conjugate().transpose() + op)) # save the fermions operators for convenience in a new list fermions = op_list[-N_f:] # Create the simple quartic Hamiltonian. H_k = 0 for a in op_list[:N_bos]: H_k = H_k + a.conjugate().transpose() * a for a in op_list[-N_f:]: H_k = H_k + (3.0 / 2) * a.conjugate().transpose() * a # vacuum energy H_k = H_k + 0.25 * (2 * N_bos - 3 * N_f - 3) from scipy.sparse.linalg import eigsh eigv = eigsh(H_k,k=10,which='SA',return_eigenvectors=False,tol=0) print(f"Free Hamiltonian eigenvalues: {eigv[::-1]}") V_b = ( x_list[2] * x_list[2] * x_list[3] * x_list[3] + x_list[2] * x_list[2] * x_list[4] * x_list[4] + x_list[1] * x_list[1] * x_list[3] * x_list[3] + x_list[1] * x_list[1] * x_list[5] * x_list[5] + x_list[0] * x_list[0] * x_list[4] * x_list[4] + x_list[0] * x_list[0] * x_list[5] * x_list[5] - 2 * x_list[0] * x_list[2] * x_list[3] * x_list[5] - 2 * x_list[0] * x_list[1] * x_list[3] * x_list[4] - 2 * x_list[1] * x_list[2] * x_list[4] * x_list[5] ) V_bf = (2j / np.sqrt(2)) * ( (x_list[0] - 1j * x_list[3]) * fermions[1].conjugate().transpose() * fermions[2].conjugate().transpose() + (x_list[1] - 1j * x_list[4]) * fermions[2].conjugate().transpose() * fermions[0].conjugate().transpose() + (x_list[2] - 1j * x_list[5]) * fermions[0].conjugate().transpose() * fermions[1].conjugate().transpose() - (x_list[0] + 1j * x_list[3]) * fermions[2] * fermions[1] - (x_list[1] + 1j * x_list[4]) * fermions[0] * fermions[2] - (x_list[2] + 1j * x_list[5]) * fermions[1] * fermions[0] ) # t'Hooft coupling g2N = 0.2 # Number of colors N = 2 # full hamiltonian H = H_k + g2N/N*V_b + np.sqrt(g2N/N)*V_bf H.shape eigv = eigsh(H,k=10,which='SM',return_eigenvectors=False,tol=0) print(f"Full Hamiltonian with lambda={g2N} : {eigv[::-1]}") import warnings import time from qiskit.opflow import MatrixOp start_time = time.time() warnings.filterwarnings("ignore") qubitOp = MatrixOp(primitive=H) print("Size of Hamiltonian:", np.shape(H)) end_time = time.time() runtime = end_time-start_time print('Program runtime: ',runtime) from qiskit.circuit.library import EfficientSU2 var_form = EfficientSU2(qubitOp.num_qubits, su2_gates=['ry','rz'], entanglement="full", reps=1) var_form.draw(output='mpl') from qiskit.algorithms import NumPyEigensolver mes = NumPyEigensolver(k=4) # k is the number of eigenvalues to compute result = mes.compute_eigenvalues(qubitOp) print(result.eigenvalues) print("Exact Result of qubit hamiltonian:", np.real(result.eigenvalues)) print("Exact Result of discrete hamiltonian:", np.real(eigv[::-1][0:4])) from qiskit import Aer # change this to Aer for C++ compiled code and the option to run on the GPU from qiskit.algorithms import VQE # start a quantum instance # fix the random seed of the simulator to make values reproducible from qiskit.utils import algorithm_globals, QuantumInstance seed = 50 algorithm_globals.random_seed = seed # with GPU #backend = Aer.get_backend("statevector_simulator", method="statevector_gpu") # with parallel computation restricted to 2 OpenMP threads (0: maximum) backend = Aer.get_backend("statevector_simulator", max_parallel_threads=6, max_parallel_experiments=0) q_instance = QuantumInstance(backend, seed_transpiler=seed, seed_simulator=seed) from qiskit.algorithms.optimizers import SLSQP, COBYLA, L_BFGS_B, NELDER_MEAD, SPSA start_time = time.time() # choose one classical optimizer # optimizer = L_BFGS_B(maxiter=5000) # optimizer = SPSA(maxiter=5000) optimizer = COBYLA(maxiter=5000) counts = [] values = [] # callback functions to store the counts from each iteration of the VQE def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # initital points #random_init = np.random.random(var_form.num_parameters) #fixed_init = result.optimal_point # Setup the VQE algorithm #vqe = VQE(ansatz=var_form, optimizer=optimizer, initial_point=random_init, quantum_instance=q_instance, callback=store_intermediate_result) #vqe = VQE(ansatz=var_form, optimizer=optimizer, initial_point=fixed_init, quantum_instance=q_instance, callback=store_intermediate_result) vqe = VQE(ansatz=var_form, optimizer=optimizer, quantum_instance=q_instance, callback=store_intermediate_result) # run the VQE with out Hamiltonian operator # since the VQE is a ground state solver, the syntax is the same as before ;-) result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print("VQE Result:", vqe_result) end_time = time.time() runtime = end_time-start_time print('Program runtime:',runtime, "s") # Plot convergence plot from matplotlib import pyplot as plt plt.figure(figsize=(12,10)) plt.plot(counts, values, label="SLSQP") plt.xlabel('Eval count') plt.ylabel('Energy') plt.title('Energy convergence') plt.legend(loc='upper right') plt.show(); # start a quantum instance # fix the random seed of the simulator to make values reproducible from qiskit.utils import algorithm_globals, QuantumInstance seed = 50 algorithm_globals.random_seed = seed # with GPU # backend = Aer.get_backend('qasm_simulator', method="statevector_gpu") # with parallel computation restricted to 1 OpenMP threads (0: maximum) backend = Aer.get_backend('qasm_simulator', max_parallel_threads=1, max_parallel_experiments=0) q_instance = QuantumInstance(backend, seed_transpiler=seed, seed_simulator=seed, shots=1024) from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua import QuantumInstance warnings.filterwarnings("ignore") optimizer = SPSA(maxiter=6000) counts = [] values = [] # callback functions to store the counts from each iteration of the VQE def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # initital points #random_init = np.random.random(var_form.num_parameters) #fixed_init = result.optimal_point # Setup the VQE algorithm #vqe = VQE(ansatz=var_form, optimizer=optimizer, initial_point=random_init, quantum_instance=q_instance, callback=store_intermediate_result) #vqe = VQE(ansatz=var_form, optimizer=optimizer, initial_point=fixed_init, quantum_instance=q_instance, callback=store_intermediate_result) vqe = VQE(ansatz=var_form, optimizer=optimizer, quantum_instance=q_instance, callback=store_intermediate_result) # run the VQE with out Hamiltonian operator # since the VQE is a ground state solver, the syntax is the same as before ;-) result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print("VQE Result:", vqe_result) # Plot convergence plot plt.figure(figsize=(12,10)) plt.plot(counts, values, label="SPSA") plt.xlabel('Eval count') plt.ylabel('Energy') plt.title('Energy convergence') plt.legend(loc='upper right') import qiskit.tools.jupyter %qiskit_version_table
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# here is a list holding all even numbers between 10 and 20 L = [10, 12, 14, 16, 18, 20] # let's print the list print(L) # let's print each element by using its index but in reverse order print(L[5],L[4],L[3],L[2],L[1],L[0]) # let's print the length (size) of list print(len(L)) # let's print each element and its index in the list # we use a for-loop and the number of iteration is determined by the length of the list # everthing is automatic :-) L = [10, 12, 14, 16, 18, 20] for i in range(len(L)): print(L[i],"is the element in our list with the index",i) # let's replace each number in the list with its double value L = [10, 12, 14, 16, 18, 20] # let's print the list before doubling print("the list before doubling",L) for i in range(len(L)): current_element=L[i] # get the value of the i-th element L[i] = 2 * current_element # update the value of the i-th element # let's shorten the replacing code #L[i] = 2 * L[i] # or #L[i] *= 2 # let's print the list after doubling print("the list after doubling",L) # after each exceution of this cell, the latest values will be doubled # so the values in the list will be exponentially increased # let's define two lists L1 = [1,2,3,4] L2 = [-5,-6,-7,-8] # two lists can be concatenated # the results is a new list print("the concatenation of L1 and L2 is",L1+L2) # the order of terms is important print("the concatenation of L2 and L1 is",L2+L1) # this is a different list than L1+L2 # we can add a new element to a list, which increases its length/size by 1 L = [10, 12, 14, 16, 18, 20] print(L,"the current length is",len(L)) # we add two values by showing two different methods # L.append(value) directly adds the value as a new element to the list L.append(-4) # we can also use concatenation operator + L = L + [-8] # here [-8] is a list with single element print(L,"the new length is",len(L)) # a list can be multiplied with an integer L = [1,2] # we can consider the multiplication of L by an integer # as a repeated summation (concatenation) of L by itself # L * 1 is the list itself # L * 2 is L + L (concatenation of L with itself) # L * 3 is L + L + L (concatenation of L with itself twice) # L * m is L + ... + L (concatenation of L with itself m-1 times) # L * 0 is the empty list # L * i is the same as i * L # let's print the different cases for i in range(6): print(i,"* L is",i*L) # this can be useful when initializing a list with the same value(s) # let's create a list of prime numbers less than 100 # here is a function determining whether a given number is prime or not def prime(number): if number < 2: return False if number == 2: return True if number % 2 == 0: return False for i in range(3,number,2): if number % i == 0: return False return True # end of function # let's start with an empty list L=[] # what can the length of this list be? print("my initial length is",len(L)) for i in range(2,100): if prime(i): L.append(i) # alternative methods: #L = L + [i] #L += [i] # print the final list print(L) print("my final length is",len(L)) # let's define the list with S(0) L = [0] # let's iteratively define n and S # initial values n = 0 S = 0 # the number of iteration N = 20 while n <= N: # we iterate all values from 1 to 20 n = n + 1 S = S + n L.append(S) # print the final list print(L) # # your solution is here # F = [1,1] # the following list stores certain information about Asja # name, surname, age, profession, height, weight, partner(s) if any, kid(s) if any, date ASJA = ['Asja','Sarkane',34,'musician',180,65.5,[],['Eleni','Fyodor'],"October 24, 2018"] print(ASJA) # Remark that an element of a list can be another list as well. # # your solution is here # # let's define a dictionary pairing a person with her/his age ages = { 'Asja':32, 'Balvis':28, 'Fyodor':43 } # let print all keys for person in ages: print(person) # let's print the values for person in ages: print(ages[person])
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
# parameterized execution algorithm example from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit import ParameterVector from qiskit.visualization import plot_histogram # Set to true for more text output detailing execution steps VERBOSE = True # set target backend and number of shots BACKEND = Aer.get_backend("qasm_simulator") NUM_SHOTS = 1000 # Fake function to update parameters based on the measurement results def update_params_from_measurement_results(thetas_array, result): """Update theta parameters with max count value divided by NUM_SHOTS.""" update = 0.1 * max(result.values()) / NUM_SHOTS return list(map(lambda theta: round(theta+update, 3), thetas_array)) # create initial set of 3 'theta' parameters thetas = [1.0, 2.0, 3.0] len_thetas = len(thetas) params = ParameterVector("θ", len_thetas) # create quantum circuit with these parameters as arguments to the gates qc = QuantumCircuit(len_thetas) for qidx, param in enumerate(params): qc.rx(param, qidx) qc.measure_all() if VERBOSE: print(qc.draw(output='text', fold=-1)) # execute this circuit ten times (and solve all the world's energy problems!) energy_value = 0 for rep in range(0, 10): # first time, do transpile to backend if rep == 0: if VERBOSE: print("\nTranspiling circuit") qc_trans = transpile(qc, BACKEND) # bind parameters to the saved and already transpiled circuit if VERBOSE: print(f"\nBinding {thetas = } to qc_exec") qc_exec = qc_trans.bind_parameters({params: thetas}) # execute this transpiled and bound circuit on the backend job = BACKEND.run(qc_exec, shots=NUM_SHOTS) # get results from completed joband counts = job.result().get_counts() # Plot a histogram plot_histogram(counts) if VERBOSE: print(f'{counts = }\nwith {thetas = }') # compute new params from the original ones and the measurement results obtained # NOTE: this is highly app-specific as in VQE/QAOA cost function calcs # Kludgy mimic: Do not update thetas on last iteration as circuit will not be ran again if rep != 9: thetas = update_params_from_measurement_results(thetas, counts) # Example of energy_value update function, actual calculation is problem specific energy_value += min(counts.values()) print(f'\n----------------------') print(f'Final {energy_value = }') print(f'Final {counts = }\nwith {thetas = }') # Uncomment below to visualize results from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt plot_histogram(counts) plt.show()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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 library of n-local circuits.""" import unittest from test import combine import numpy as np from ddt import ddt, data, unpack from qiskit.test.base import QiskitTestCase from qiskit import transpile from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector, ParameterExpression from qiskit.circuit.library import ( NLocal, TwoLocal, RealAmplitudes, ExcitationPreserving, XGate, CRXGate, CCXGate, SwapGate, RXGate, RYGate, EfficientSU2, RZGate, RXXGate, RYYGate, CXGate, ) from qiskit.circuit.random.utils import random_circuit from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.quantum_info import Operator @ddt class TestNLocal(QiskitTestCase): """Test the n-local circuit class.""" def test_if_reps_is_negative(self): """Test to check if error is raised for negative value of reps""" with self.assertRaises(ValueError): _ = NLocal(reps=-1) def test_if_reps_is_str(self): """Test to check if proper error is raised for str value of reps""" with self.assertRaises(TypeError): _ = NLocal(reps="3") def test_if_reps_is_float(self): """Test to check if proper error is raised for float value of reps""" with self.assertRaises(TypeError): _ = NLocal(reps=5.6) def test_if_reps_is_npint32(self): """Equality test for reps with int value and np.int32 value""" self.assertEqual(NLocal(reps=3), NLocal(reps=np.int32(3))) def test_if_reps_is_npint64(self): """Equality test for reps with int value and np.int64 value""" self.assertEqual(NLocal(reps=3), NLocal(reps=np.int64(3))) def test_reps_setter_when_negative(self): """Test to check if setter raises error for reps < 0""" nlocal = NLocal(reps=1) with self.assertRaises(ValueError): nlocal.reps = -1 def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True): """An equality test specialized to circuits.""" if transpiled: basis_gates = ["id", "u1", "u3", "cx"] qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0) qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0) qc1, qc2 = qc1_transpiled, qc2_transpiled if visual: self.assertEqual(qc1.draw(), qc2.draw()) else: self.assertEqual(qc1, qc2) def test_empty_nlocal(self): """Test the creation of an empty NLocal.""" nlocal = NLocal() self.assertEqual(nlocal.num_qubits, 0) self.assertEqual(nlocal.num_parameters_settable, 0) self.assertEqual(nlocal.reps, 1) self.assertEqual(nlocal, QuantumCircuit()) for attribute in [nlocal.rotation_blocks, nlocal.entanglement_blocks]: self.assertEqual(len(attribute), 0) @data( (XGate(), [[0], [2], [1]]), (XGate(), [[0]]), (CRXGate(-0.2), [[2, 0], [1, 3]]), ) @unpack def test_add_layer_to_empty_nlocal(self, block, entangler_map): """Test appending gates to an empty nlocal.""" nlocal = NLocal() nlocal.add_layer(block, entangler_map) max_num_qubits = max(max(indices) for indices in entangler_map) reference = QuantumCircuit(max_num_qubits + 1) for indices in entangler_map: reference.append(block, indices) self.assertCircuitEqual(nlocal, reference) @data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10]) def test_append_circuit(self, num_qubits): """Test appending circuits to an nlocal works normally.""" # fixed depth of 3 gates per circuit depth = 3 # keep track of a reference circuit reference = QuantumCircuit(max(num_qubits)) # construct the NLocal from the first circuit first_circuit = random_circuit(num_qubits[0], depth, seed=4200) # TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1) reference.append(first_circuit, list(range(num_qubits[0]))) # append the rest for num in num_qubits[1:]: circuit = random_circuit(num, depth, seed=4200) nlocal.append(circuit, list(range(num))) reference.append(circuit, list(range(num))) self.assertCircuitEqual(nlocal, reference) @data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10]) def test_add_nlocal(self, num_qubits): """Test adding an nlocal to an nlocal (using add_layer).""" # fixed depth of 3 gates per circuit depth = 3 # keep track of a reference circuit reference = QuantumCircuit(max(num_qubits)) # construct the NLocal from the first circuit first_circuit = random_circuit(num_qubits[0], depth, seed=4220) # TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1) nlocal2 = nlocal.copy() _ = nlocal2.data reference.append(first_circuit, list(range(num_qubits[0]))) # append the rest for num in num_qubits[1:]: circuit = random_circuit(num, depth, seed=4220) layer = NLocal(num, entanglement_blocks=circuit, reps=1) nlocal.add_layer(layer) nlocal2.add_layer(layer) reference.append(circuit, list(range(num))) self.assertCircuitEqual(nlocal, reference) self.assertCircuitEqual(nlocal2, reference) @unittest.skip("Feature missing") def test_iadd_overload(self): """Test the overloaded + operator.""" num_qubits, depth = 2, 2 # construct two circuits for adding first_circuit = random_circuit(num_qubits, depth, seed=4242) circuit = random_circuit(num_qubits, depth, seed=4242) # get a reference reference = first_circuit + circuit # convert the object to be appended to different types others = [circuit, circuit.to_instruction(), circuit.to_gate(), NLocal(circuit)] # try adding each type for other in others: nlocal = NLocal(num_qubits, entanglement_blocks=first_circuit, reps=1) nlocal += other with self.subTest(msg=f"type: {type(other)}"): self.assertCircuitEqual(nlocal, reference) def test_parameter_getter_from_automatic_repetition(self): """Test getting and setting of the nlocal parameters.""" circuit = QuantumCircuit(2) circuit.ry(Parameter("a"), 0) circuit.crx(Parameter("b"), 0, 1) # repeat circuit and check that parameters are duplicated reps = 3 nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps) self.assertTrue(nlocal.num_parameters, 6) self.assertTrue(len(nlocal.parameters), 6) @data(list(range(6)), ParameterVector("θ", length=6), [0, 1, Parameter("theta"), 3, 4, 5]) def test_parameter_setter_from_automatic_repetition(self, params): """Test getting and setting of the nlocal parameters.""" circuit = QuantumCircuit(2) circuit.ry(Parameter("a"), 0) circuit.crx(Parameter("b"), 0, 1) # repeat circuit and check that parameters are duplicated reps = 3 nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps) nlocal.assign_parameters(params, inplace=True) param_set = {p for p in params if isinstance(p, ParameterExpression)} with self.subTest(msg="Test the parameters of the non-transpiled circuit"): # check the parameters of the final circuit self.assertEqual(nlocal.parameters, param_set) with self.subTest(msg="Test the parameters of the transpiled circuit"): basis_gates = ["id", "u1", "u2", "u3", "cx"] transpiled_circuit = transpile(nlocal, basis_gates=basis_gates) self.assertEqual(transpiled_circuit.parameters, param_set) @data(list(range(6)), ParameterVector("θ", length=6), [0, 1, Parameter("theta"), 3, 4, 5]) def test_parameters_setter(self, params): """Test setting the parameters via list.""" # construct circuit with some parameters initial_params = ParameterVector("p", length=6) circuit = QuantumCircuit(1) for i, initial_param in enumerate(initial_params): circuit.ry(i * initial_param, 0) # create an NLocal from the circuit and set the new parameters nlocal = NLocal(1, entanglement_blocks=circuit, reps=1) nlocal.assign_parameters(params, inplace=True) param_set = {p for p in params if isinstance(p, ParameterExpression)} with self.subTest(msg="Test the parameters of the non-transpiled circuit"): # check the parameters of the final circuit self.assertEqual(nlocal.parameters, param_set) with self.subTest(msg="Test the parameters of the transpiled circuit"): basis_gates = ["id", "u1", "u2", "u3", "cx"] transpiled_circuit = transpile(nlocal, basis_gates=basis_gates) self.assertEqual(transpiled_circuit.parameters, param_set) def test_repetetive_parameter_setting(self): """Test alternate setting of parameters and circuit construction.""" x = Parameter("x") circuit = QuantumCircuit(1) circuit.rx(x, 0) nlocal = NLocal(1, entanglement_blocks=circuit, reps=3, insert_barriers=True) with self.subTest(msg="immediately after initialization"): self.assertEqual(len(nlocal.parameters), 3) with self.subTest(msg="after circuit construction"): self.assertEqual(len(nlocal.parameters), 3) q = Parameter("q") nlocal.assign_parameters([x, q, q], inplace=True) with self.subTest(msg="setting parameter to Parameter objects"): self.assertEqual(nlocal.parameters, set({x, q})) nlocal.assign_parameters([0, -1], inplace=True) with self.subTest(msg="setting parameter to numbers"): self.assertEqual(nlocal.parameters, set()) def test_skip_unentangled_qubits(self): """Test skipping the unentangled qubits.""" num_qubits = 6 entanglement_1 = [[0, 1, 3], [1, 3, 5], [0, 1, 5]] skipped_1 = [2, 4] entanglement_2 = [entanglement_1, [[0, 1, 2], [2, 3, 5]]] skipped_2 = [4] for entanglement, skipped in zip([entanglement_1, entanglement_2], [skipped_1, skipped_2]): with self.subTest(entanglement=entanglement, skipped=skipped): nlocal = NLocal( num_qubits, rotation_blocks=XGate(), entanglement_blocks=CCXGate(), entanglement=entanglement, reps=3, skip_unentangled_qubits=True, ) decomposed = nlocal.decompose() skipped_set = {decomposed.qubits[i] for i in skipped} dag = circuit_to_dag(decomposed) idle = set(dag.idle_wires()) self.assertEqual(skipped_set, idle) @data( "linear", "full", "circular", "sca", "reverse_linear", ["linear", "full"], ["reverse_linear", "full"], ["circular", "linear", "sca"], ) def test_entanglement_by_str(self, entanglement): """Test setting the entanglement of the layers by str.""" reps = 3 nlocal = NLocal( 5, rotation_blocks=XGate(), entanglement_blocks=CCXGate(), entanglement=entanglement, reps=reps, ) def get_expected_entangler_map(rep_num, mode): if mode == "linear": return [(0, 1, 2), (1, 2, 3), (2, 3, 4)] elif mode == "reverse_linear": return [(2, 3, 4), (1, 2, 3), (0, 1, 2)] elif mode == "full": return [ (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), ] else: circular = [(3, 4, 0), (0, 1, 2), (1, 2, 3), (2, 3, 4)] if mode == "circular": return circular sca = circular[-rep_num:] + circular[:-rep_num] if rep_num % 2 == 1: sca = [tuple(reversed(indices)) for indices in sca] return sca for rep_num in range(reps): entangler_map = nlocal.get_entangler_map(rep_num, 0, 3) if isinstance(entanglement, list): mode = entanglement[rep_num % len(entanglement)] else: mode = entanglement expected = get_expected_entangler_map(rep_num, mode) with self.subTest(rep_num=rep_num): # using a set here since the order does not matter self.assertEqual(entangler_map, expected) def test_pairwise_entanglement(self): """Test pairwise entanglement.""" nlocal = NLocal( 5, rotation_blocks=XGate(), entanglement_blocks=CXGate(), entanglement="pairwise", reps=1, ) entangler_map = nlocal.get_entangler_map(0, 0, 2) pairwise = [(0, 1), (2, 3), (1, 2), (3, 4)] self.assertEqual(pairwise, entangler_map) def test_pairwise_entanglement_raises(self): """Test choosing pairwise entanglement raises an error for too large blocks.""" nlocal = NLocal(3, XGate(), CCXGate(), entanglement="pairwise", reps=1) # pairwise entanglement is only defined if the entangling gate has 2 qubits with self.assertRaises(ValueError): print(nlocal.draw()) def test_entanglement_by_list(self): """Test setting the entanglement by list. This is the circuit we test (times 2, with final X layer) ┌───┐ ┌───┐┌───┐ ┌───┐ q_0: |0>┤ X ├──■────■───X────┤ X ├┤ X ├──■───X─────── .. ┤ X ├ ├───┤ │ │ │ ├───┤└─┬─┘ │ │ ├───┤ q_1: |0>┤ X ├──■────┼───┼──X─┤ X ├──■────┼───X──X──── .. ┤ X ├ ├───┤┌─┴─┐ │ │ │ ├───┤ │ │ │ x2 ├───┤ q_2: |0>┤ X ├┤ X ├──■───┼──X─┤ X ├──■────■──────X──X─ .. ┤ X ├ ├───┤└───┘┌─┴─┐ │ ├───┤ ┌─┴─┐ │ ├───┤ q_3: |0>┤ X ├─────┤ X ├─X────┤ X ├─────┤ X ├───────X─ .. ┤ X ├ └───┘ └───┘ └───┘ └───┘ └───┘ """ circuit = QuantumCircuit(4) for _ in range(2): circuit.x([0, 1, 2, 3]) circuit.barrier() circuit.ccx(0, 1, 2) circuit.ccx(0, 2, 3) circuit.swap(0, 3) circuit.swap(1, 2) circuit.barrier() circuit.x([0, 1, 2, 3]) circuit.barrier() circuit.ccx(2, 1, 0) circuit.ccx(0, 2, 3) circuit.swap(0, 1) circuit.swap(1, 2) circuit.swap(2, 3) circuit.barrier() circuit.x([0, 1, 2, 3]) layer_1_ccx = [(0, 1, 2), (0, 2, 3)] layer_1_swap = [(0, 3), (1, 2)] layer_1 = [layer_1_ccx, layer_1_swap] layer_2_ccx = [(2, 1, 0), (0, 2, 3)] layer_2_swap = [(0, 1), (1, 2), (2, 3)] layer_2 = [layer_2_ccx, layer_2_swap] entanglement = [layer_1, layer_2] nlocal = NLocal( 4, rotation_blocks=XGate(), entanglement_blocks=[CCXGate(), SwapGate()], reps=4, entanglement=entanglement, insert_barriers=True, ) self.assertCircuitEqual(nlocal, circuit) def test_initial_state_as_circuit_object(self): """Test setting `initial_state` to `QuantumCircuit` object""" # ┌───┐ ┌───┐ # q_0: ──■──┤ X ├───────■──┤ X ├ # ┌─┴─┐├───┤┌───┐┌─┴─┐├───┤ # q_1: ┤ X ├┤ H ├┤ X ├┤ X ├┤ X ├ # └───┘└───┘└───┘└───┘└───┘ ref = QuantumCircuit(2) ref.cx(0, 1) ref.x(0) ref.h(1) ref.x(1) ref.cx(0, 1) ref.x(0) ref.x(1) qc = QuantumCircuit(2) qc.cx(0, 1) qc.h(1) expected = NLocal( num_qubits=2, rotation_blocks=XGate(), entanglement_blocks=CXGate(), initial_state=qc, reps=1, ) self.assertCircuitEqual(ref, expected) @ddt class TestTwoLocal(QiskitTestCase): """Tests for the TwoLocal circuit.""" def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True): """An equality test specialized to circuits.""" if transpiled: basis_gates = ["id", "u1", "u3", "cx"] qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0) qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0) qc1, qc2 = qc1_transpiled, qc2_transpiled if visual: self.assertEqual(qc1.draw(), qc2.draw()) else: self.assertEqual(qc1, qc2) def test_skip_final_rotation_layer(self): """Test skipping the final rotation layer works.""" two = TwoLocal(3, ["ry", "h"], ["cz", "cx"], reps=2, skip_final_rotation_layer=True) self.assertEqual(two.num_parameters, 6) # would be 9 with a final rotation layer @data( (5, "rx", "cx", "full", 2, 15), (3, "x", "z", "linear", 1, 0), (3, "rx", "cz", "linear", 0, 3), (3, ["rx", "ry"], ["cry", "cx"], "circular", 2, 24), ) @unpack def test_num_parameters(self, num_qubits, rot, ent, ent_mode, reps, expected): """Test the number of parameters.""" two = TwoLocal( num_qubits, rotation_blocks=rot, entanglement_blocks=ent, entanglement=ent_mode, reps=reps, ) with self.subTest(msg="num_parameters_settable"): self.assertEqual(two.num_parameters_settable, expected) with self.subTest(msg="num_parameters"): self.assertEqual(two.num_parameters, expected) def test_empty_two_local(self): """Test the setup of an empty two-local circuit.""" two = TwoLocal() with self.subTest(msg="0 qubits"): self.assertEqual(two.num_qubits, 0) with self.subTest(msg="no blocks are set"): self.assertListEqual(two.rotation_blocks, []) self.assertListEqual(two.entanglement_blocks, []) with self.subTest(msg="equal to empty circuit"): self.assertEqual(two, QuantumCircuit()) @data("rx", RXGate(Parameter("p")), RXGate, "circuit") def test_various_block_types(self, rot): """Test setting the rotation blocks to various type and assert the output type is RX.""" if rot == "circuit": rot = QuantumCircuit(1) rot.rx(Parameter("angle"), 0) two = TwoLocal(3, rot, reps=0) self.assertEqual(len(two.rotation_blocks), 1) rotation = two.rotation_blocks[0] # decompose self.assertIsInstance(rotation.data[0].operation, RXGate) def test_parameter_setters(self): """Test different possibilities to set parameters.""" two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2) params = [0, 1, 2, Parameter("x"), Parameter("y"), Parameter("z"), 6, 7, 0] params_set = {param for param in params if isinstance(param, Parameter)} with self.subTest(msg="dict assign and copy"): ordered = two.ordered_parameters bound = two.assign_parameters(dict(zip(ordered, params)), inplace=False) self.assertEqual(bound.parameters, params_set) self.assertEqual(two.num_parameters, 9) with self.subTest(msg="list assign and copy"): ordered = two.ordered_parameters bound = two.assign_parameters(params, inplace=False) self.assertEqual(bound.parameters, params_set) self.assertEqual(two.num_parameters, 9) with self.subTest(msg="list assign inplace"): ordered = two.ordered_parameters two.assign_parameters(params, inplace=True) self.assertEqual(two.parameters, params_set) self.assertEqual(two.num_parameters, 3) self.assertEqual(two.num_parameters_settable, 9) def test_parameters_settable_is_constant(self): """Test the attribute num_parameters_settable does not change on parameter change.""" two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2) ordered_params = two.ordered_parameters x = Parameter("x") two.assign_parameters(dict(zip(ordered_params, [x] * two.num_parameters)), inplace=True) with self.subTest(msg="num_parameters collapsed to 1"): self.assertEqual(two.num_parameters, 1) with self.subTest(msg="num_parameters_settable remained constant"): self.assertEqual(two.num_parameters_settable, len(ordered_params)) def test_compose_inplace_to_circuit(self): """Test adding a two-local to an existing circuit.""" two = TwoLocal(3, ["ry", "rz"], "cz", "full", reps=1, insert_barriers=True) circuit = QuantumCircuit(3) circuit.compose(two, inplace=True) # ┌──────────┐┌──────────┐ ░ ░ ┌──────────┐ ┌──────────┐ # q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├ # ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤┌┴──────────┤ # q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├ # ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤├───────────┤ # q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├ # └──────────┘└──────────┘ ░ ░ └──────────┘└───────────┘ reference = QuantumCircuit(3) param_iter = iter(two.ordered_parameters) for i in range(3): reference.ry(next(param_iter), i) for i in range(3): reference.rz(next(param_iter), i) reference.barrier() reference.cz(0, 1) reference.cz(0, 2) reference.cz(1, 2) reference.barrier() for i in range(3): reference.ry(next(param_iter), i) for i in range(3): reference.rz(next(param_iter), i) self.assertCircuitEqual(circuit.decompose(), reference) def test_composing_two(self): """Test adding two two-local circuits.""" entangler_map = [[0, 3], [0, 2]] two = TwoLocal(4, [], "cry", entangler_map, reps=1) circuit = two.compose(two) reference = QuantumCircuit(4) params = two.ordered_parameters for _ in range(2): reference.cry(params[0], 0, 3) reference.cry(params[1], 0, 2) self.assertCircuitEqual(reference, circuit) def test_ry_blocks(self): """Test that the RealAmplitudes circuit is instantiated correctly.""" two = RealAmplitudes(4) with self.subTest(msg="test rotation gate"): self.assertEqual(len(two.rotation_blocks), 1) self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate) with self.subTest(msg="test parameter bounds"): expected = [(-np.pi, np.pi)] * two.num_parameters np.testing.assert_almost_equal(two.parameter_bounds, expected) def test_ry_circuit_reverse_linear(self): """Test a RealAmplitudes circuit with entanglement = "reverse_linear".""" num_qubits = 3 reps = 2 entanglement = "reverse_linear" parameters = ParameterVector("theta", num_qubits * (reps + 1)) param_iter = iter(parameters) expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.ry(next(param_iter), i) expected.cx(1, 2) expected.cx(0, 1) for i in range(num_qubits): expected.ry(next(param_iter), i) library = RealAmplitudes( num_qubits, reps=reps, entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_ry_circuit_full(self): """Test a RealAmplitudes circuit with entanglement = "full".""" num_qubits = 3 reps = 2 entanglement = "full" parameters = ParameterVector("theta", num_qubits * (reps + 1)) param_iter = iter(parameters) # ┌──────────┐ ┌──────────┐ ┌──────────┐ # q_0: ┤ Ry(θ[0]) ├──■────■──┤ Ry(θ[3]) ├──────────────■────■──┤ Ry(θ[6]) ├──────────── # ├──────────┤┌─┴─┐ │ └──────────┘┌──────────┐┌─┴─┐ │ └──────────┘┌──────────┐ # q_1: ┤ Ry(θ[1]) ├┤ X ├──┼─────────■────┤ Ry(θ[4]) ├┤ X ├──┼─────────■────┤ Ry(θ[7]) ├ # ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤ # q_2: ┤ Ry(θ[2]) ├─────┤ X ├─────┤ X ├──┤ Ry(θ[5]) ├─────┤ X ├─────┤ X ├──┤ Ry(θ[8]) ├ # └──────────┘ └───┘ └───┘ └──────────┘ └───┘ └───┘ └──────────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.ry(next(param_iter), i) expected.cx(0, 1) expected.cx(0, 2) expected.cx(1, 2) for i in range(num_qubits): expected.ry(next(param_iter), i) library = RealAmplitudes( num_qubits, reps=reps, entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_ryrz_blocks(self): """Test that the EfficientSU2 circuit is instantiated correctly.""" two = EfficientSU2(3) with self.subTest(msg="test rotation gate"): self.assertEqual(len(two.rotation_blocks), 2) self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate) self.assertIsInstance(two.rotation_blocks[1].data[0].operation, RZGate) with self.subTest(msg="test parameter bounds"): expected = [(-np.pi, np.pi)] * two.num_parameters np.testing.assert_almost_equal(two.parameter_bounds, expected) def test_ryrz_circuit(self): """Test an EfficientSU2 circuit.""" num_qubits = 3 reps = 2 entanglement = "circular" parameters = ParameterVector("theta", 2 * num_qubits * (reps + 1)) param_iter = iter(parameters) # ┌──────────┐┌──────────┐┌───┐ ┌──────────┐┌──────────┐ » # q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├┤ X ├──■──┤ Ry(θ[6]) ├┤ Rz(θ[9]) ├─────────────» # ├──────────┤├──────────┤└─┬─┘┌─┴─┐└──────────┘├──────────┤┌───────────┐» # q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├──┼──┤ X ├─────■──────┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├» # ├──────────┤├──────────┤ │ └───┘ ┌─┴─┐ ├──────────┤├───────────┤» # q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├──■──────────┤ X ├────┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├» # └──────────┘└──────────┘ └───┘ └──────────┘└───────────┘» # « ┌───┐ ┌───────────┐┌───────────┐ # «q_0: ┤ X ├──■──┤ Ry(θ[12]) ├┤ Rz(θ[15]) ├───────────── # « └─┬─┘┌─┴─┐└───────────┘├───────────┤┌───────────┐ # «q_1: ──┼──┤ X ├──────■──────┤ Ry(θ[13]) ├┤ Rz(θ[16]) ├ # « │ └───┘ ┌─┴─┐ ├───────────┤├───────────┤ # «q_2: ──■───────────┤ X ├────┤ Ry(θ[14]) ├┤ Rz(θ[17]) ├ # « └───┘ └───────────┘└───────────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.ry(next(param_iter), i) for i in range(num_qubits): expected.rz(next(param_iter), i) expected.cx(2, 0) expected.cx(0, 1) expected.cx(1, 2) for i in range(num_qubits): expected.ry(next(param_iter), i) for i in range(num_qubits): expected.rz(next(param_iter), i) library = EfficientSU2(num_qubits, reps=reps, entanglement=entanglement).assign_parameters( parameters ) self.assertCircuitEqual(library, expected) def test_swaprz_blocks(self): """Test that the ExcitationPreserving circuit is instantiated correctly.""" two = ExcitationPreserving(5) with self.subTest(msg="test rotation gate"): self.assertEqual(len(two.rotation_blocks), 1) self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RZGate) with self.subTest(msg="test entanglement gate"): self.assertEqual(len(two.entanglement_blocks), 1) block = two.entanglement_blocks[0] self.assertEqual(len(block.data), 2) self.assertIsInstance(block.data[0].operation, RXXGate) self.assertIsInstance(block.data[1].operation, RYYGate) with self.subTest(msg="test parameter bounds"): expected = [(-np.pi, np.pi)] * two.num_parameters np.testing.assert_almost_equal(two.parameter_bounds, expected) def test_swaprz_circuit(self): """Test a ExcitationPreserving circuit in iswap mode.""" num_qubits = 3 reps = 2 entanglement = "linear" parameters = ParameterVector("theta", num_qubits * (reps + 1) + reps * (num_qubits - 1)) param_iter = iter(parameters) # ┌──────────┐┌────────────┐┌────────────┐ ┌──────────┐ » # q_0: ┤ Rz(θ[0]) ├┤0 ├┤0 ├─┤ Rz(θ[5]) ├───────────────» # ├──────────┤│ Rxx(θ[3]) ││ Ryy(θ[3]) │┌┴──────────┴┐┌────────────┐» # q_1: ┤ Rz(θ[1]) ├┤1 ├┤1 ├┤0 ├┤0 ├» # ├──────────┤└────────────┘└────────────┘│ Rxx(θ[4]) ││ Ryy(θ[4]) │» # q_2: ┤ Rz(θ[2]) ├────────────────────────────┤1 ├┤1 ├» # └──────────┘ └────────────┘└────────────┘» # « ┌────────────┐┌────────────┐┌───────────┐ » # «q_0: ────────────┤0 ├┤0 ├┤ Rz(θ[10]) ├───────────────» # « ┌──────────┐│ Rxx(θ[8]) ││ Ryy(θ[8]) │├───────────┴┐┌────────────┐» # «q_1: ┤ Rz(θ[6]) ├┤1 ├┤1 ├┤0 ├┤0 ├» # « ├──────────┤└────────────┘└────────────┘│ Rxx(θ[9]) ││ Ryy(θ[9]) │» # «q_2: ┤ Rz(θ[7]) ├────────────────────────────┤1 ├┤1 ├» # « └──────────┘ └────────────┘└────────────┘» # « # «q_0: ───────────── # « ┌───────────┐ # «q_1: ┤ Rz(θ[11]) ├ # « ├───────────┤ # «q_2: ┤ Rz(θ[12]) ├ # « └───────────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.rz(next(param_iter), i) shared_param = next(param_iter) expected.rxx(shared_param, 0, 1) expected.ryy(shared_param, 0, 1) shared_param = next(param_iter) expected.rxx(shared_param, 1, 2) expected.ryy(shared_param, 1, 2) for i in range(num_qubits): expected.rz(next(param_iter), i) library = ExcitationPreserving( num_qubits, reps=reps, entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_fsim_circuit(self): """Test a ExcitationPreserving circuit in fsim mode.""" num_qubits = 3 reps = 2 entanglement = "linear" # need the parameters in the entanglement blocks to be the same because the order # can get mixed up in ExcitationPreserving (since parameters are not ordered in circuits) parameters = [1] * (num_qubits * (reps + 1) + reps * (1 + num_qubits)) param_iter = iter(parameters) # ┌───────┐┌─────────┐┌─────────┐ ┌───────┐ » # q_0: ┤ Rz(1) ├┤0 ├┤0 ├─■──────┤ Rz(1) ├───────────────────» # ├───────┤│ Rxx(1) ││ Ryy(1) │ │P(1) ┌┴───────┴┐┌─────────┐ » # q_1: ┤ Rz(1) ├┤1 ├┤1 ├─■─────┤0 ├┤0 ├─■─────» # ├───────┤└─────────┘└─────────┘ │ Rxx(1) ││ Ryy(1) │ │P(1) » # q_2: ┤ Rz(1) ├─────────────────────────────┤1 ├┤1 ├─■─────» # └───────┘ └─────────┘└─────────┘ » # « ┌─────────┐┌─────────┐ ┌───────┐ » # «q_0: ─────────┤0 ├┤0 ├─■──────┤ Rz(1) ├───────────────────» # « ┌───────┐│ Rxx(1) ││ Ryy(1) │ │P(1) ┌┴───────┴┐┌─────────┐ » # «q_1: ┤ Rz(1) ├┤1 ├┤1 ├─■─────┤0 ├┤0 ├─■─────» # « ├───────┤└─────────┘└─────────┘ │ Rxx(1) ││ Ryy(1) │ │P(1) » # «q_2: ┤ Rz(1) ├─────────────────────────────┤1 ├┤1 ├─■─────» # « └───────┘ └─────────┘└─────────┘ » # « # «q_0: ───────── # « ┌───────┐ # «q_1: ┤ Rz(1) ├ # « ├───────┤ # «q_2: ┤ Rz(1) ├ # « └───────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.rz(next(param_iter), i) shared_param = next(param_iter) expected.rxx(shared_param, 0, 1) expected.ryy(shared_param, 0, 1) expected.cp(next(param_iter), 0, 1) shared_param = next(param_iter) expected.rxx(shared_param, 1, 2) expected.ryy(shared_param, 1, 2) expected.cp(next(param_iter), 1, 2) for i in range(num_qubits): expected.rz(next(param_iter), i) library = ExcitationPreserving( num_qubits, reps=reps, mode="fsim", entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_circular_on_same_block_and_circuit_size(self): """Test circular entanglement works correctly if the circuit and block sizes match.""" two = TwoLocal(2, "ry", "cx", entanglement="circular", reps=1) parameters = np.arange(two.num_parameters) # ┌───────┐ ┌───────┐ # q_0: ┤ Ry(0) ├──■──┤ Ry(2) ├ # ├───────┤┌─┴─┐├───────┤ # q_1: ┤ Ry(1) ├┤ X ├┤ Ry(3) ├ # └───────┘└───┘└───────┘ ref = QuantumCircuit(2) ref.ry(parameters[0], 0) ref.ry(parameters[1], 1) ref.cx(0, 1) ref.ry(parameters[2], 0) ref.ry(parameters[3], 1) self.assertCircuitEqual(two.assign_parameters(parameters), ref) def test_circuit_with_numpy_integers(self): """Test if TwoLocal can be made from numpy integers""" num_qubits = 6 reps = 3 expected_np32 = [ (i, j) for i in np.arange(num_qubits, dtype=np.int32) for j in np.arange(num_qubits, dtype=np.int32) if i < j ] expected_np64 = [ (i, j) for i in np.arange(num_qubits, dtype=np.int64) for j in np.arange(num_qubits, dtype=np.int64) if i < j ] two_np32 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np32, reps=reps) two_np64 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np64, reps=reps) expected_cx = reps * num_qubits * (num_qubits - 1) / 2 self.assertEqual(two_np32.decompose().count_ops()["cx"], expected_cx) self.assertEqual(two_np64.decompose().count_ops()["cx"], expected_cx) @combine(num_qubits=[4, 5]) def test_full_vs_reverse_linear(self, num_qubits): """Test that 'full' and 'reverse_linear' provide the same unitary element.""" reps = 2 full = RealAmplitudes(num_qubits=num_qubits, entanglement="full", reps=reps) num_params = (reps + 1) * num_qubits np.random.seed(num_qubits) params = np.random.rand(num_params) reverse = RealAmplitudes(num_qubits=num_qubits, entanglement="reverse_linear", reps=reps) full.assign_parameters(params, inplace=True) reverse.assign_parameters(params, inplace=True) self.assertEqual(Operator(full), Operator(reverse)) if __name__ == "__main__": unittest.main()
https://github.com/kevinab107/QiskitPulseRL
kevinab107
# Install the dependencies !pip install tensorflow !pip install -q tf-agents !pip install qiskit !pip install numpy !pip3 uninstall protobuf --yes !pip3 uninstall python-protobuf --yes !pip install protobuf from pulseRL.environment import QiskitEnv import numpy as np from tf_agents.environments import tf_py_environment from pulseRL.agent import Agent from qiskit.visualization import plot_bloch_multivector import matplotlib as plt # Learning Parameters num_iterations = 1000 #In an iteration multiple episodes are collected together and a trajectory is built out of it. #Later these trajectory is used for learning. Trajectory is added to a replay buffer and analysed together. collect_episodes_per_iteration = 250 # replay_buffer_capacity = 2000 learning_rate = 1e-3 num_eval_episodes = 2 eval_interval = 50 num_intervals = 10 interval_length = 60 """Enviroment which make use of Qiskit Pulse Simulator and pulse builder to simulate the dynamics of a qubit under the influence of a pulse. The RL agent interact with this environment through action defined as pulse lenght. Here a constant pulse of amplitude 1 is used and applied for a time "pulse width". "pulse width" is the action that the agent takes here. The agent observes the state obtained with the action along with the Fidelity to the expected final state. Here initial state is fixed to |0> and target state is |1> The pulse is designed as follows The process time is divided into "num_intervals" of length "interval_length". For each interval a constant amplitude of range(0,1) is defined by the agent delay the mesearement channel for num_intervals*interval_length + 10 time and make mesurement. TODO: Make the environement more gernect to handle different operators and initial states""" environment = QiskitEnv(np.array([1,0]), num_intervals, interval_length) #convert the python environment to tensorflow compactible format for training. tf_dumm = tf_py_environment.TFPyEnvironment(environment) """Get the reinfoce agent. Reward is the fielily to target state. Observation is the state""" agent = Agent(num_iterations, collect_episodes_per_iteration, replay_buffer_capacity, learning_rate, num_eval_episodes, eval_interval, num_intervals, interval_length) agent_reinforce = agent.get_agent(environment, 'reinforce', "without_noise_trained") train_results = agent.train(tf_dumm, agent_reinforce) # useful to save the policy for later usage: from tf_agents.policies import policy_saver policy_dir = "policy" tf_policy_saver = policy_saver.PolicySaver(agent_reinforce.policy) tf_policy_saver.save(policy_dir) env_test = QiskitEnv(np.array([0,1]),5,100) vector, fid, action, pulse_prog = agent.evaluate(agent_reinforce, env_test) print("Fidelity : ", fid) control_pulse = [act.numpy()[0][0] for act in action] print("Control pulse", control_pulse) env_test.get_state(control_pulse) #plot_bloch_multivector(vector) pulse_prog.draw() import tensorflow as tf import numpy as np from tensorflow.saved_model import load from tf_agents import policies from pulseRL.environment import QiskitEnv import warnings import logging, sys def evaluate(policy, eval_py_env): eval_env = tf_py_environment.TFPyEnvironment(eval_py_env) num_episodes = 1 fidelity = [] actions = [] for _ in range(num_episodes): time_step = eval_env.reset() while not time_step.is_last(): action_step = policy.action(time_step) time_step = eval_env.step(action_step.action) actions.append(action_step.action) fidelity,state, pulse_prog = eval_py_env.get_state(actions) return state, fidelity, actions,pulse_prog env_test = QiskitEnv(np.array([0,1]),5,100) policy_dir = "best_policy" saved_policy = load(policy_dir) state, fidelity, actions, pulse_prog = evaluate(saved_policy,env_test) print("Showing the results of the best policy") print("Fidelity : ",fidelity) print("Initial State: ", [1,0]) print("Final State: ", state) print("\n\n") pulse_prog.draw() plt.pyplot.plot(train_results[2])
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute import math import random import numpy as np from scipy.optimize import minimize def apply_fixed_ansatz(qubits, parameters): for iz in range (0, len(qubits)): circ.ry(parameters[0][iz], qubits[iz]) circ.cz(qubits[0], qubits[1]) circ.cz(qubits[2], qubits[0]) for iz in range (0, len(qubits)): circ.ry(parameters[1][iz], qubits[iz]) circ.cz(qubits[1], qubits[2]) circ.cz(qubits[2], qubits[0]) for iz in range (0, len(qubits)): circ.ry(parameters[2][iz], qubits[iz]) circ = QuantumCircuit(3) apply_fixed_ansatz([0, 1, 2], [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) print(circ) #Creates the Hadamard test def had_test(gate_type, qubits, ancilla_index, parameters): circ.h(ancilla_index) apply_fixed_ansatz(qubits, parameters) for ie in range (0, len(gate_type[0])): if (gate_type[0][ie] == 1): circ.cz(ancilla_index, qubits[ie]) for ie in range (0, len(gate_type[1])): if (gate_type[1][ie] == 1): circ.cz(ancilla_index, qubits[ie]) circ.h(ancilla_index) circ = QuantumCircuit(4) had_test([[0, 0, 0], [0, 0, 1]], [1, 2, 3], 0, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) print(circ) #Creates controlled anstaz for calculating |<b|psi>|^2 with a Hadamard test def control_fixed_ansatz(qubits, parameters, ancilla, reg): for i in range (0, len(qubits)): circ.cry(parameters[0][i], qiskit.circuit.Qubit(reg, ancilla), qiskit.circuit.Qubit(reg, qubits[i])) circ.ccx(ancilla, qubits[1], 4) circ.cz(qubits[0], 4) circ.ccx(ancilla, qubits[1], 4) circ.ccx(ancilla, qubits[0], 4) circ.cz(qubits[2], 4) circ.ccx(ancilla, qubits[0], 4) for i in range (0, len(qubits)): circ.cry(parameters[1][i], qiskit.circuit.Qubit(reg, ancilla), qiskit.circuit.Qubit(reg, qubits[i])) circ.ccx(ancilla, qubits[2], 4) circ.cz(qubits[1], 4) circ.ccx(ancilla, qubits[2], 4) circ.ccx(ancilla, qubits[0], 4) circ.cz(qubits[2], 4) circ.ccx(ancilla, qubits[0], 4) for i in range (0, len(qubits)): circ.cry(parameters[2][i], qiskit.circuit.Qubit(reg, ancilla), qiskit.circuit.Qubit(reg, qubits[i])) q_reg = QuantumRegister(5) circ = QuantumCircuit(q_reg) control_fixed_ansatz([1, 2, 3], [[1, 1, 1], [1, 1, 1], [1, 1, 1]], 0, q_reg) print(circ) def control_b(ancilla, qubits): for ia in qubits: circ.ch(ancilla, ia) circ = QuantumCircuit(4) control_b(0, [1, 2, 3]) print(circ) #Create the controlled Hadamard test, for calculating <psi|psi> def special_had_test(gate_type, qubits, ancilla_index, parameters, reg): circ.h(ancilla_index) control_fixed_ansatz(qubits, parameters, ancilla_index, reg) for ty in range (0, len(gate_type)): if (gate_type[ty] == 1): circ.cz(ancilla_index, qubits[ty]) control_b(ancilla_index, qubits) circ.h(ancilla_index) q_reg = QuantumRegister(5) circ = QuantumCircuit(q_reg) special_had_test([[0, 0, 0], [0, 0, 1]], [1, 2, 3], 0, [[1, 1, 1], [1, 1, 1], [1, 1, 1]], q_reg) print(circ) #Implements the entire cost function on the quantum circuit def calculate_cost_function(parameters): global opt overall_sum_1 = 0 parameters = [parameters[0:3], parameters[3:6], parameters[6:9]] for i in range(0, len(gate_set)): for j in range(0, len(gate_set)): global circ qctl = QuantumRegister(5) qc = ClassicalRegister(5) circ = QuantumCircuit(qctl, qc) backend = Aer.get_backend('statevector_simulator') multiply = coefficient_set[i]*coefficient_set[j] had_test([gate_set[i], gate_set[j]], [1, 2, 3], 0, parameters) job = execute(circ, backend) result = job.result() outputstate = result.get_statevector(circ, decimals=100) o = outputstate m_sum = 0 for l in range (0, len(o)): if (l%2 == 1): n = float(o[l])**2 m_sum+=n overall_sum_1+=multiply*(1-(2*m_sum)) overall_sum_2 = 0 for i in range(0, len(gate_set)): for j in range(0, len(gate_set)): multiply = coefficient_set[i]*coefficient_set[j] mult = 1 for extra in range(0, 2): qctl = QuantumRegister(5) qc = ClassicalRegister(5) circ = QuantumCircuit(qctl, qc) backend = Aer.get_backend('statevector_simulator') if (extra == 0): special_had_test(gate_set[i], [1, 2, 3], 0, parameters, qctl) if (extra == 1): special_had_test(gate_set[j], [1, 2, 3], 0, parameters, qctl) job = execute(circ, backend) result = job.result() outputstate = result.get_statevector(circ, decimals=100) o = outputstate m_sum = 0 for l in range (0, len(o)): if (l%2 == 1): n = float(o[l])**2 m_sum+=n mult = mult*(1-(2*m_sum)) overall_sum_2+=multiply*mult print(1-float(overall_sum_2/overall_sum_1)) return 1-float(overall_sum_2/overall_sum_1) coefficient_set = [0.55, 0.45] gate_set = [[0, 0, 0], [0, 0, 1]] out = minimize(calculate_cost_function, x0=[float(random.randint(0,3000))/1000 for i in range(0, 9)], method="COBYLA", options={'maxiter':200}) print(out) out_f = [out['x'][0:3], out['x'][3:6], out['x'][6:9]] circ = QuantumCircuit(3, 3) apply_fixed_ansatz([0, 1, 2], out_f) backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) result = job.result() o = result.get_statevector(circ, decimals=10) a1 = coefficient_set[1]*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,-1,0], [0,0,0,0,0,0,0,-1]]) a2 = coefficient_set[0]*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,1,0], [0,0,0,0,0,0,0,1]]) a3 = np.add(a1, a2) b = np.array([float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8))]) print((b.dot(a3.dot(o)/(np.linalg.norm(a3.dot(o)))))**2) coefficient_set = [0.55, 0.225, 0.225] gate_set = [[0, 0, 0], [0, 1, 0], [0, 0, 1]] out = minimize(calculate_cost_function, x0=[float(random.randint(0,3000))/1000 for i in range(0, 9)], method="COBYLA", options={'maxiter':200}) print(out) out_f = [out['x'][0:3], out['x'][3:6], out['x'][6:9]] circ = QuantumCircuit(3, 3) apply_fixed_ansatz([0, 1, 2], out_f) backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) result = job.result() o = result.get_statevector(circ, decimals=10) a1 = coefficient_set[2]*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,-1,0], [0,0,0,0,0,0,0,-1]]) a0 = coefficient_set[1]*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,-1,0], [0,0,0,0,0,0,0,-1]]) a2 = coefficient_set[0]*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,1,0], [0,0,0,0,0,0,0,1]]) a3 = np.add(np.add(a2, a0), a1) b = np.array([float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8))]) print((b.dot(a3.dot(o)/(np.linalg.norm(a3.dot(o)))))**2) #Implements the entire cost function on the quantum circuit (sampling, 100000 shots) def calculate_cost_function(parameters): global opt overall_sum_1 = 0 parameters = [parameters[0:3], parameters[3:6], parameters[6:9]] for i in range(0, len(gate_set)): for j in range(0, len(gate_set)): global circ qctl = QuantumRegister(5) qc = ClassicalRegister(1) circ = QuantumCircuit(qctl, qc) backend = Aer.get_backend('qasm_simulator') multiply = coefficient_set[i]*coefficient_set[j] had_test([gate_set[i], gate_set[j]], [1, 2, 3], 0, parameters) circ.measure(0, 0) job = execute(circ, backend, shots=100000) result = job.result() outputstate = result.get_counts(circ) if ('1' in outputstate.keys()): m_sum = float(outputstate["1"])/100000 else: m_sum = 0 overall_sum_1+=multiply*(1-2*m_sum) overall_sum_2 = 0 for i in range(0, len(gate_set)): for j in range(0, len(gate_set)): multiply = coefficient_set[i]*coefficient_set[j] mult = 1 for extra in range(0, 2): qctl = QuantumRegister(5) qc = ClassicalRegister(1) circ = QuantumCircuit(qctl, qc) backend = Aer.get_backend('qasm_simulator') if (extra == 0): special_had_test(gate_set[i], [1, 2, 3], 0, parameters, qctl) if (extra == 1): special_had_test(gate_set[j], [1, 2, 3], 0, parameters, qctl) circ.measure(0, 0) job = execute(circ, backend, shots=100000) result = job.result() outputstate = result.get_counts(circ) if ('1' in outputstate.keys()): m_sum = float(outputstate["1"])/100000 else: m_sum = 0 mult = mult*(1-2*m_sum) overall_sum_2+=multiply*mult print(1-float(overall_sum_2/overall_sum_1)) return 1-float(overall_sum_2/overall_sum_1) coefficient_set = [0.55, 0.225, 0.225] gate_set = [[0, 0, 0], [0, 1, 0], [0, 0, 1]] out = minimize(calculate_cost_function, x0=[float(random.randint(0,3000))/1000 for i in range(0, 9)], method="COBYLA", options={'maxiter':200}) print(out) out_f = [out['x'][0:3], out['x'][3:6], out['x'][6:9]] circ = QuantumCircuit(3, 3) apply_fixed_ansatz([0, 1, 2], out_f) backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) result = job.result() o = result.get_statevector(circ, decimals=10) a1 = coefficient_set[2]*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,-1,0], [0,0,0,0,0,0,0,-1]]) a0 = coefficient_set[1]*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,-1,0], [0,0,0,0,0,0,0,-1]]) a2 = coefficient_set[0]*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,1,0], [0,0,0,0,0,0,0,1]]) a3 = np.add(np.add(a2, a0), a1) b = np.array([float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8))]) print((b.dot(a3.dot(o)/(np.linalg.norm(a3.dot(o)))))**2)
https://github.com/Hayatto9217/Qiskit9
Hayatto9217
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) 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.3, 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') #duration = 160dt schedule = build_schedule(circ, backend, method="as_late_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() #time = 0 schedule = build_schedule(circ, backend, method="as_soon_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
import numpy as np from scipy.linalg import expm from qiskit import BasicAer from qiskit import execute as q_execute from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import state_fidelity from qiskit.aqua.operators import MatrixOperator, op_converter from qiskit.aqua.components.initial_states import Custom num_qubits = 2 evo_time = 1 temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) h1 = temp + temp.T qubitOp = MatrixOperator(matrix=h1) state_in = Custom(num_qubits, state='random') state_in_vec = state_in.construct_circuit('vector') groundtruth = expm(-1.j * h1 * evo_time) @ state_in_vec print('The directly computed groundtruth evolution result state is\n{}.'.format(groundtruth)) groundtruth_evolution = qubitOp.evolve(state_in_vec, evo_time, num_time_slices=0) print('The groundtruth evolution result as computed by the Dynamics algorithm is\n{}.'.format(groundtruth_evolution)) np.testing.assert_allclose(groundtruth_evolution, groundtruth) qubit_op = op_converter.to_weighted_pauli_operator(qubitOp) quantum_registers = QuantumRegister(qubit_op.num_qubits) circuit = state_in.construct_circuit('circuit', quantum_registers) circuit += qubit_op.evolve( None, evo_time, num_time_slices=1, quantum_registers=quantum_registers, expansion_mode='suzuki', expansion_order=3 ) circuit.draw(output='mpl') backend = BasicAer.get_backend('statevector_simulator') job = q_execute(circuit, backend) circuit_execution_result = np.asarray(job.result().get_statevector(circuit)) print('The evolution result state from executing the Dynamics circuit is\n{}.'.format(circuit_execution_result)) print('Fidelity between the groundtruth and the circuit result states is {}.'.format( state_fidelity(groundtruth, circuit_execution_result) ))
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Numpy for numeric functions import numpy as np # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline def run_on_statevector_simulator(quantum_circuit, decimals=6): """Takes a circuit, and runs it on the state vector simulator backend.""" statevector_simulator = Aer.get_backend('statevector_simulator') job = execute(quantum_circuit, backend=statevector_simulator) result = job.result() statevector = result.get_statevector(quantum_circuit, decimals=decimals) return statevector # Generate a quantum circuit for two qubits qc = QuantumCircuit(2) # Add the gates which generate |psi_0> qc.x(1) qc.h(0) qc.h(1) # Draw the quantum circuit qc.draw(output='mpl') # Run it on the state vector simulator vec = run_on_statevector_simulator(qc) # Visualize the resulting state vector plot_bloch_multivector(vec) # Add a CNOT gate to the circuit qc.cnot(0,1) # Draw the circuit qc.draw(output='mpl') # Run it on the state vector simulator vec = run_on_statevector_simulator(qc) # Visualize the resulting state vector plot_bloch_multivector(vec) # Generate a quantum circuit for two qubits which generates |psi_0> qc2 = QuantumCircuit(2) # Add the gates qc2.x(1) qc2.h(0) qc2.h(1) # Draw the quantum circuit qc2.draw(output='mpl') # Run it on the state vector simulator for various angles of Rx # Number of steps nsteps = 10 for i in range(nsteps): # We add a controlled R_x gate with different angle to our base circuit qc3 = QuantumCircuit(2) qc3.compose(qc2, inplace=True) qc3.crx(i*4*np.pi/nsteps,0,1) # Run the resulting circuit on the state vector simulator vec = run_on_statevector_simulator(qc3) # Visualize the state vector h = plot_bloch_multivector(vec) # Save the image to disk h.savefig(str(i)+'.png')
https://github.com/calebclothier/GoogleDTC
calebclothier
import numpy as np import matplotlib.pyplot as plt from qiskit import IBMQ, assemble, transpile from qiskit import * from statsmodels.graphics.tsaplots import plot_acf N_QUBITS = 20 G = 0.98 T = 40 class DiscreteTimeCrystal: def __init__(self, n_qubits: int) -> None: self.n_qubits = n_qubits provider = IBMQ.load_account() self.backend = provider.backend.ibmq_qasm_simulator def random_bitstring_circuit(self) -> QuantumCircuit: """ Args: n_qubits: number of qubits in the circuit Returns: QuantumCircuit: object that creates a random bitstring from the ground state """ qc = QuantumCircuit(self.n_qubits) random_state = np.random.randint(2, size=self.n_qubits) for i in range(self.n_qubits): if random_state[i]: qc.x(i) return qc def floquet_circuit(self, n_qubits: int, g: float) -> QuantumCircuit: """ Args: n_qubits: number of qubits in the floquet_circuit g: parameter in range [0.5, 1] controlling the magnitude of x-rotation Returns: QuantumCircuit: implementation of the Floquet unitary circuit U_f described in https://arxiv.org/pdf/2107.13571.pdf """ qc = QuantumCircuit(n_qubits) # X rotation by (pi * g) for i in range(n_qubits): qc.rx(np.pi * g, i) # Ising interaction (only coupling adjacent spins) for i in range(0, n_qubits-1, 2): phi = np.random.uniform(low=0.5, high=1.5) theta = np.pi * phi / 2 qc.rzz(-theta, i, i+1) for i in range(1, n_qubits-1, 2): phi = np.random.uniform(low=0.5, high=1.5) theta = np.pi * phi / 2 qc.rzz(-theta, i, i+1) # Longitudinal fields for disorder for i in range(n_qubits): h = np.random.uniform(low=-1, high=1) qc.rz(np.pi * h, i) return qc def mean_polarization(self, counts: dict, q_index: int) -> float: """ Args: counts: dictionary of measurement results and corresponding counts q_index: index of qubit in question Returns: float: the mean polarization, in [-1, 1], of the qubit at q_index, as given by the counts dictionary """ exp, num_shots = 0, 0 for bitstring in counts.keys(): val = 1 if int(bitstring[self.n_qubits-q_index-1]) else -1 exp += val * counts[bitstring] num_shots += counts[bitstring] return exp / num_shots def acf(self, series): n = len(series) data = np.asarray(series) mean = np.mean(data) c0 = np.sum((data - mean) ** 2) / float(n) def r(h): acf_lag = ((data[:n - h] - mean) * (data[h:] - mean)).sum() / float(n) / c0 return round(acf_lag, 3) x = np.arange(n) # Avoiding lag 0 calculation acf_coeffs = list(map(r, x)) return acf_coeffs def simulate(self, initial_state: QuantumCircuit, T: float, g: float, plot=False) -> None: exp_arr = [] floq_qc = self.floquet_circuit(self.n_qubits, g) for t in range(1, T): qc = QuantumCircuit(self.n_qubits) qc = qc.compose(initial_state) for i in range(t): qc = qc.compose(floq_qc) qc.measure_all() transpiled = transpile(qc, backend=self.backend) job = self.backend.run(transpiled) retrieved_job = self.backend.retrieve_job(job.job_id()) counts = retrieved_job.result().get_counts() exp = self.mean_polarization(counts, 11) exp_arr.append(exp) if plot: plt.plot(range(1, T), exp_arr, 'ms-') autocorr = self.acf(exp_arr) print(autocorr) plt.plot(range(1, T), autocorr, 'bs-') plt.show() return exp_arr dtc = DiscreteTimeCrystal(n_qubits=N_QUBITS) exp = [] ac = np.zeros(shape=(T-1)) for j in range(36): print(j) initial_state = dtc.random_bitstring_circuit() q11_z_exp = dtc.simulate(initial_state=initial_state, T=T, g=G, plot=False) q11_z_ac = dtc.acf(q11_z_exp) ac += np.array(q11_z_ac) print(ac) ac = ac / 36 plt.plot(range(1, T), ac, 'bs-') plt.show()
https://github.com/sarthag/Quantum-Algos-using-Qiskit
sarthag
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram, plot_bloch_multivector from qiskit.extensions import Initialize from qiskit_textbook.tools import random_state, array_to_latex import matplotlib.pyplot %pylab inline #Defining srtucture of the circuit circuit = QuantumCircuit(3,1) #Creating a qubit in random state psi = random_state(1) # Display it nicely array_to_latex(psi, pretext="|\\psi\\rangle =") # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" #append inti gate to the qc circuit.append(init_gate, [0]) circuit.barrier() #Creating entanglement in q1 and q2 circuit.h(1) circuit.cx(1,2) circuit.barrier() #Defining gates for sender circuit.cx(0,1) circuit.h(0) circuit.barrier() #reciever gates (different as no operations can be performed after measuring on hardware) circuit.cx(1,2) circuit.cz(0,2) circuit.barrier() #to measure the 3rd qubit inverse_init_gate = init_gate.gates_to_uncompute() circuit.append(inverse_init_gate, [2]) #measure circuit.measure(2,0) circuit.draw('mpl') #Using Quasm Simulator qasm_sim = Aer.get_backend('qasm_simulator') t_qc = transpile(circuit, qasm_sim) qobj = assemble(t_qc) counts = qasm_sim.run(qobj).result().get_counts() plot_histogram(counts) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor shots = 1024 transpiled_circuit = transpile(circuit, backend) qobj = assemble(transpiled_circuit, shots=shots) job = backend.run(qobj) job_monitor(job, interval=2) results = job.result() answer = results.get_counts() plot_histogram(answer)
https://github.com/ctuning/ck-qiskit
ctuning
#!/usr/bin/env python3 import qiskit.tools.apps.optimization num_of_qubits = 2 circuit_depth = 6 num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz ## Previously used for Hydrogen VQE in QISKit implementation # def universal_ansatz(current_params, entangler_map=None): if entangler_map==None: # Which qubits to use (0 to 1 best to avoid qiskit bugs) entangler_map = {1: [0]} return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2.126 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, strike_price - x) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = -sum(uncertainty_model.probabilities[x <= strike_price]) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = -np.array(result_delta.confidence_interval)[::-1] print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % -result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/epelaaez/QuantumLibrary
epelaaez
# To clean enviroment variables %reset import numpy as np import pandas as pd import folium import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit_algorithms import SamplingVQE from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler df = pd.read_csv("uscities.csv") columnsNeeded = ["city", "lat", "lng"] # Inicialization of variables locationsNumber = 15 # OJO que en local me crashea si sobrepaso 5 coordenatesDf = df[columnsNeeded].iloc[:locationsNumber] n = coordenatesDf.shape[0] # number of nodes + depot (n+1) K = 3 # number of vehicles print(coordenatesDf) # Initialize instance values by calculate the squared Euclidean distances between a set of coordinates # represented in the dataframe. def generate_instance(coordenatesDf): n = coordenatesDf.shape[0] xc = coordenatesDf["lat"] yc = coordenatesDf["lng"] loc = coordenatesDf["city"] instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance, loc # Initialize the problem by randomly generating the instance lat, lng, instance, loc = generate_instance(coordenatesDf) print(lat, lng, loc, instance) #print(instance) class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 #vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) #optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) print(qp) #quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) print(classical_cost) m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m print(quantum_cost) x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x_quantum[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m algorithms = ("Classic", "Quantum") data = { 'K = 1': (2249.2068134000006, 1706.2245994000696), 'k = 2': (2771.940853740001, 1845.127222779207), 'K = 3': (3981.1556002800016, 3981.155600280501), } x = np.arange(len(algorithms)) # the label locations width = 0.25 # the width of the bars multiplier = 0 fig, ax = plt.subplots(layout='constrained') for attribute, measurement in data.items(): offset = width * multiplier rects = ax.bar(x + offset, measurement, width, label=attribute) ax.bar_label(rects, padding=3) multiplier += 1 # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Length (mm)') ax.set_title('Comparision of Quantum and Classical Cost') ax.set_xticks(x + width, algorithms) ax.legend(loc='upper left', ncols=3) ax.set_ylim(0, 5000) plt.show()
https://github.com/Naphann/Solving-TSP-Grover
Naphann
import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer import numpy as np from math import floor, ceil %matplotlib inline def RTL(qc, a, b, c): ## fig 3 dashed qc.rccx(a, b, c) def RTL_inv(qc, a, b, c): RTL(qc, a, b, c) def RTS(qc, a, b, c): ## fig 3 gates 2-6 qc.h(c) qc.t(c) qc.cx(b, c) qc.tdg(c) qc.cx(a, c) def RTS_inv(qc, a, b, c): qc.cx(a, c) qc.t(c) qc.cx(b, c) qc.tdg(c) qc.h(c) def SRTS(qc, a, b, c): ## circuit 3 dashed qc.h(c) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) def SRTS_inv(qc, a, b, c): qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.h(c) def RT4L(qc, a, b, c, d): ## fig 4 qc.rcccx(a, b, c, d) def RT4L_inv(qc, a, b, c, d): qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) def RT4S(qc, a, b, c, d): ## fig 4 dashed qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) def RT4S_inv(qc, a, b, c, d): qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) def apply_mct_clean(self, controls, target, ancilla_register): if len(controls) < 3: raise ValueError("there's something wrong") n = len(controls) ancilla = ancilla_register[:ceil((n-2)/2)] if n == 3: # TODO: Check for ancilla length self.rccx(controls[0], controls[1], ancilla[0]) self.ccx(controls[2], ancilla[0], target) self.rccx(controls[0], controls[1], ancilla[0]) return if n == 4: # TODO: Check for ancilla length self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.ccx(controls[3], ancilla[0], target) self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) return ## when controls >= 5 if n % 2 == 0: self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.barrier() anc_idx = 1 for i in range(3, n-1, 2): # print('i = /{}'.format(i)) self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() anc_idx += 1 if (n-3)%2 == 1: self.ccx(controls[-1], ancilla[-1], target) self.barrier() else: self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() self.ccx(controls[-1], ancilla[-1], target) self.barrier() self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() for i in reversed(range(3, n-1, 2)): anc_idx -= 1 self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) else: self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.barrier() anc_idx = 1 for i in range(3, n-3, 2): # print('i = /{}'.format(i)) self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() anc_idx += 1 if (n-3)%2 == 1: self.ccx(controls[-1], ancilla[-1], target) self.barrier() else: self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() self.ccx(controls[-1], ancilla[-1], target) self.barrier() self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() for i in reversed(range(3, n-3, 2)): anc_idx -= 1 self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) qr = QuantumRegister(5, 'qr') anc = QuantumRegister(2, 'anc') target = QuantumRegister(1, 'target') qc = QuantumCircuit(qr, anc, target) apply_mct_clean(qc, qr, target, anc) # backend = Aer.get_backend('unitary_simulator') # job = qiskit.execute(qc, backend) # result = job.result() # print(result.get_unitary(qc, decimals=3)) # qc.draw(output='mpl') def apply_mct_dirty(self, controls, target, ancilla): # TODO: check controls to be list of bits or register if len(controls) == 1: self.cx(controls[0], target) return if len(controls) == 2: self.ccx(controls[0], controls[1], target) return if len(controls) == 3: SRTS(self, controls[2], ancilla[0], target) RTL(self, controls[0], controls[1], ancilla[0]) SRTS_inv(self, controls[2], ancilla[0], target) RTL_inv(self, controls[0], controls[1], ancilla[0]) return n = len(controls) anc = ancilla[:ceil((n-2)/2)] SRTS(self, controls[-1], anc[-1], target) qc.barrier() if (n-4)%2 == 0: a_idx = 1 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) qc.barrier() else: a_idx = 2 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) qc.barrier() RTS(self, anc[0], controls[3], anc[1]) qc.barrier() RT4L(self, controls[0], controls[1], controls[2], anc[0]) qc.barrier() if (n-4)%2 == 0: a_idx = 1 for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) qc.barrier() else: a_idx = 2 RTS_inv(self, anc[0], controls[3], anc[1]) qc.barrier() for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) qc.barrier() SRTS_inv(self, controls[-1], anc[-1], target) qc.barrier() ## SAME AS ABOVE if (n-4)%2 == 0: a_idx = 1 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) qc.barrier() else: a_idx = 2 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) qc.barrier() RTS(self, anc[0], controls[3], anc[1]) qc.barrier() RT4L_inv(self, controls[0], controls[1], controls[2], anc[0]) qc.barrier() if (n-4)%2 == 0: a_idx = 1 for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) qc.barrier() else: a_idx = 2 RTS_inv(self, anc[0], controls[3], anc[1]) qc.barrier() for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) qc.barrier() qr = QuantumRegister(3, 'qr') anc = QuantumRegister(3, 'anc') target = QuantumRegister(1, 'target') qc = QuantumCircuit(qr, anc, target) apply_mct_dirty(qc, qr, target, anc) # backend = Aer.get_backend('unitary_simulator') # job = qiskit.execute(qc, backend) # result = job.result() # print(result.get_unitary(qc, decimals=3)) # qc.draw(output='mpl') for n in range(5, 10): print('{}-bit controls'.format(n)) for inp in range(2**n): qr = QuantumRegister(n, 'qr') anc = QuantumRegister(max(ceil((n-2)/2), 1), 'anc') target = QuantumRegister(1) cr = ClassicalRegister(1, 'cr') qc = QuantumCircuit(qr, anc, target, cr) for i in range(n): if (inp & (1<<i)) > 0: qc.x(qr[i]) # apply_mct_dirty(qc, qr, target, anc) apply_mct_clean(qc, qr, target, anc) qc.barrier() qc.measure(target, cr[0]) backend = Aer.get_backend('qasm_simulator') job = qiskit.execute(qc, backend, shots=10) result = job.result() counts = result.get_counts() # print(inp) if '1' in counts: print('{} got 1'.format(inp)) def apply_mct(circuit, controls, target, anc, mode='clean-ancilla'): if len(controls) == 1: circuit.cx(controls[0], target) else if mode == 'clean-ancilla':
https://github.com/C2QA/bosonic-qiskit
C2QA
import math import multiprocessing import os import pathlib import matplotlib import matplotlib.animation import matplotlib.pyplot as plt import numpy import qiskit from c2qa.circuit import CVCircuit from c2qa.discretize import discretize_circuits, discretize_single_circuit from c2qa.wigner import simulate_wigner, simulate_wigner_multiple_statevectors def animate_wigner( circuit: CVCircuit, qubit: qiskit.circuit.quantumcircuit.QubitSpecifier = None, cbit: qiskit.circuit.quantumcircuit.ClbitSpecifier = None, animation_segments: int = 10, discretize_epsilon: float = None, shots: int = 1, file: str = None, axes_min: int = -6, axes_max: int = 6, axes_steps: int = 200, processes: int = None, keep_state: bool = True, noise_passes = None, sequential_subcircuit: bool = False, draw_grid: bool = False, trace: bool = True, bitrate: int = -1 ): """Animate the Wigner function at each step defined in the given CVCirctuit. This assumes the CVCircuit was simulated with an animation_segments > 0 to act as the frames of the generated movie. The ffmpeg binary must be on your system PATH in order to execute this function. See https://ffmpeg.org/download.html to download and install on your system. Args: circuit (CVCircuit): circuit to simulate and plot qubit ([type]): Qubit to measure, if performing Hadamard measure for use with cat states. Defaults to None. cbit ([type]): Classical bit to measure into, if performing Hadamard measure for use with cat states. Defaults to None. animation_segments (int, optional): Number of segments to split each gate into for animation. Defaults to 10. shots (int, optional): Number of simulation shots per frame. Defaults to 1. file (str, optional): File path to save (supported formats include MP4 with ffmpeg installed, animated GIF, and APNG). If None, return plot. Defaults to None. axes_min (int, optional): Minimum axes plot value. Defaults to -6. axes_max (int, optional): Maximum axes plot value. Defaults to 6. axes_steps (int, optional): Steps between axes ticks. Defaults to 200. processes (int, optional): Number of parallel Python processes to start. If None, perform serially in main process. Defaults to None. keep_state (bool, optional): True if each frame builds on the previous frame's state vector. False if each frame starts over from the beginning of the circuit. If True, it requires sequential simulation of each frame. noise_passes (list of Qiskit noise passes, optional): noise passes to apply sequential_subcircuit (bool, optional): boolean flag to animate subcircuits as one gate (False) or as sequential gates (True). Defautls to False. draw_grid (bool, optional): True if grid lines should be drawn on plot. Defaults to False. trace (bool, optional): True if qubits should be tracedfor each frame prior to calculating Wigner function. Defaults to True. Returns: [type]: [description] """ if qubit or cbit: w_fock, xvec = __discretize_wigner_with_measure( circuit, qubit, cbit, animation_segments, shots, axes_min, axes_max, axes_steps, processes, keep_state, noise_passes, sequential_subcircuit, trace ) else: w_fock, xvec = __discretize_wigner_without_measure( circuit, animation_segments, discretize_epsilon, shots, axes_min, axes_max, axes_steps, noise_passes, sequential_subcircuit, trace ) # Remove None values in w_fock if simulation didn't produce results w_fock = [i for i in w_fock if i is not None] # Animate w_fock Wigner function results # Create empty plot to animate fig, ax = plt.subplots(constrained_layout=True) # Animate anim = matplotlib.animation.FuncAnimation( fig=fig, init_func=_animate_init, func=_animate, frames=len(w_fock), fargs=(fig, ax, xvec, w_fock, file, draw_grid), interval=200, repeat=True, ) # Save to file using ffmpeg, Pillow (GIF, APNG), or display if file: save_animation(anim, file, bitrate) return anim def __discretize_wigner_with_measure( circuit: CVCircuit, qubit: qiskit.circuit.quantumcircuit.QubitSpecifier = None, cbit: qiskit.circuit.quantumcircuit.ClbitSpecifier = None, animation_segments: int = 10, shots: int = 1, axes_min: int = -6, axes_max: int = 6, axes_steps: int = 200, processes: int = None, keep_state: bool = True, noise_passes = None, sequential_subcircuit: bool = False, trace: bool = True, ): circuits = discretize_circuits(circuit, animation_segments, keep_state, qubit, cbit, sequential_subcircuit) # Calculate the Wigner functions for each frame if not processes or processes < 1: processes = math.floor(multiprocessing.cpu_count() / 2) processes = max(processes, 1) # prevent zero processes with 1 CPU # Simulate each frame, storing Wigner function data in w_fock xvec = numpy.linspace(axes_min, axes_max, axes_steps) if keep_state: w_fock = __simulate_wigner_with_state(circuits, qubit, cbit, xvec, shots, noise_passes, trace) elif processes == 1: w_fock = [] for circuit in circuits: fock, _ = simulate_wigner( circuit, xvec, shots, noise_passes=noise_passes, conditional=cbit is not None, trace=trace or cbit is not None, ) w_fock.append(fock) else: pool = multiprocessing.Pool(processes) results = pool.starmap( simulate_wigner, ( (circuit, xvec, shots, noise_passes, cbit is not None, trace or cbit is not None) for circuit in circuits ), ) pool.close() w_fock = [i[0] for i in results if i is not None] return w_fock, xvec def __discretize_wigner_without_measure( circuit: CVCircuit, animation_segments: int = 10, discretize_epsilon: float = None, shots: int = 1, axes_min: int = -6, axes_max: int = 6, axes_steps: int = 200, noise_passes = None, sequential_subcircuit: bool = False, trace: bool = True, ): statevector_label = "segment_" discretized, num_statevectors = discretize_single_circuit( circuit=circuit, segments_per_gate=animation_segments, epsilon=discretize_epsilon, sequential_subcircuit=sequential_subcircuit, statevector_per_segment=True, statevector_label=statevector_label, noise_passes=noise_passes) xvec = numpy.linspace(axes_min, axes_max, axes_steps) w_fock = simulate_wigner_multiple_statevectors( circuit=discretized, xvec=xvec, shots=shots, statevector_label=statevector_label, num_statevectors=num_statevectors, noise_passes=noise_passes, trace=trace ) return w_fock, xvec def save_animation(anim: matplotlib.animation.FuncAnimation, file: str, bitrate: int): file_path = pathlib.Path(file) if file_path.suffix == ".mp4": writer = matplotlib.animation.FFMpegWriter(fps=24, bitrate=bitrate) elif file_path.suffix == ".gif" or file_path.suffix == ".apng": writer = matplotlib.animation.PillowWriter(fps=24, bitrate=bitrate) else: print( f"Unknown animation file type {file_path.suffix}, defaulting to using PillowWriter" ) writer = matplotlib.animation.PillowWriter(fps=24, bitrate=bitrate) anim.save(file, writer=writer) def _animate_init(): pass # Prevent rendering frame 0 twice (once for init, once for animate) def _animate(frame, *fargs): """Generate individual matplotlib frame in animation.""" fig = fargs[0] ax = fargs[1] xvec = fargs[2] w_fock = fargs[3][frame] file = fargs[4] draw_grid = fargs[5] amax = numpy.amax(w_fock) amin = numpy.amin(w_fock) abs_max = max(amax, abs(amin)) if abs_max == 0: abs_max = 5 color_levels = numpy.linspace(-abs_max, abs_max, 100) xvec_int = [int(x) for x in xvec] xvec_int = sorted(set(xvec_int)) ax.clear() cont = ax.contourf(xvec, xvec, w_fock, color_levels, cmap="RdBu") ax.set_xlabel(r"$x$") ax.set_xticks(xvec_int) ax.set_ylabel(r"$p$") ax.set_yticks(xvec_int) if draw_grid: ax.grid() if frame == 0: fig.colorbar(cont, ax=ax) time_text = ax.text(0.05, 0.95, "", horizontalalignment="left", verticalalignment="top", transform=ax.transAxes) time_text.set_text(f"Frame {frame}") if file: os.makedirs(f"{file}_frames", exist_ok=True) plt.savefig(f"{file}_frames/frame_{frame}.png") def __simulate_wigner_with_state(circuits, qubit, cbit, xvec, shots, noise_passes, trace): """Simulate Wigner function, preserving state between iterations""" w_fock = [] previous_state = None for circuit in circuits: if previous_state: # Initialize circuit to simulate with the previous frame's state, then append the last instruction sim_circuit = circuit.copy() sim_circuit.data.clear() # Is this safe -- could we copy without data? sim_circuit.initialize(previous_state) if qubit and cbit: last_instructions = circuit.data[ -3: ] # Get the last instruction, plus the Hadamard/measure else: last_instructions = circuit.data[-1:] # Get the last instruction for inst in last_instructions: sim_circuit.append(*inst) else: # No previous simulation state, just run the current circuit sim_circuit = circuit fock, previous_state = simulate_wigner( sim_circuit, xvec, shots, noise_passes=noise_passes, conditional=cbit is not None, trace=trace or cbit is not None, ) w_fock.append(fock) return w_fock
https://github.com/stefan-woerner/qiskit_optimization_circuits
stefan-woerner
# useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes import numpy as np import networkx as nx from qiskit import Aer, execute, QuantumCircuit from qiskit.quantum_info import Statevector # auxilliary function to plot graphs def plot_result(G, x): colors = ['r' if x[i] == 0 else 'b' for i in range(n)] pos, default_axes = nx.spring_layout(G), plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos) # create graph G = nx.Graph() # add nodes n = 5 G.add_nodes_from(range(n)) # add edges: tuple is (i,j,weight) where (i,j) is the edge edges = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0), (2, 4, 1.0), (3, 4, 1.0)] G.add_weighted_edges_from(edges) # plot graph plot_result(G, [0]*n) from docplex.mp.model import Model mdl = Model('MaxCut') x = mdl.binary_var_list('x{}'.format(i) for i in range(n)) objective = mdl.sum([ w * (x[i] + x[j] - 2*x[i]*x[j]) for (i, j, w) in edges]) mdl.maximize(objective) mdl.prettyprint() b = 2 mdl.add_constraint(mdl.sum(x) == b) mdl.prettyprint() from qiskit.optimization import QuadraticProgram from qiskit.optimization.algorithms import CplexOptimizer # convert from DOcplex model to Qiskit Quadratic Program qp = QuadraticProgram() qp.from_docplex(mdl) # Solve Quadratic Program using CPLEX cplex = CplexOptimizer() result = cplex.solve(qp) print(result) plot_result(G, result.x) from qiskit.optimization.converters import ( InequalityToEquality, # converts inequality constraints to equality constraints by adding slack variables LinearEqualityToPenalty, # converts linear equality constraints to quadratic penalty terms IntegerToBinary, # converts integer variables to binary variables QuadraticProgramToQubo # combines the previous three converters ) lineq2penalty = LinearEqualityToPenalty(penalty=1) qp_wo_constr = lineq2penalty.convert(qp) qp_wo_constr # Solve converted Quadratic Program using CPLEX result = cplex.solve(qp_wo_constr) print(result) plot_result(G, result.x) H, offset = qp_wo_constr.to_ising() print('offset =', offset) print() print('H =', H) # print Ising Hamiltonian as matrix H_matrix = np.real(H.to_matrix()) print('dim(H):', H_matrix.shape) print(H_matrix) # plot diagonal of matrix opt_indices = list(np.where(H_matrix.diagonal() == min(H_matrix.diagonal())))[0] plt.figure(figsize=(12, 5)) plt.bar(range(2**n), H_matrix.diagonal()) plt.bar(opt_indices, H_matrix.diagonal()[opt_indices], color='g') plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14) plt.show() from qiskit.circuit.library import RealAmplitudes qc = RealAmplitudes(5, reps=1) qc.draw(fold=120) # run VQE from qiskit.aqua.algorithms import VQE vqe = VQE(H, qc, quantum_instance=Aer.get_backend('statevector_simulator')) result = vqe.run() print('optimal value:', np.round(result.eigenvalue, decimals=4)) # plot probabilities probabilities = np.abs(result.eigenstate)**2 plt.figure(figsize=(12, 5)) plt.bar(range(2**n), probabilities) plt.bar(opt_indices, probabilities[opt_indices], color='g') plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14) plt.show() from qiskit.circuit import Parameter gamma, beta = Parameter('gamma'), Parameter('beta') qc = QuantumCircuit(1) qc.h(0) qc.barrier() qc.rz(gamma, 0) qc.rx(beta, 0) qc.barrier() qc.draw() def construct_schedule(T, N): delta_t = T/N gammas, betas = [], [] # H_C, H_X parameters for i in range(N+1): t = i * delta_t gammas += [ 2 * delta_t * t/T ] # H_C betas += [ -2 * delta_t * (1 - t/T) ] # H_X return gammas, betas T = 5 N = 10 gammas, betas = construct_schedule(T, N) plt.figure(figsize=(10, 4)) plt.plot(np.linspace(0, T, N+1), gammas, label='gammas') plt.plot(np.linspace(0, T, N+1), betas, label='betas') plt.legend(fontsize=14) plt.xticks(fontsize=14) plt.xlabel('time', fontsize=14) plt.yticks(fontsize=14) plt.ylabel('parameters', fontsize=14); # track probabilities during trotterized annealing probabilities = np.zeros((2, N+1)) # construct circuit qc = QuantumCircuit(1) qc.h(0) qc.barrier() for i, (gamma, beta) in enumerate(zip(gammas, betas)): qc.rz(gamma, 0) qc.rx(beta, 0) qc.barrier() probabilities[:, i] = Statevector.from_instruction(qc).probabilities() qc.draw() plt.figure(figsize=(12, 7)) plt.plot(np.linspace(0, T, N+1), probabilities[1, :], 'gd-', label=r'$|1\rangle$') plt.plot(np.linspace(0, T, N+1), probabilities[0, :], 'bo-', label=r'$|0\rangle$') plt.legend(fontsize=14) plt.xticks(fontsize=14) plt.xlabel('time $t$', fontsize=14) plt.yticks(fontsize=14) plt.ylabel('probabilities', fontsize=14); plt.figure(figsize=(12, 7)) plt.plot(np.linspace(0, T, N+1), probabilities[0, :] - probabilities[1, :], 'gd-') plt.xticks(fontsize=14) plt.xlabel('time $t$', fontsize=14) plt.yticks(fontsize=14) plt.ylabel('objective value', fontsize=14); gamma = Parameter('gamma') qc1 = QuantumCircuit(2) qc1.cx(0, 1) qc1.rz(gamma, 1) qc1.cx(0, 1) qc1.draw() qc2 = QuantumCircuit(2) qc2.rzz(gamma, 0, 1) qc2.draw() from qiskit.aqua.components.optimizers import COBYLA # QAOA circuit for p = 1 gamma, beta = Parameter('gamma'), Parameter('beta') qc = QuantumCircuit(1) qc.h(0) qc.rz(gamma, 0) qc.rx(beta, 0) def objective(params): qc_ = qc.bind_parameters({gamma: params[0], beta: params[1]}) probs = Statevector.from_instruction(qc_).probabilities() return probs @ [1, -1] optimizer = COBYLA() result = optimizer.optimize(num_vars=2, objective_function=objective, initial_point=[0.5, 0.5]) print('optimal params:', np.round(result[0], decimals=4)) print('optimal value: ', np.round(result[1], decimals=4)) print('optimal state: ', np.round(Statevector.from_instruction(qc.bind_parameters( {gamma: result[0][0], beta: result[0][1]})).data, decimals=4)) from qiskit.aqua.algorithms.minimum_eigen_solvers.qaoa.var_form import QAOAVarForm # construct parameters from annealing schedule T = 10 N = 20 gammas, betas = construct_schedule(T, N) # construct variational form var_form = QAOAVarForm(H, N+1) # evaluate circuit qc = var_form.construct_circuit(gammas + betas) sv = Statevector.from_instruction(qc) # plot probabilities probabilities = sv.probabilities() plt.figure(figsize=(12, 5)) plt.bar(range(2**n), probabilities) plt.bar(opt_indices, probabilities[opt_indices], color='g') plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14); # illustrating the QAOA var form p = 1 var_form = QAOAVarForm(H, p) var_form.construct_circuit([gamma, beta]).draw() from qiskit.aqua.algorithms import QAOA qaoa_mes = QAOA(H, p=1, optimizer=optimizer, quantum_instance=Aer.get_backend('statevector_simulator')) result = qaoa_mes.run() print('optimal params: ', result.optimal_parameters) print('optimal value: ', result.optimal_value) print('optimal probability: ', sum(np.abs(result.eigenstate[opt_indices])**2)) # plot probabilities probabilities = np.abs(result['eigenstate'])**2 plt.figure(figsize=(12, 5)) plt.bar(range(2**n), probabilities) plt.bar(opt_indices, probabilities[opt_indices], color='g') plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14) plt.show() from qiskit.optimization.algorithms import MinimumEigenOptimizer # construct QAOA as Minimum Eigensolver qaoa_mes = QAOA(p=1, optimizer=optimizer, quantum_instance=Aer.get_backend('statevector_simulator')) # construct Minimum Eigen Optimizer based on QAOA qaoa = MinimumEigenOptimizer(qaoa_mes) # solve Quadratic Program result = qaoa.solve(qp) print(result) plot_result(G, result.x) # converts two's complement bit string to corresponding integer def twos_complement(val, num_bits): val = int(val, 2) if (val & (1 << (num_bits - 1))) != 0: val = val - (1 << num_bits) return val print(twos_complement('0011', 4)) print(twos_complement('1011', 4)) from qiskit.circuit.library import QFT def encode(num_qubits, k): qc = QuantumCircuit(num_qubits, name='enc({})'.format(k)) for i in range(num_qubits): theta = 2*np.pi * 2**i / 2**num_qubits * k qc.rz(theta, i) return qc num_value_qubits = 4 qc = QuantumCircuit(num_value_qubits, num_value_qubits) qc.h(range(num_value_qubits)) qc.barrier() qc.extend(encode(num_value_qubits, 2)) qc.barrier() qc.append(QFT(num_value_qubits, do_swaps=False).inverse(), qc.qubits) qc.measure(qc.qregs[0], qc.cregs[0][::-1]) qc.draw(fold=120) num_value_qubits = 4 qc = QuantumCircuit(num_value_qubits, num_value_qubits) qc.h(range(num_value_qubits)) qc.barrier() qc.extend(encode(num_value_qubits, 2)) # qc.extend(encode(num_value_qubits, -3)) # qc.extend(encode(num_value_qubits, 4)) qc.barrier() qc.append(QFT(num_value_qubits, do_swaps=False, inverse=True), qc.qubits) qc.measure(qc.qregs[0], qc.cregs[0][::-1]) qc.draw(fold=120) counts = execute(qc, Aer.get_backend('qasm_simulator')).result().get_counts() for key in counts: print(key, ' -->', twos_complement(key, num_value_qubits)) num_input_qubits = 3 num_total_qubits = num_input_qubits + num_value_qubits qc = QuantumCircuit(num_total_qubits) qc.h([0, 1, 2]) qc.barrier() qc.h(range(num_input_qubits, num_total_qubits)) qc.append(encode(num_value_qubits, 2).control(2), [0, 2] + list(range(num_input_qubits, num_total_qubits))) qc.append(encode(num_value_qubits, -3).control(), [1] + list(range(num_input_qubits, num_total_qubits))) qc.append(encode(num_value_qubits, 4).control(), [2] + list(range(num_input_qubits, num_total_qubits))) qc.append(QFT(num_value_qubits, do_swaps=False).inverse(), range(num_input_qubits, num_total_qubits)) qc.measure_all() qc.draw(fold=120) counts = execute(qc, Aer.get_backend('qasm_simulator')).result().get_counts() for key, value in counts.items(): x = key[num_value_qubits:] y_bin = key[:num_value_qubits][::-1] y_int = twos_complement(y_bin, num_value_qubits) print(x, '-->', y_bin, '-->', y_int, '\t(counts: {})'.format(value)) from qiskit.circuit.library import QuadraticForm # get quadratic / linear / constant part of quadratic program A = qp_wo_constr.objective.quadratic.to_array() b = qp_wo_constr.objective.linear.to_array() c = qp_wo_constr.objective.constant # set number of results qubits num_value_qubits = 5 # construct circuit to evaluate quadratic form qf = QuadraticForm(num_value_qubits, A, b, c) qf.draw(fold=115) qc = QuantumCircuit(n + num_value_qubits) qc.h(range(n)) qc.append(qf, range(n + num_value_qubits)) qc.measure_all() qc.draw() counts = execute(qc, backend=Aer.get_backend('qasm_simulator')).result().get_counts() for key, value in counts.items(): x_ = key[num_value_qubits:] x = [0 if x__ == '0' else 1 for x__ in x_][::-1] y_bin = key[:num_value_qubits] y_int = twos_complement(y_bin, num_value_qubits) qx = qp_wo_constr.objective.evaluate(x) print('x =', x_, '\ty_bin =', y_bin, '\ty_int =', y_int, '\tQ(x) =', qx, '\t(counts: {})'.format(value)) qc = QuantumCircuit(n + num_value_qubits) qc.append(qf, range(n + num_value_qubits)) # 1. compute Q(x) qc.z(qc.qubits[-1]) # 2. multiply all |x>|Q(x)> by -1 where Q(x) < 0. qc.append(qf.inverse(), range(n + num_value_qubits)) # 3. uncompute Q(x). qc.draw(output='text', vertical_compression="high") from qiskit.optimization.algorithms import GroverOptimizer # set up Grover Optimizer grover = GroverOptimizer(num_value_qubits=5, quantum_instance=Aer.get_backend('statevector_simulator')) grover._qubo_converter.penalty = 1 # set to small value to reduce required number of value qubits # solver problem result = grover.solve(qp) print(result) plot_result(G, result.x)
https://github.com/divyanshchoubisa/Quantum-Computing-Dynamic-Circuits
divyanshchoubisa
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) ####### your code goes here ####### qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.draw("mpl") answer_0 = 2 #answer_0 = 500 print ##### Hint: Remember to run this cell after changing your value ### # Grader Cell: Run this to submit your answer from qc_grader.challenges.spring_2023 import grade_ex1a grade_ex1a(answer_0) 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) ####### your code goes here ####### with qc.if_test((b0, 0)) as else_: qc.x(q1) with else_: qc.h(q1) 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}") # Submit your circuit from qc_grader.challenges.spring_2023 import grade_ex1b grade_ex1b(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.""" ####### your code goes here ####### t = target c0, c1 = controls m0, m1 = measures circuit.h(c0) circuit.h(c1) circuit.h(t) circuit.ccx(c0, c1, t) circuit.s(t) circuit.ccx(c0, c1, t) circuit.h(c0) circuit.h(c1) circuit.h(t) circuit.measure(c0, m0) circuit.measure(c1, m1) qc = base.copy_empty_like() trial(qc, target, controls, mid_measure) qc.draw("mpl", cregbundle=False) # Submit your circuit from qc_grader.challenges.spring_2023 import grade_ex1c grade_ex1c(qc) def reset_controls( circuit: QuantumCircuit, controls: QuantumRegister, measures: ClassicalRegister ): """Reset the control qubits if they are in |1>.""" c0, c1 = controls m0, m1 = measures ####### your code goes here ####### with qc.if_test((m0, 1)): circuit.x(c0) with qc.if_test((m1, 1)): circuit.x(c1) 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) # Submit your circuit from qc_grader.challenges.spring_2023 import grade_ex1d grade_ex1d(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() qc = circuit # The first trial does not need to reset its inputs, since the controls # are guaranteed to start in the |0> state. trial(qc, 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(qc, controls, mid_measure) with qc.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_: ####### your code goes here ####### qc.x(target) trial(qc, target, controls, mid_measure) # We need to measure the control qubits again to ensure we # get their final results; this is a hardware limitation. qc.measure(controls, mid_measure) # Finally, let's measure our target, to check that we're # getting the rotation we desired. qc.measure(target, final_measure) qc.draw("mpl", cregbundle=False) # Submit your circuit from qc_grader.challenges.spring_2023 import grade_ex1e grade_ex1e(circuit) sim = AerSimulator() job = sim.run(circuit, shots=1000) result = job.result() counts = result.get_counts() plot_histogram(counts) from qiskit_ibm_provider import IBMProvider provider = IBMProvider() hub = "qc-spring-23-1" group = "group-1" project = "recIvcxUcc27LvvSh" backend_name = "ibm_peekskill" backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}") from qiskit import transpile qc_transpiled = transpile(circuit, backend) job = backend.run(qc_transpiled, shots=1000, dynamic=True) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/urwin419/QiskitChecker
urwin419
import numpy as np import qiskit as q #Code based on Qiskit offcial Textbook #Create the oracle for the Deutsch-Jozsa Algorithm def dj_oracle(case: str, num_qubits: int) -> q.QuantumCircuit: #Create the circuit oracle_qc = q.QuantumCircuit(num_qubits + 1) #Create the balanced oracle if case == "balanced": #Ganerate a random binary string b = np.random.randint(1, 2 ** num_qubits) b_str = format(b, f"0{num_qubits}b") for index, bit in enumerate(b_str): if bit == "1": #If the position is equal to 1, apply X-gate oracle_qc.x(index) for index in range(num_qubits): #For all the qubits, apply CX-gate oracle_qc.cx(index, num_qubits) for index, bit in enumerate(b_str): if bit == "1": #If the position is equal to 1, apply X-gate oracle_qc.x(index) #Create the the constant oracle if case == "constant": #Set the output to 0 or 1 randomly output = np.random.randint(2) if output == 1: #If the position is equal to 1, apply X-gate oracle_qc.x(num_qubits) #Create the Gate oracle_gate = oracle_qc.to_gate() return oracle_gate #Carry out the Deutsch-Jozsa Algorithm def dj_algorithm(oracle: q.QuantumCircuit, num_qubits: int) -> q.QuantumCircuit: #Create a quantum circuit dj_circuit = q.QuantumCircuit(num_qubits + 1, num_qubits) #Apply X-gates to the output qubit dj_circuit.x(num_qubits) #Apply H-gates to the output qubit dj_circuit.h(num_qubits) #Apply H-gate to all qubits for qubit in range(num_qubits): dj_circuit.h(qubit) #Apply the oracle created dj_circuit.append(oracle, range(num_qubits + 1)) #Apply H-gate to all qubits for qubit in range(num_qubits): dj_circuit.h(qubit) #Measure all the qubits for i in range(num_qubits): dj_circuit.measure(i, i) return dj_circuit #Run the simulation with the created circuit def deutsch_jozsa(case: str, num_qubits: int) -> q.result.counts.Counts: #Get the simulator simulator = q.Aer.get_backend("qasm_simulator") #Get the oracle oracle = dj_oracle(case, num_qubits) #Ger the circuit dj_circuit = dj_algorithm(oracle, num_qubits) #Performe the algorithm job = q.execute(dj_circuit, simulator, shots=1000) return job.result().get_counts(dj_circuit)
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. """Helper function for converting a circuit to an instruction.""" from qiskit.exceptions import QiskitError from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit.classicalregister import ClassicalRegister, Clbit def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None, label=None): """Build an :class:`~.circuit.Instruction` object from a :class:`.QuantumCircuit`. The instruction is anonymous (not tied to a named quantum register), and so can be inserted into another circuit. The instruction will have the same string name as the circuit. Args: circuit (QuantumCircuit): the input circuit. parameter_map (dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. equivalence_library (EquivalenceLibrary): Optional equivalence library where the converted instruction will be registered. label (str): Optional instruction label. Raises: QiskitError: if parameter_map is not compatible with circuit Return: qiskit.circuit.Instruction: an instruction equivalent to the action of the input circuit. Upon decomposition, this instruction will yield the components comprising the original circuit. Example: .. code-block:: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.converters import circuit_to_instruction q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) circuit_to_instruction(circ) """ # pylint: disable=cyclic-import from qiskit.circuit.quantumcircuit import QuantumCircuit if parameter_map is None: parameter_dict = {p: p for p in circuit.parameters} else: parameter_dict = circuit._unroll_param_dict(parameter_map) if parameter_dict.keys() != circuit.parameters: raise QiskitError( ( "parameter_map should map all circuit parameters. " "Circuit parameters: {}, parameter_map: {}" ).format(circuit.parameters, parameter_dict) ) out_instruction = Instruction( name=circuit.name, num_qubits=circuit.num_qubits, num_clbits=circuit.num_clbits, params=[*parameter_dict.values()], label=label, ) out_instruction.condition = None target = circuit.assign_parameters(parameter_dict, inplace=False) if equivalence_library is not None: equivalence_library.add_equivalence(out_instruction, target) regs = [] if out_instruction.num_qubits > 0: q = QuantumRegister(out_instruction.num_qubits, "q") regs.append(q) if out_instruction.num_clbits > 0: c = ClassicalRegister(out_instruction.num_clbits, "c") regs.append(c) qubit_map = {bit: q[idx] for idx, bit in enumerate(circuit.qubits)} clbit_map = {bit: c[idx] for idx, bit in enumerate(circuit.clbits)} definition = [ instruction.replace( qubits=[qubit_map[y] for y in instruction.qubits], clbits=[clbit_map[y] for y in instruction.clbits], ) for instruction in target.data ] # fix condition for rule in definition: condition = getattr(rule.operation, "condition", None) if condition: reg, val = condition if isinstance(reg, Clbit): rule.operation.condition = (clbit_map[reg], val) elif reg.size == c.size: rule.operation.condition = (c, val) else: raise QiskitError( "Cannot convert condition in circuit with " "multiple classical registers to instruction" ) qc = QuantumCircuit(*regs, name=out_instruction.name) for instruction in definition: qc._append(instruction) if circuit.global_phase: qc.global_phase = circuit.global_phase out_instruction.definition = qc return out_instruction
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import numpy as np import matplotlib.pyplot as plt import itertools import random import pickle 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 = 100 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits # qr = QuantumRegister(7) qc = QuantumCircuit(3) # 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([1,0]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) qc.x([1]) # encoding # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [1, 0]) qc.cx(1, 2) qc.cx(0, 1) # 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}) # circuit optimization t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_qc = transpile(t3_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, [2, 1, 0]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates # Pauli Twirling def pauli_twirling(circ: str) -> QuantumCircuit: """ そのまま使う: 修正は後回し """ #! qasm ベタ書き def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'id q[{qb}];\n' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解 for op in ops: if (op[:2] == 'cx'): # can add for cz, etc. num = random.randrange(len(paulis)) #! permute paulis qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0]): """ """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] #! 後からPauli Twirlingを施す! return folded_qcs zne_qcs = zne_wrapper(st_qcs) print("number of circuits: ", len(zne_qcs)) zne_qcs[-3].draw("mpl") zne_qcs_jakarta = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"], initial_layout=[5,3,1]) zne_qcs_jakarta = transpile(zne_qcs_jakarta, optimization_level=3, basis_gates=["sx", "cx", "rz"]) from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 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) print('Job ID', cal_job.job_id()) with open("jakarta_100step.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) 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/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Phase Estimation Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../quantum-fourier-transform/qsim"] import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate from execute import BenchmarkResult # Benchmark Name benchmark_name = "Phase Estimation" np.random.seed(0) verbose = False # saved subcircuits circuits for printing QC_ = None QFTI_ = None U_ = None ############### Circuit Definition def PhaseEstimation(num_qubits, theta): qr = QuantumRegister(num_qubits) num_counting_qubits = num_qubits - 1 # only 1 state qubit cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr, cr, name=f"qpe-{num_qubits}-{theta}") # initialize counting qubits in superposition for i in range(num_counting_qubits): qc.h(qr[i]) # change to |1> in state qubit, so phase will be applied by cphase gate qc.x(num_counting_qubits) qc.barrier() repeat = 1 for j in reversed(range(num_counting_qubits)): # controlled operation: adds phase exp(i*2*pi*theta*repeat) to the state |1> # does nothing to state |0> cp, _ = CPhase(2*np.pi*theta, repeat) qc.append(cp, [j, num_counting_qubits]) repeat *= 2 #Define global U operator as the phase operator _, U = CPhase(2*np.pi*theta, 1) qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr[:num_counting_qubits]) qc.barrier() # measure counting qubits qc.measure([qr[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_, U_, QFTI_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if U_ == None or num_qubits <= 5: if num_qubits < 9: U_ = U if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) return qc #Construct the phase gates and include matching gate representation as readme circuit def CPhase(angle, exponent): qc = QuantumCircuit(1, name=f"U^{exponent}") qc.p(angle*exponent, 0) phase_gate = qc.to_gate().control(1) return phase_gate, qc # Analyze and print measured results # Expected result is always theta, so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, theta, num_shots): if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts counts = probs # calculate expected output histogram correct_dist = theta_to_bitstring(theta, num_counting_qubits) # generate thermal_dist to be comparable to correct_dist thermal_dist = metrics.uniform_dist(num_counting_qubits) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring theta correctly 100% of the time app_counts = bitstring_to_theta(counts, num_counting_qubits) app_correct_dist = {theta: 1.0} app_thermal_dist = bitstring_to_theta(thermal_dist, num_counting_qubits) if verbose: print(f"For theta {theta}, expected: {correct_dist} measured: {counts}") print(f" ... For theta {theta} thermal_dist: {thermal_dist}") print(f"For theta {theta}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For theta {theta} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) hf_fidelity = metrics.hellinger_fidelity_with_expected(counts, correct_dist) if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return counts, fidelity # Convert theta to a bitstring distribution def theta_to_bitstring(theta, num_counting_qubits): counts = {format( int(theta * (2**num_counting_qubits)), "0"+str(num_counting_qubits)+"b"): 1.0} return counts # Convert bitstring to theta representation, useful for debugging def bitstring_to_theta(counts, num_counting_qubits): theta_counts = {} for key in counts.keys(): r = counts[key] theta = int(key,2) / (2**num_counting_qubits) if theta not in theta_counts.keys(): theta_counts[theta] = 0 theta_counts[theta] += r return theta_counts ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") num_state_qubits = 1 # default, not exposed to users, cannot be changed in current implementation # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: PE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(3, min_qubits), num_state_qubits + 2) skip_qubits = max(1, skip_qubits) #print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, theta, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(theta), num_shots) metrics.store_metric(num_qubits, theta, 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: theta_range = [i/(2**(num_counting_qubits)) for i in list(range(num_circuits))] else: theta_range = [i/(2**(num_counting_qubits)) for i in np.random.choice(2**(num_counting_qubits), num_circuits, False)] # loop over limited # of random theta choices for theta in theta_range: # create the circuit for given qubit size and theta, store time metric ts = time.time() qc = PhaseEstimation(num_qubits, theta).reverse_bits() # to change the endianness metrics.store_metric(num_qubits, theta, 'create_time', time.time() - ts) # collapse the 3 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, theta, num_shots) # Wait for some active circuits to complete; report metrics when groups complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nPhase Operator 'U' = "); print(U_ if U_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * print(qiskit.__version__) %matplotlib inline from qiskit.tools.visualization import plot_histogram from ibm_quantum_widgets import draw_circuit # initialize two qubits in the zero state and # two classical bits in the zero state in the quantum circuit circuit = QuantumCircuit(3,3) # C gate # (2) => q2 circuit.x(2) circuit.draw(output='mpl') draw_circuit(circuit) # Hadamard (H) gate # (0) => (q0) circuit.h(0) circuit.draw(output='mpl') draw_circuit(circuit) # A controlled-NOT (CX NOT) gate, on control qubit 0 # and target qubit 1, putting the qubits in an entangled state. # (2,1) = > q2(control bit)(quantum bit)(origin) --> q1(target bit)(quantum bit)(destination) circuit.cx(2,1) # (0,2) = > q0(control bit)(quantum bit)(origin) --> q2(target bit)(quantum bit)(destination) circuit.cx(0,2) circuit.draw(output='mpl') draw_circuit(circuit) # measurement between quantum state and classical state # [1,1] => [q1,q1](quantum bit) and [2,0] => [c2,c0](classical bit) circuit.measure([1,1],[2,0]) circuit.draw(output='mpl') draw_circuit(circuit) # The n qubit’s measurement result will be stored in the n classical bit circuit.measure([1,1,2],[2,0,0]) circuit.draw(output='mpl') draw_circuit(circuit) simulator = Aer.get_backend("qasm_simulator") job = execute(circuit, simulator, shots=2024) result = job.result() counts = result.get_counts(circuit) print("Total count for 100 and 101 are: ", counts) # 1. plot_histogram(counts) # 2. from ibm_quantum_widgets import draw_circuit draw_circuit(circuit)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(range(2)) qc.measure(range(2), range(2)) # apply x gate if the classical register has the value 2 (10 in binary) qc.x(0).c_if(cr, 2) # apply y gate if bit 0 is set to 1 qc.y(1).c_if(0, 1) qc.draw('mpl')
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/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
from qiskit import * # Loading your IBM Quantum account(s) provider = IBMQ.load_account() circuit = QuantumCircuit(3,3) %matplotlib inline circuit.x(0) circuit.barrier() circuit.h(1) circuit.cx(1,2) circuit.barrier() circuit.cx(0,1) circuit.h(0) circuit.barrier() circuit.measure([0, 1], [0, 1]) circuit.barrier() circuit.cx(1, 2) circuit.cz(0, 2) circuit.measure([2], [2]) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) print(circuit.qasm()) statevector_simulator = Aer.get_backend('statevector_simulator') result=execute(circuit,statevector_simulator).result() statevector_results=result.get_statevector(circuit) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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 sys import logging import time import copy import os import uuid import numpy as np from qiskit import compiler from qiskit.assembler import assemble_circuits from qiskit.providers import BaseBackend, JobStatus, JobError from qiskit.providers.basicaer import BasicAerJob from qiskit.qobj import QobjHeader from qiskit.aqua.aqua_error import AquaError from qiskit.aqua.utils import summarize_circuits from qiskit.aqua.utils.backend_utils import (is_aer_provider, is_basicaer_provider, is_ibmq_provider, is_simulator_backend, is_local_backend) MAX_CIRCUITS_PER_JOB = os.environ.get('QISKIT_AQUA_MAX_CIRCUITS_PER_JOB', None) logger = logging.getLogger(__name__) def find_regs_by_name(circuit, name, qreg=True): """Find the registers in the circuits. Args: circuit (QuantumCircuit): the quantum circuit. name (str): name of register qreg (bool): quantum or classical register Returns: QuantumRegister or ClassicalRegister or None: if not found, return None. """ found_reg = None regs = circuit.qregs if qreg else circuit.cregs for reg in regs: if reg.name == name: found_reg = reg break return found_reg def _avoid_empty_circuits(circuits): new_circuits = [] for qc in circuits: if len(qc) == 0: tmp_q = None for q in qc.qregs: tmp_q = q break if tmp_q is None: raise NameError("A QASM without any quantum register is invalid.") qc.iden(tmp_q[0]) new_circuits.append(qc) return new_circuits def _combine_result_objects(results): """Tempoary helper function. TODO: This function would be removed after Terra supports job with infinite circuits. """ if len(results) == 1: return results[0] new_result = copy.deepcopy(results[0]) for idx in range(1, len(results)): new_result.results.extend(results[idx].results) return new_result def _maybe_add_aer_expectation_instruction(qobj, options): if 'expectation' in options: from qiskit.providers.aer.utils.qobj_utils import snapshot_instr, append_instr, get_instr_pos # add others, how to derive the correct used number of qubits? # the compiled qobj could be wrong if coupling map is used. params = options['expectation']['params'] num_qubits = options['expectation']['num_qubits'] for idx in range(len(qobj.experiments)): # if mulitple params are provided, we assume that each circuit is corresponding one param # otherwise, params are used for all circuits. param_idx = idx if len(params) > 1 else 0 snapshot_pos = get_instr_pos(qobj, idx, 'snapshot') if len(snapshot_pos) == 0: # does not append the instruction yet. new_ins = snapshot_instr('expectation_value_pauli', 'test', list(range(num_qubits)), params=params[param_idx]) qobj = append_instr(qobj, idx, new_ins) else: for i in snapshot_pos: # update all expectation_value_snapshot if qobj.experiments[idx].instructions[i].type == 'expectation_value_pauli': qobj.experiments[idx].instructions[i].params = params[param_idx] return qobj def _compile_wrapper(circuits, backend, backend_config, compile_config, run_config): transpiled_circuits = compiler.transpile(circuits, backend, **backend_config, **compile_config) if not isinstance(transpiled_circuits, list): transpiled_circuits = [transpiled_circuits] qobj = assemble_circuits(transpiled_circuits, qobj_id=str(uuid.uuid4()), qobj_header=QobjHeader(), run_config=run_config) return qobj, transpiled_circuits def compile_circuits(circuits, backend, backend_config=None, compile_config=None, run_config=None, show_circuit_summary=False, circuit_cache=None, **kwargs): """ An execution wrapper with Qiskit-Terra, with job auto recover capability. The autorecovery feature is only applied for non-simulator backend. This wraper will try to get the result no matter how long it costs. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute backend (BaseBackend): backend instance backend_config (dict, optional): configuration for backend compile_config (dict, optional): configuration for compilation run_config (RunConfig, optional): configuration for running a circuit show_circuit_summary (bool, optional): showing the summary of submitted circuits. circuit_cache (CircuitCache, optional): A CircuitCache to use when calling compile_and_run_circuits Returns: QasmObj: compiled qobj. Raises: AquaError: Any error except for JobError raised by Qiskit Terra """ backend_config = backend_config or {} compile_config = compile_config or {} run_config = run_config or {} if backend is None or not isinstance(backend, BaseBackend): raise ValueError('Backend is missing or not an instance of BaseBackend') if not isinstance(circuits, list): circuits = [circuits] if is_simulator_backend(backend): circuits = _avoid_empty_circuits(circuits) if MAX_CIRCUITS_PER_JOB is not None: max_circuits_per_job = int(MAX_CIRCUITS_PER_JOB) else: if is_local_backend(backend): max_circuits_per_job = sys.maxsize else: max_circuits_per_job = backend.configuration().max_experiments if circuit_cache is not None and circuit_cache.try_reusing_qobjs: # Check if all circuits are the same length. # If not, don't try to use the same qobj.experiment for all of them. if len(set([len(circ.data) for circ in circuits])) > 1: circuit_cache.try_reusing_qobjs = False else: # Try setting up the reusable qobj # Compile and cache first circuit if cache is empty. The load method will try to reuse it if circuit_cache.qobjs is None: qobj, transpiled_circuits = _compile_wrapper([circuits[0]], backend, backend_config, compile_config, run_config) if is_aer_provider(backend): qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs) circuit_cache.cache_circuit(qobj, [circuits[0]], 0) qobjs = [] transpiled_circuits = [] chunks = int(np.ceil(len(circuits) / max_circuits_per_job)) for i in range(chunks): sub_circuits = circuits[i * max_circuits_per_job:(i + 1) * max_circuits_per_job] if circuit_cache is not None and circuit_cache.misses < circuit_cache.allowed_misses: try: if circuit_cache.cache_transpiled_circuits: transpiled_sub_circuits = compiler.transpile(sub_circuits, backend, **backend_config, **compile_config) qobj = circuit_cache.load_qobj_from_cache(transpiled_sub_circuits, i, run_config=run_config) else: qobj = circuit_cache.load_qobj_from_cache(sub_circuits, i, run_config=run_config) if is_aer_provider(backend): qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs) # cache miss, fail gracefully except (TypeError, IndexError, FileNotFoundError, EOFError, AquaError, AttributeError) as e: circuit_cache.try_reusing_qobjs = False # Reusing Qobj didn't work if len(circuit_cache.qobjs) > 0: logger.info('Circuit cache miss, recompiling. Cache miss reason: ' + repr(e)) circuit_cache.misses += 1 else: logger.info('Circuit cache is empty, compiling from scratch.') circuit_cache.clear_cache() qobj, transpiled_sub_circuits = _compile_wrapper(sub_circuits, backend, backend_config, compile_config, run_config) transpiled_circuits.extend(transpiled_sub_circuits) if is_aer_provider(backend): qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs) try: circuit_cache.cache_circuit(qobj, sub_circuits, i) except (TypeError, IndexError, AquaError, AttributeError, KeyError) as e: try: circuit_cache.cache_transpiled_circuits = True circuit_cache.cache_circuit(qobj, transpiled_sub_circuits, i) except (TypeError, IndexError, AquaError, AttributeError, KeyError) as e: logger.info('Circuit could not be cached for reason: ' + repr(e)) logger.info('Transpilation may be too aggressive. Try skipping transpiler.') else: qobj, transpiled_sub_circuits = _compile_wrapper(sub_circuits, backend, backend_config, compile_config, run_config) transpiled_circuits.extend(transpiled_sub_circuits) if is_aer_provider(backend): qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs) qobjs.append(qobj) if logger.isEnabledFor(logging.DEBUG) and show_circuit_summary: logger.debug("==== Before transpiler ====") logger.debug(summarize_circuits(circuits)) logger.debug("==== After transpiler ====") logger.debug(summarize_circuits(transpiled_circuits)) return qobjs def _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation): # assure get job ids while True: job = run_on_backend(backend, qobj, backend_options=backend_options, noise_config=noise_config, skip_qobj_validation=skip_qobj_validation) try: job_id = job.job_id() break except JobError as e: logger.warning("FAILURE: Can not get job id, Resubmit the qobj to get job id." "Terra job error: {} ".format(e)) except Exception as e: logger.warning("FAILURE: Can not get job id, Resubmit the qobj to get job id." "Error: {} ".format(e)) return job, job_id def run_qobjs(qobjs, backend, qjob_config=None, backend_options=None, noise_config=None, skip_qobj_validation=False): """ An execution wrapper with Qiskit-Terra, with job auto recover capability. The autorecovery feature is only applied for non-simulator backend. This wraper will try to get the result no matter how long it costs. Args: qobjs (list[QasmObj]): qobjs to execute backend (BaseBackend): backend instance qjob_config (dict, optional): configuration for quantum job object backend_options (dict, optional): configuration for simulator noise_config (dict, optional): configuration for noise model skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time Returns: Result: Result object Raises: AquaError: Any error except for JobError raised by Qiskit Terra """ qjob_config = qjob_config or {} backend_options = backend_options or {} noise_config = noise_config or {} if backend is None or not isinstance(backend, BaseBackend): raise ValueError('Backend is missing or not an instance of BaseBackend') with_autorecover = False if is_simulator_backend(backend) else True jobs = [] job_ids = [] for qobj in qobjs: job, job_id = _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation) job_ids.append(job_id) jobs.append(job) results = [] if with_autorecover: logger.info("Backend status: {}".format(backend.status())) logger.info("There are {} jobs are submitted.".format(len(jobs))) logger.info("All job ids:\n{}".format(job_ids)) for idx in range(len(jobs)): job = jobs[idx] job_id = job_ids[idx] while True: logger.info("Running {}-th qobj, job id: {}".format(idx, job_id)) # try to get result if possible try: result = job.result(**qjob_config) if result.success: results.append(result) logger.info("COMPLETED the {}-th qobj, " "job id: {}".format(idx, job_id)) break else: logger.warning("FAILURE: the {}-th qobj, " "job id: {}".format(idx, job_id)) except JobError as e: # if terra raise any error, which means something wrong, re-run it logger.warning("FAILURE: the {}-th qobj, job id: {} " "Terra job error: {} ".format(idx, job_id, e)) except Exception as e: raise AquaError("FAILURE: the {}-th qobj, job id: {} " "Unknown error: {} ".format(idx, job_id, e)) from e # something wrong here if reach here, querying the status to check how to handle it. # keep qeurying it until getting the status. while True: try: job_status = job.status() break except JobError as e: logger.warning("FAILURE: job id: {}, " "status: 'FAIL_TO_GET_STATUS' " "Terra job error: {}".format(job_id, e)) time.sleep(5) except Exception as e: raise AquaError("FAILURE: job id: {}, " "status: 'FAIL_TO_GET_STATUS' " "Unknown error: ({})".format(job_id, e)) from e logger.info("Job status: {}".format(job_status)) # handle the failure job based on job status if job_status == JobStatus.DONE: logger.info("Job ({}) is completed anyway, retrieve result " "from backend.".format(job_id)) job = backend.retrieve_job(job_id) elif job_status == JobStatus.RUNNING or job_status == JobStatus.QUEUED: logger.info("Job ({}) is {}, but encounter an exception, " "recover it from backend.".format(job_id, job_status)) job = backend.retrieve_job(job_id) else: logger.info("Fail to run Job ({}), resubmit it.".format(job_id)) qobj = qobjs[idx] # assure job get its id job, job_id = _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation) jobs[idx] = job job_ids[idx] = job_id else: results = [] for job in jobs: results.append(job.result(**qjob_config)) result = _combine_result_objects(results) if len(results) != 0 else None return result def compile_and_run_circuits(circuits, backend, backend_config=None, compile_config=None, run_config=None, qjob_config=None, backend_options=None, noise_config=None, show_circuit_summary=False, circuit_cache=None, skip_qobj_validation=False, **kwargs): """ An execution wrapper with Qiskit-Terra, with job auto recover capability. The autorecovery feature is only applied for non-simulator backend. This wraper will try to get the result no matter how long it costs. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute backend (BaseBackend): backend instance backend_config (dict, optional): configuration for backend compile_config (dict, optional): configuration for compilation run_config (RunConfig, optional): configuration for running a circuit qjob_config (dict, optional): configuration for quantum job object backend_options (dict, optional): configuration for simulator noise_config (dict, optional): configuration for noise model show_circuit_summary (bool, optional): showing the summary of submitted circuits. circuit_cache (CircuitCache, optional): A CircuitCache to use when calling compile_and_run_circuits skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time Returns: Result: Result object Raises: AquaError: Any error except for JobError raised by Qiskit Terra """ qobjs = compile_circuits(circuits, backend, backend_config, compile_config, run_config, show_circuit_summary, circuit_cache, **kwargs) result = run_qobjs(qobjs, backend, qjob_config, backend_options, noise_config, skip_qobj_validation) return result # skip_qobj_validation = True does what backend.run and aerjob.submit do, but without qobj validation. def run_on_backend(backend, qobj, backend_options=None, noise_config=None, skip_qobj_validation=False): if skip_qobj_validation: job_id = str(uuid.uuid4()) if is_aer_provider(backend): from qiskit.providers.aer.aerjob import AerJob temp_backend_options = backend_options['backend_options'] if backend_options != {} else None temp_noise_config = noise_config['noise_model'] if noise_config != {} else None job = AerJob(backend, job_id, backend._run_job, qobj, temp_backend_options, temp_noise_config, False) job._future = job._executor.submit(job._fn, job._job_id, job._qobj, *job._args) elif is_basicaer_provider(backend): backend._set_options(qobj_config=qobj.config, **backend_options) job = BasicAerJob(backend, job_id, backend._run_job, qobj) job._future = job._executor.submit(job._fn, job._job_id, job._qobj) elif is_ibmq_provider(backend): # TODO: IBMQJob performs validation during the constructor. the following lines does not # skip validation but run as is. from qiskit.providers.ibmq.ibmqjob import IBMQJob job = IBMQJob(backend, None, backend._api, qobj=qobj) job._future = job._executor.submit(job._submit_callback) else: logger.info("Can't skip qobj validation for the third-party provider.") job = backend.run(qobj, **backend_options, **noise_config) return job else: job = backend.run(qobj, **backend_options, **noise_config) return job
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') # Python imports import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() # Qiskit from qiskit import BasicAer from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B from qiskit.circuit.library import TwoLocal # VOLTA from volta.vqd import VQD from volta.utils import classical_solver from volta.hamiltonians import BCS_hamiltonian %load_ext autoreload %autoreload 2 EPSILONS = [3., 3., 3., 4., 3.] V = -2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(f"Hamiltonian: {hamiltonian}\n") eigenvalues, eigenvectors = classical_solver(hamiltonian) print(f"Eigenvalues: {eigenvalues}") from itertools import product # Get the ideal count ideal_dict = {} bin_combinations = list(product(['0','1'], repeat=hamiltonian.num_qubits)) for i, eigvect in enumerate(np.abs(eigenvectors)**2): dic = {} for ind, val in enumerate(bin_combinations): val = ''.join(val) dic[val] = eigvect[ind] ideal_dict[i] = dic from qiskit.aqua import QuantumInstance # Define Optimizer # optimizer = COBYLA() optimizer = SPSA(maxiter=250, c1=.7, last_avg=25) # optimizer = L_BFGS_B() # Define Backend # backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=10000) # Define ansatz ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3) # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=3, beta=10., optimizer=optimizer, backend=backend) Algo.run() vqd_energies = Algo.energies vqd_states = Algo.states from copy import copy # Create states and measure them states = [] for ind, state in enumerate(vqd_states): states.append(copy(state)) states[ind].measure_all() from qiskit import execute from qiskit.visualization import plot_histogram fig, axs = plt.subplots(2, 2, figsize=(30,15)) for i, ax in zip(range(len(states)), axs.flat): count = execute(states[i], backend=backend, shots=10000).result().get_counts() plot_histogram([ideal_dict[i], count],legend=['Ideal','Result'], ax=ax) print(f'Ideal eigenvalues: {eigenvalues}') print(f'Obtained eigenvalues: {vqd_energies}') n_1_sim, n_2_sim = 1, 2 n_1_vqd, n_2_vqd = 1, 2 print(f"Gap Exact: {(eigenvalues[n_2_sim] - eigenvalues[n_1_sim])/2}") print(f"Gap VQD: {(vqd_energies[n_2_vqd] - vqd_energies[n_1_vqd])/2}") from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel # T1 and T2 values for qubits 0-n n_qubits = 4 T1s = np.random.normal(50e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec T1s = [30e3]*n_qubits T2s = [20e3]*n_qubits # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(n_qubits)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(n_qubits): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(n_qubits): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) from qiskit.aqua import QuantumInstance from qiskit import Aer # Define Optimizer # optimizer = COBYLA() optimizer = SPSA(maxiter=250, c1=.7, last_avg=25) # Define Backend backend = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), noise_model=noise_thermal, shots=10000) # Define ansatz ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3) # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=3, beta=10., optimizer=optimizer, backend=backend) Algo.run() vqd_energies = Algo.energies vqd_states = Algo.states from copy import copy # Create states and measure them states = [] for ind, state in enumerate(vqd_states): states.append(copy(state)) states[ind].measure_all() from qiskit import execute from qiskit.visualization import plot_histogram import seaborn as sns sns.set() fig, axs = plt.subplots(2, 2, figsize=(30,15)) backend = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), noise_model=noise_thermal, shots=10000) for i, ax in zip(range(len(states)), axs.flat): count = backend.execute(states[i]).get_counts() plot_histogram([ideal_dict[i], count],legend=['Ideal','Result'], ax=ax) print(f'Ideal eigenvalues: {eigenvalues}') print(f'Obtained eigenvalues: {vqd_energies}') n_1_sim, n_2_sim = 1, 2 n_1_vqd, n_2_vqd = 1, 2 print(f"Gap Exact: {(eigenvalues[n_2_sim] - eigenvalues[n_1_sim])/2}") print(f"Gap VQD: {(vqd_energies[n_2_vqd] - vqd_energies[n_1_vqd])/2}") from tqdm import tqdm from qiskit.aqua import QuantumInstance es_1 = [] es_2 = [] n = 50 for _ in tqdm(range(n)): # Define Optimizer optimizer = COBYLA() # Define Backend # backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=10000) # Define ansatz ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2) # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=2, beta=10., optimizer=optimizer, backend=backend) Algo.run(0) vqd_energies = Algo.energies es_1.append(vqd_energies[1]) es_2.append(vqd_energies[2]) np.savetxt("groundstate.txt", es_1) np.savetxt("excitedstate.txt", es_2) print(f"Ground State: {np.round(np.mean(es_1),3)} +/- {np.round(np.std(es_1),3)} | Expected: {eigenvalues[1]}") print(f"Excited State: {np.round(np.mean(es_2),3)} +/- {np.round(np.std(es_2),3)} | Expected: {eigenvalues[2]}") np.round(np.mean(es_2) - np.mean(es_1), 3)/2 import seaborn as sns sns.boxplot(x=es_1) ax=sns.swarmplot(x=es_1, color="0.25") ax.set_title("1st Excited State") ax.vlines(x=eigenvalues[1], ymin=-10, ymax=10, label='Expected Eigenvalue',color='r') plt.legend() plt.show() sns.boxplot(x=es_2) ax=sns.swarmplot(x=es_2, color="0.25") ax.set_title("2nd Excited State") ax.vlines(x=eigenvalues[2], ymin=-10, ymax=10, label='Expected Eigenvalue',color='r') plt.legend() plt.show() sns.boxplot(x=(np.array(es_2)- np.array(es_1))/2) ax=sns.swarmplot(x=(np.array(es_2)- np.array(es_1))/2, color="0.25") ax.set_title("Gap") ax.vlines(x=(eigenvalues[2] - eigenvalues[1])/2, ymin=-10, ymax=10, label='Expected value',color='r') plt.legend() plt.show() v_dependence =[] v_values = np.linspace(0, 5, 20) for v in v_values: EPSILONS = [3., 3., 3., 4., 3.] hamiltonian = BCS_hamiltonian(EPSILONS, -float(v)) eigenvalues, eigenvectors = classical_solver(hamiltonian) v_dependence.append(eigenvalues[1] - eigenvalues[0]) plt.plot(v_values, v_dependence, 'o');
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/JouziP/MQITE
JouziP
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 6 11:35:58 2022 @author: pejmanjouzdani """ import numpy as np from qiskit import QuantumCircuit from BasicFunctions.functions import getBinary def getImagPart_base_circ(nspins, circ_U , Q, j_ref, gamma = np.pi/10): circ_adj = QuantumCircuit(nspins+1) circ_adj.ry(gamma, qubit=-1) ### R_gamma circ_adj.x(qubit=-1) ### X ### U ### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) ) ### control-Q ; Ancillary - n target for (q,o) in enumerate(Q): if o==1: circ_adj.cx(-1, q) if o==2: circ_adj.cy(-1, q) if o==3: circ_adj.cz(-1, q) ### U^ circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse()) ### control-P_{0 j_ref} circ_adj.x(qubit=nspins) J1 = list(getBinary(j_ref, nspins)) + [0] for (q,o) in enumerate(J1): if o==1: circ_adj.cx(nspins, q) circ_adj.x(nspins) ### H on ancillary circ_adj.h(nspins) return circ_adj
https://github.com/WhenTheyCry96/qiskitHackathon2022
WhenTheyCry96
import warnings warnings.filterwarnings('ignore') from qiskit_metal import designs, MetalGUI design = designs.DesignPlanar() design.overwrite_enabled = True design.chips.main.size_x = '12mm' design.chips.main.size_y = '10mm' gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL design.delete_all_components() design_span_x = 5 design_span_y = 3 half_chip_width = design_span_x / 2 half_chip_height = design_span_y / 2 connection_pads_options = dict( a = dict(loc_W=1, loc_H=-1), b = dict(loc_W=1, loc_H=1), c = dict(loc_W=-1, loc_H=-1) ) connection23_pads_options = dict( a = dict(loc_W=1, loc_H=-1), c = dict(loc_W=-1, loc_H=-1) ) transmons = [] transmons.append(TransmonPocketCL(design, 'Q1', options=dict(pos_x=f'-{half_chip_width}mm', pos_y=f'{-half_chip_height}mm', connection_pads=dict(**connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q2', options=dict(pos_x=f'0mm', pos_y=f'{half_chip_height}mm', orientation=-90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q3', options=dict(pos_x=f'0mm', pos_y=f'{-half_chip_height}mm', orientation=90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q4', options=dict(pos_x=f'{half_chip_width}mm', pos_y=f'{half_chip_height}mm', orientation=180, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal import Dict fillet='99.99um' options = Dict( meander=Dict( lead_start='0.1mm', lead_end='0.1mm', asymmetry='0 um') ) def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str, length: str, asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False): """Connect two pins with a CPW.""" myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component=component1, pin=pin1), end_pin=Dict( component=component2, pin=pin2)), lead=Dict( start_straight=start_strght, end_straight=end_strght ), total_length=length, fillet = '99.9um') myoptions.update(options) myoptions.meander.asymmetry = asymmetry myoptions.meander.lead_direction_inverted = 'true' if flip else 'false' return RouteMeander(design, component_name, myoptions) asym_h = 100 asym_v = 100 cpw = [] cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled readouts_lwc = [] control_lwc = [] offset_x = 0 offset_y = 1 #Readouts readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1', options = dict( pos_x = '-5mm', pos_y = f'-{half_chip_height+offset_y}mm', lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2', options = dict( pos_x = '-1mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3', options = dict( pos_x = '1mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4', options = dict( pos_x = '5mm', pos_y = f'{half_chip_height+offset_y}mm', orientation = 180, lead_length = '30um'))) #Controls control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1', options = dict( pos_x = '-5mm', pos_y = '2mm', lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2', options = dict( pos_x = '4mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3', options = dict( pos_x = '-4mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4', options = dict( pos_x = '5mm', pos_y = '-2mm', orientation = 180, lead_length = '30um'))) gui.rebuild() gui.autoscale() readout_lines = [] asym_14 = 700 asym_23 = 700 options = Dict( lead=Dict( start_straight='330um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um')) options = Dict( lead=Dict( start_straight='430um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um')) gui.rebuild() gui.autoscale() from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from collections import OrderedDict import numpy as np control_lines = [] def connectRouteAnchor(name: str, component1: str, pin1: str, component2: str, pin2: str, anchor_points: OrderedDict) -> RouteAnchors: options_line_cl = dict( pin_inputs = dict(start_pin = dict(component = component1, pin = pin1), end_pin = dict(component = component2, pin = pin2)), anchors = anchor_points, lead = dict(start_straight = '200um', end_straight = '225um'), fillet = fillet ) return RouteAnchors(design, name, options_line_cl) anchors1c = OrderedDict() anchors1c[0] = np.array([-4, -1.42]) anchors1c[1] = np.array([-4, 2]) control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c)) anchors2c = OrderedDict() anchors2c[0] = np.array([0.08, 3.25]) anchors2c[1] = np.array([4, 3.25]) control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c)) anchors3c = OrderedDict() anchors3c[0] = np.array([-0.08, -3.25]) anchors3c[1] = np.array([-4, -3.25]) control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c)) anchors4c = OrderedDict() anchors4c[0] = np.array([4, 1.42]) anchors4c[1] = np.array([4, -2]) control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c)) gui.rebuild() gui.autoscale() gui.autoscale() gui.screenshot(name="full_design") import numpy as np from scipy.constants import c, h, pi, hbar, e from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength # constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) find_resonator_length(np.around(np.linspace(8, 9.2, 4), 2), 10, 6, 2) transmons[0].options.pad_gap = '40um' transmons[0].options.pad_width = '550um' # 405 transmons[0].options.pad_height = '120um' transmons[1].options.pad_gap = '40um' transmons[1].options.pad_width = '500um' # 405 transmons[1].options.pad_height = '120um' transmons[2].options.pad_gap = '40um' transmons[2].options.pad_width = '460um' # 405 transmons[2].options.pad_height = '120um' transmons[3].options.pad_gap = '40um' transmons[3].options.pad_width = '440um' # 405 transmons[3].options.pad_height = '120um' readout_lines[0].options.total_length = '8.06mm' readout_lines[1].options.total_length = '8.42mm' readout_lines[2].options.total_length = '8.24mm' readout_lines[3].options.total_length = '8.06mm' cpw[0].options.total_length = '7.6mm' cpw[1].options.total_length = '7.2mm' cpw[2].options.total_length = '6.9mm' cpw[3].options.total_length = '6.6mm' gui.rebuild() gui.autoscale() qcomps = design.components # short handle (alias) qcomps['Q1'].options['hfss_inductance'] = 'Lj1' qcomps['Q1'].options['hfss_capacitance'] = 'Cj1' qcomps['Q2'].options['hfss_inductance'] = 'Lj2' qcomps['Q2'].options['hfss_capacitance'] = 'Cj2' qcomps['Q3'].options['hfss_inductance'] = 'Lj3' qcomps['Q3'].options['hfss_capacitance'] = 'Cj3' qcomps['Q4'].options['hfss_inductance'] = 'Lj4' qcomps['Q4'].options['hfss_capacitance'] = 'Cj4' from qiskit_metal.analyses.quantization import EPRanalysis eig_qb = EPRanalysis(design, "hfss") eig_qb.sim.setup.n_modes = 2 eig_qb.sim.run(name="Qbit", components=['Q1', 'R1', 'ol1'], open_terminations=[], box_plus_buffer = True) eig_qb.sim.plot_convergences() eig_qb.setup.junctions.jj.rect = 'JJ_rect_Lj_Q1_rect_jj' eig_qb.setup.junctions.jj.line = 'JJ_Lj_Q1_rect_jj_' eig_qb.setup eig_qb.run_epr() transmons[1].options.pad_gap = '40um' transmons[1].options.pad_width = '500um' # 405 transmons[1].options.pad_height = '120um' gui.rebuild() eig_qb = EPRanalysis(design, "hfss") eig_qb.sim.setup.n_modes = 2 eig_qb.sim.run(name="Qbit2", components=['Q2'], open_terminations=[], box_plus_buffer = False) eig_qb.sim.plot_convergences() transmons[2].options.pad_gap = '40um' transmons[2].options.pad_width = '460um' # 405 transmons[2].options.pad_height = '120um' gui.rebuild() eig_qb = EPRanalysis(design, "hfss") eig_qb.sim.setup.n_modes = 2 eig_qb.sim.run(name="Qbit3", components=['Q3'], open_terminations=[], box_plus_buffer = False) eig_qb.sim.plot_convergences() transmons[3].options.pad_gap = '40um' transmons[3].options.pad_width = '440um' # 405 transmons[3].options.pad_height = '120um' gui.rebuild() eig_qb = EPRanalysis(design, "hfss") eig_qb.sim.setup.n_modes = 2 eig_qb.sim.run(name="Qbit4", components=['Q4'], open_terminations=[], box_plus_buffer = False) eig_qb.sim.plot_convergences() from qiskit_metal.analyses.quantization import EPRanalysis eig_rd = EPRanalysis(design, "hfss") readout_lines[0].options.total_length = '11.7mm' gui.rebuild() eig_rd.sim.setup.n_modes = 2 eig_rd.sim.setup.max_passes = 10 eig_rd.sim.run(name="Readout", components=['R1','ol1']) eig_rd.sim.plot_convergences() from qiskit_metal.analyses.quantization import EPRanalysis eig_rd = EPRanalysis(design, "hfss") readout_lines[1].options.total_length = '11.2mm' gui.rebuild() eig_rd.sim.setup.n_modes = 2 eig_rd.sim.setup.max_passes = 10 eig_rd.sim.run(name="Readout", components=['R2','ol2']) eig_rd.sim.plot_convergences() from qiskit_metal.analyses.quantization import EPRanalysis eig_rd = EPRanalysis(design, "hfss") readout_lines[2].options.total_length = '10.6mm' gui.rebuild() eig_rd.sim.setup.n_modes = 2 eig_rd.sim.setup.max_passes = 10 eig_rd.sim.run(name="Readout", components=['R3','ol3']) eig_rd.sim.plot_convergences() from qiskit_metal.analyses.quantization import EPRanalysis eig_rd = EPRanalysis(design, "hfss") readout_lines[3].options.total_length = '10mm' gui.rebuild() eig_rd.sim.setup.n_modes = 2 eig_rd.sim.setup.max_passes = 10 eig_rd.sim.run(name="Readout", components=['R4','ol4']) eig_rd.sim.plot_convergences() from qiskit_metal.analyses.quantization import EPRanalysis eig_c = EPRanalysis(design, "hfss") cpw[0].options.total_length = '10mm' gui.rebuild() eig_c.sim.setup.n_modes = 2 eig_c.sim.setup.passes = 10 eig_c.sim.run(name="CPW1", components=['cpw1']) eig_c.sim.plot_convergences() from qiskit_metal.analyses.quantization import EPRanalysis eig_c = EPRanalysis(design, "hfss") cpw[1].options.total_length = '9.6mm' gui.rebuild() eig_c.sim.setup.n_modes = 2 eig_c.sim.setup.passes = 10 eig_c.sim.run(name="CPW2", components=['cpw3']) eig_c.sim.plot_convergences() from qiskit_metal.analyses.quantization import EPRanalysis eig_c = EPRanalysis(design, "hfss") cpw[2].options.total_length = '9.3mm' gui.rebuild() eig_c.sim.setup.n_modes = 2 eig_c.sim.setup.passes = 10 eig_c.sim.run(name="CPW4", components=['cpw4']) eig_c.sim.plot_convergences() from qiskit_metal.analyses.quantization import EPRanalysis eig_c = EPRanalysis(design, "hfss") cpw[3].options.total_length = '9mm' gui.rebuild() eig_c.sim.setup.n_modes = 2 eig_c.sim.setup.passes = 10 eig_c.sim.run(name="CPW5", components=['cpw5']) eig_c.sim.plot_convergences()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) dag_drawer(dag)
https://github.com/khaledalam/QuantumComputingAndPrimesAndOthers
khaledalam
# Author: Khaled Alam(khaledalam.net@gmail.com) ''' Guess binary string (secret) of length N in 1 shot only using quantum computing circuit! ~ by using clasical computers we need at least N shots to guess string (secret) of length N ~ by using quantum computer we need 1 shot to guess string (secret) of ANY length ( cool isn't it! ^^ ) ''' secret = '01000001' # `01000001` = `A` from qiskit import * n = len(secret) qCircuit = QuantumCircuit(n+1, n) # n+1 qubits and n classical bits qCircuit.x(n) qCircuit.barrier() qCircuit.h(range(n+1)) qCircuit.barrier() for ii, OZ in enumerate(reversed(secret)): if OZ == '1': qCircuit.cx(ii, n) qCircuit.barrier() qCircuit.h(range(n+1)) qCircuit.barrier() qCircuit.measure(range(n), range(n)) %matplotlib inline qCircuit.draw(output='mpl') # run on simulator simulator = Aer.get_backend('qasm_simulator') result = execute(qCircuit, backend=simulator, shots=1).result() # only 1 shot from qiskit.visualization import plot_histogram plot_histogram( result.get_counts(qCircuit) )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the DenseLayout pass""" import unittest import numpy as np from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.circuit import Parameter, Qubit from qiskit.circuit.library import CXGate, UGate, ECRGate, RZGate from qiskit.transpiler import CouplingMap, Target, InstructionProperties, TranspilerError from qiskit.transpiler.passes import DenseLayout from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeTokyo from qiskit.transpiler.passes.layout.dense_layout import _build_error_matrix class TestDenseLayout(QiskitTestCase): """Tests the DenseLayout pass""" def setUp(self): super().setUp() self.cmap20 = FakeTokyo().configuration().coupling_map self.target_19 = Target() rng = np.random.default_rng(12345) instruction_props = { edge: InstructionProperties( duration=rng.uniform(1e-7, 1e-6), error=rng.uniform(1e-4, 1e-3) ) for edge in CouplingMap.from_heavy_hex(3).get_edges() } self.target_19.add_instruction(CXGate(), instruction_props) def test_5q_circuit_20q_coupling(self): """Test finds dense 5q corner in 20q coupling map.""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[3], qr[1]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_ = DenseLayout(CouplingMap(self.cmap20)) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 11) self.assertEqual(layout[qr[1]], 10) self.assertEqual(layout[qr[2]], 6) self.assertEqual(layout[qr[3]], 5) self.assertEqual(layout[qr[4]], 0) def test_6q_circuit_20q_coupling(self): """Test finds dense 5q corner in 20q coupling map.""" qr0 = QuantumRegister(3, "q0") qr1 = QuantumRegister(3, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr0[0], qr1[2]) circuit.cx(qr1[1], qr0[2]) dag = circuit_to_dag(circuit) pass_ = DenseLayout(CouplingMap(self.cmap20)) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr0[0]], 11) self.assertEqual(layout[qr0[1]], 10) self.assertEqual(layout[qr0[2]], 6) self.assertEqual(layout[qr1[0]], 5) self.assertEqual(layout[qr1[1]], 1) self.assertEqual(layout[qr1[2]], 0) def test_5q_circuit_19q_target_with_noise(self): """Test layout works finds a dense 5q subgraph in a 19q heavy hex target.""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[3], qr[1]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_ = DenseLayout(target=self.target_19) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 9) self.assertEqual(layout[qr[1]], 3) self.assertEqual(layout[qr[2]], 11) self.assertEqual(layout[qr[3]], 15) self.assertEqual(layout[qr[4]], 4) def test_5q_circuit_19q_target_without_noise(self): """Test layout works finds a dense 5q subgraph in a 19q heavy hex target with no noise.""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[3], qr[1]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) instruction_props = {edge: None for edge in CouplingMap.from_heavy_hex(3).get_edges()} noiseless_target = Target() noiseless_target.add_instruction(CXGate(), instruction_props) pass_ = DenseLayout(target=noiseless_target) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 1) self.assertEqual(layout[qr[1]], 13) self.assertEqual(layout[qr[2]], 0) self.assertEqual(layout[qr[3]], 9) self.assertEqual(layout[qr[4]], 3) def test_ideal_target_no_coupling(self): """Test pass fails as expected if a target without edge constraints exists.""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[3], qr[1]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) target = Target(num_qubits=19) target.add_instruction(CXGate()) layout_pass = DenseLayout(target=target) with self.assertRaises(TranspilerError): layout_pass.run(dag) def test_target_too_small_for_circuit(self): """Test error is raised when target is too small for circuit.""" target = Target() target.add_instruction( CXGate(), {edge: None for edge in CouplingMap.from_line(3).get_edges()} ) dag = circuit_to_dag(QuantumCircuit(5)) layout_pass = DenseLayout(target=target) with self.assertRaises(TranspilerError): layout_pass.run(dag) def test_19q_target_with_noise_error_matrix(self): """Test the error matrix construction works for a just cx target.""" expected_error_mat = np.zeros((19, 19)) for qargs, props in self.target_19["cx"].items(): error = props.error expected_error_mat[qargs[0]][qargs[1]] = error error_mat = _build_error_matrix( self.target_19.num_qubits, {i: i for i in range(self.target_19.num_qubits)}, target=self.target_19, )[0] np.testing.assert_array_equal(expected_error_mat, error_mat) def test_multiple_gate_error_matrix(self): """Test error matrix ona small target with multiple gets on each qubit generates""" target = Target(num_qubits=3) phi = Parameter("phi") lam = Parameter("lam") theta = Parameter("theta") target.add_instruction( RZGate(phi), {(i,): InstructionProperties(duration=0, error=0) for i in range(3)} ) target.add_instruction( UGate(theta, phi, lam), {(i,): InstructionProperties(duration=1e-7, error=1e-2) for i in range(3)}, ) cx_props = { (0, 1): InstructionProperties(error=1e-3), (0, 2): InstructionProperties(error=1e-3), (1, 0): InstructionProperties(error=1e-3), (1, 2): InstructionProperties(error=1e-3), (2, 0): InstructionProperties(error=1e-3), (2, 1): InstructionProperties(error=1e-3), } target.add_instruction(CXGate(), cx_props) ecr_props = { (0, 1): InstructionProperties(error=2e-2), (1, 2): InstructionProperties(error=2e-2), (2, 0): InstructionProperties(error=2e-2), } target.add_instruction(ECRGate(), ecr_props) expected_error_matrix = np.array( [ [1e-2, 2e-2, 1e-3], [1e-3, 1e-2, 2e-2], [2e-2, 1e-3, 1e-2], ] ) error_mat = _build_error_matrix( target.num_qubits, {i: i for i in range(target.num_qubits)}, target=target )[0] np.testing.assert_array_equal(expected_error_matrix, error_mat) def test_5q_circuit_20q_with_if_else(self): """Test layout works finds a dense 5q subgraph in a 19q heavy hex target.""" qr = QuantumRegister(5, "q") cr = ClassicalRegister(5) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr, cr) false_body = QuantumCircuit(qr, cr) true_body.cx(qr[0], qr[3]) true_body.cx(qr[3], qr[4]) false_body.cx(qr[3], qr[1]) false_body.cx(qr[0], qr[2]) circuit.if_else((cr, 0), true_body, false_body, qr, cr) circuit.cx(0, 4) dag = circuit_to_dag(circuit) pass_ = DenseLayout(CouplingMap(self.cmap20)) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[qr[0]], 11) self.assertEqual(layout[qr[1]], 10) self.assertEqual(layout[qr[2]], 6) self.assertEqual(layout[qr[3]], 5) self.assertEqual(layout[qr[4]], 0) def test_loose_bit_circuit(self): """Test dense layout works with loose bits outside a register.""" bits = [Qubit() for _ in range(5)] circuit = QuantumCircuit() circuit.add_bits(bits) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) dag = circuit_to_dag(circuit) pass_ = DenseLayout(CouplingMap(self.cmap20)) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual(layout[bits[0]], 11) self.assertEqual(layout[bits[1]], 10) self.assertEqual(layout[bits[2]], 6) self.assertEqual(layout[bits[3]], 5) self.assertEqual(layout[bits[4]], 0) if __name__ == "__main__": unittest.main()