repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
from qiskit import QuantumRegister, QuantumCircuit # Quantum register q = QuantumRegister(2, name='q') # Quantum circuit bell = QuantumCircuit(q) # Create a Bell state bell.x(q[0]) bell.x(q[1]) bell.h(q[0]) bell.cx(q[0], q[1]) # Draw circuit bell.draw(output = 'mpl') # Quantum register q = QuantumRegister(2, name='q') # Quantum circuit entangled = QuantumCircuit(q) # Entangled state entangled.h(q[0]) entangled.s(q[0]) entangled.cx(q[0], q[1]) entangled.h(q[0]) # Draw circuit entangled.draw(output='mpl') # Quantum register q = QuantumRegister(2, name='q') # Quantum circuit channel = QuantumCircuit(q) # CNOT gate channel.cx(q[0], q[1]) # Draw circuit channel.draw(output='mpl') # Quantum register q = QuantumRegister(2, name='q') # Quantum circuit channel = QuantumCircuit(q) # CNOT gate channel.h(q[1]) channel.cz(q[0], q[1]) channel.cx(q[1], q[0]) # Draw circuit channel.draw(output='mpl') from qiskit import IBMQ, execute from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.tools.visualization import plot_histogram, plot_state_city IBMQ.load_account() backend = IBMQ.get_provider().get_backend('ibmqx2') # qiskit-ignis provides tools for noise mitigation from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter, MeasurementFilter # For visualizing the circuits import matplotlib.pyplot as plt # Suppose we have a 5-qubit quantum computer, and we want to perform measurements on qubits 0 and 2 # We first initialize a 5-qubit quantum register q = QuantumRegister(5) # Next, we generate the calibration circuits meas_calibs, state_labels = complete_meas_cal(qubit_list=[0,2], qr=q) # We can plot them fig, axes = plt.subplots(1, 4) for i, circuit in enumerate(meas_calibs): circuit.draw(output='mpl', ax=axes[i], scale=2) print("State labels:",state_labels) # We now perform the calibration on the real device job_calibration = execute(meas_calibs, backend=backend) cal_results = job_calibration.result() # We now calculate the calibration matrix from the outcomes meas_fitter = CompleteMeasFitter(cal_results, state_labels) meas_fitter.plot_calibration() # What is the measurement fidelity? print("Average Measurement Fidelity: %f" % meas_fitter.readout_fidelity()) # Make a 2Q Bell state between Q0 and Q2 c = ClassicalRegister(2) bell = QuantumCircuit(q) bell.x(q[0]) bell.x(q[2]) bell.h(q[0]) bell.cx(q[0], q[2]) meas = QuantumCircuit(q, c) meas.measure(q[0],c[0]) meas.measure(q[2],c[1]) qc = bell + meas qc.draw(output='mpl') # We execute the circuit job = execute(qc, backend=backend, shots=5000) results = job.result() # We also simulate the circuit in a noiseless case from qiskit import Aer simjob = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=10000) simresults = simjob.result() # We get the raw counts raw_counts = results.get_counts() sim_counts = simresults.get_counts() # ... and the mitigated counts # First we need to get the measurement filter object meas_filter = meas_fitter.filter # and then we apply it to the results mitigated_results = meas_filter.apply(results) mitigated_counts = mitigated_results.get_counts(0) plot_histogram([sim_counts, raw_counts, mitigated_counts], legend=['simulated', 'raw', 'mitigated']) # We import the required classes from ignis. from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.tools.qi.qi import partial_trace job_state_vec = execute(bell, Aer.get_backend('statevector_simulator')) state_vec = partial_trace(job_state_vec.result().get_statevector(), [1, 3, 4]) plot_state_city(state_vec) # We construct all the tomographic circuits qst = state_tomography_circuits(bell, [q[0], q[2]]) # We can plot them fig, axes = plt.subplots(3, 3) for i, circuit in enumerate(qst): row = i // 3 col = i % 3 circuit.draw(output='mpl', ax=axes[row, col], scale=2) # We execute the tomography circuits on the real device job = execute(qst, backend=backend) # We create a StateTomographyFitter from the job result and the tomography circuit tomo_fitter = StateTomographyFitter(job.result(), qst) # To obtain the rho_tomo = tomo_fitter.fit() plot_state_city(rho_tomo) plot_state_city(state_vec) # Import the state_fidelity function from qiskit.quantum_info import state_fidelity # Exercise code: # ... # ...
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
# imports import numpy as np from qiskit import QuantumRegister, QuantumCircuit #################################### # Depolarizing channel on IBMQX2 # #################################### # Quantum register q = QuantumRegister(4, name="q") # Quantum circuit depolarizing = QuantumCircuit(q) # Depolarizing channel acting on q_2 ## Qubit identification system = 0 a_0 = 1 a_1 = 2 a_2 = 3 ## Define rotation angle theta = 0.0 ## Construct circuit depolarizing.ry(theta, q[a_0]) depolarizing.ry(theta, q[a_1]) depolarizing.ry(theta, q[a_2]) depolarizing.cx(q[a_0], q[system]) depolarizing.cy(q[a_1], q[system]) depolarizing.cz(q[a_2], q[system]) # Draw circuit depolarizing.draw(output='mpl') def depolarizing_channel(q, p, system, ancillae): """Returns a QuantumCircuit implementing depolarizing channel on q[system] Args: q (QuantumRegister): the register to use for the circuit p (float): the probability for the channel between 0 and 1 system (int): index of the system qubit ancillae (list): list of indices for the ancillary qubits Returns: A QuantumCircuit object """ # Write the code here... # Let's fix the quantum register and the qubit assignments # We create the quantum circuit q = QuantumRegister(5, name='q') # Index of the system qubit system = 2 # Indices of the ancillary qubits ancillae = [1, 3, 4] # For example, let's consider 10 equally spaced values of p p_values = np.linspace(0, 1, 10)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
# Imports import numpy as np from qiskit import QuantumRegister, QuantumCircuit, Aer, execute from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter import matplotlib.pyplot as plt from qiskit.quantum_info import partial_trace from qiskit.quantum_info.states import DensityMatrix def depolarizing_channel(q, p, system, ancillae): """Returns a QuantumCircuit implementing depolarizing channel on q[system] Args: q (QuantumRegister): the register to use for the circuit p (float): the probability for the channel between 0 and 1 system (int): index of the system qubit ancillae (list): list of indices for the ancillary qubits Returns: A QuantumCircuit object """ dc = QuantumCircuit(q) # theta = 1/2 * np.arccos(1-2*p) # dc.ry(theta, q[ancillae[0]]) dc.ry(theta, q[ancillae[1]]) dc.ry(theta, q[ancillae[2]]) dc.cx(q[ancillae[0]], q[system]) dc.cy(q[ancillae[1]], q[system]) dc.cz(q[ancillae[2]], q[system]) return dc # We create the quantum circuit q = QuantumRegister(5, name='q') # Index of the system qubit system = 2 # Indices of the ancillary qubits ancillae = [1, 3, 4] # Prepare the qubit in a state that has coherence and different populations prepare_state = QuantumCircuit(q) prepare_state.u(np.pi/4, np.pi/4, 0, q[system]) # For example, let's consider 10 equally spaced values of p p_values = np.linspace(0, 1, 10) # Here we will create a list of results for each different value of p tomography_circuits = [] for p in p_values: circ = prepare_state + depolarizing_channel(q, p, system, ancillae) tomography_circuits.append(state_tomography_circuits(circ, q[system])) tomography_results = [] for tomo_circ in tomography_circuits: job = execute(tomo_circ, Aer.get_backend('qasm_simulator'), shots=8192) tomography_results.append(job.result()) tomo_rhos = np.zeros((2,2,len(p_values)), dtype=complex) for (i, p) in enumerate(p_values): tomo_fitter = StateTomographyFitter(tomography_results[i], tomography_circuits[i]) tomo_rhos[:,:,i] = tomo_fitter.fit() # Simulated results plt.plot(p_values, np.real(tomo_rhos[0,1,:]),"C0*", label='Re $\\rho_{01}$') plt.plot(p_values, np.imag(tomo_rhos[0,1,:]),"C1*", label='Im $\\rho_{01}$') plt.plot(p_values, np.real(tomo_rhos[0,0,:]),"C2x", label='$\\rho_{00}$') plt.plot(p_values, np.real(tomo_rhos[1,1,:]),"C3x", label='$\\rho_{11}$') # Theoretical prediction # We obtain the density operator of the initial state rho0 = partial_trace(DensityMatrix.from_instruction(prepare_state), [0, 1, 3, 4]).data plt.plot(p_values, np.real(rho0[0,1])*(1-p_values), "C0", linewidth=.5) plt.plot(p_values, np.imag(rho0[0,1])*(1-p_values), "C1", linewidth=.5) plt.plot(p_values, 0.5*p_values + np.real(rho0[0,0])*(1-p_values), "C2", linewidth=.5) plt.plot(p_values, 0.5*p_values + np.real(rho0[1,1])*(1-p_values), "C3", linewidth=.5) plt.xlabel('p') plt.ylabel('$\\rho_{xx}$') plt.legend(); plt.title("SIMULATION Depol. channel. Full tomo. $|\\psi_0\\rangle = U_3(\\pi/4,\\pi/4,0)|0\\rangle$");
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import Parameter ############################# # Pauli channel on IBMQX2 # ############################# # Quantum register q = QuantumRegister(3, name="q") # Quantum circuit pauli = QuantumCircuit(q) # Pauli channel acting on q_2 ## Qubit identification system = 0 a_0 = 1 a_1 = 2 # ## Define rotation angles theta_1 = Parameter('θ1') theta_2 = Parameter('θ2') theta_3 = Parameter('θ3') ## Construct circuit pauli.ry(theta_1, q[a_0]) pauli.cx(q[a_0], q[a_1]) pauli.ry(theta_2, q[a_0]) pauli.ry(theta_3, q[a_1]) pauli.cx(q[a_0], q[system]) pauli.cy(q[a_1], q[system]) # Draw circuit pauli.draw(output='mpl') def pauli_channel(q, p, system, pauli_ancillae): """ Apply the Pauli channel to system with probabilities p Args: q (QuantumRegister): the quantum register for the circuit system (int): index of the system qubit pauli_ancillae (list): list of indices of the ancillary qubits p (list): list of probabilities [p_1, p_2, p_3] for the Pauli channel Returns: A QuantumCircuit implementing the Pauli channel """ # Write code # Suggested imports... from qiskit.tools.qi.qi import entropy, partial_trace def conditional_entropy(state, qubit_a, qubit_b): """Conditional entropy S(A|B) = S(AB) - S(B) Args: state: a vector or density operator qubit_a: 0-based index of the qubit A qubit_b: 0-based index of the qubit B Returns: int: the conditional entropy """ # Write code here def extractable_work(state, system_qubit, memory_qubit): """Extractable work from a two-qubit state = Cfr. Eq. (4) Bylicka et al., Sci. Rep. 6, 27989 (2016) Args: qubit_a: 0-based index of the system qubit S qubit_b: 0-based index of the memory qubit M """ # Write code here
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np from scipy.optimize import fsolve, differential_evolution # Main qiskit imports from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ # Tomography from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.ignis.verification.tomography import StateTomographyFitter # Plots import matplotlib.pyplot as plt # We have an analytical solution of the system of equations def theta_from_p(p): """ Returns the angles [theta_1, theta_2, theta_3] that implement the Pauli channel with probabilities p = [p_1, p_2, p_3]""" p = np.asarray(p, dtype=complex) c = [np.sqrt(1 - np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))))/np.sqrt(2), np.sqrt(8*p[0]**3 - 4*p[0]**2*(-1 - 6*p[2] + np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))))) + (1 - 2*p[2])**2*(-1 + 2*p[2] + np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))))) - 2*p[0]*(1 + 4*(p[2] - 3*p[2]**2 - p[2]*np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))) + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))*np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))))))/ (np.sqrt(2)*np.sqrt((-1 + 2*p[0] + 2*p[2])*(4*p[0]**2 + (1 - 2*p[2])**2 + p[0]*(4 + 8*p[2])))), np.sqrt((8*p[0]**3 - 4*p[0]**2*(-1 - 6*p[2] + np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))))) + (1 - 2*p[2])**2*(-1 + 2*p[2] + np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))))) - 2*p[0]*(1 + 4*(p[2] - 3*p[2]**2 - p[2]*np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))) + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))*np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))))))/ (4*p[0]**2 + (1 - 2*p[2])**2 + p[0]*(4 + 8*p[2])))/np.sqrt(-2 + 4*p[0] + 4*p[2])] theta = 2*np.arccos(np.real(c)) return theta def pauli_channel(q, p, system, pauli_ancillae): """ Apply the Pauli channel to system with probabilities p Args: q (QuantumRegister): the quantum register for the circuit system (int): index of the system qubit pauli_ancillae (list): list of indices of the ancillary qubits p (list): list of probabilities [p_1, p_2, p_3] for the Pauli channel Returns: A QuantumCircuit implementing the Pauli channel """ theta = theta_from_p(p) dc = QuantumCircuit(q) dc.ry(theta[0], q[pauli_ancillae[0]]) dc.cx(q[pauli_ancillae[0]], q[pauli_ancillae[1]]) dc.ry(theta[1], q[pauli_ancillae[0]]) dc.ry(theta[2], q[pauli_ancillae[1]]) dc.cx(q[pauli_ancillae[0]], q[system]) dc.cy(q[pauli_ancillae[1]], q[system]) return dc from qiskit.quantum_info import entropy, partial_trace def conditional_entropy(state, qubit_a, qubit_b): """Conditional entropy S(A|B) = S(AB) - S(B) Args: state: a vector or density operator qubit_a: 0-based index of the qubit A qubit_b: 0-based index of the qubit B Returns: int: the conditional entropy """ return entropy(state) - entropy(partial_trace(state, [qubit_b])) def extractable_work(state, system_qubit, memory_qubit, n=1): """Extractable work from a two-qubit state = Cfr. Eq. (3-4) Bylicka et al., Sci. Rep. 6, 27989 (2016) Args: qubit_a: 0-based index of the system qubit S qubit_b: 0-based index of the memory qubit M """ return (n - conditional_entropy(state, system_qubit, memory_qubit)/np.log(2)) def p_enm(t, eta=1., omega=1.): p = [1/4 * (1 - np.exp(-2 * t *eta)), 1/4 * (1 - np.exp(-2 * t *eta)), 1/4 * (1 + np.exp(-2 * t * eta) - 2 *np.exp(-t *eta) * np.cosh(t *omega))] return p def p_ncp(t, eta=1., omega=1.): p = [1/4 * (1 - np.exp(-2 * t *eta)), 1/4 * (1 - np.exp(-2 * t *eta)), 1/4 * (1 + np.exp(-2 * t * eta) - 2 *np.exp(-t *eta) * np.cos(t *omega))] return p # Here are the parameters t_values = np.linspace(0, 3, 11) # Parameters params_ncp = {'eta': 0.1, 'omega': 2.0} params_enm = {'eta': 1.0, 'omega': .5} # And the qubit assignments SHOTS = 8192 q = QuantumRegister(5, name='q') c = ClassicalRegister(2, name='c') system = 2 ancilla = 4 pauli_ancillae = [0, 1] # Prepare the two qubits 0 and 2 in a psi- state prepare_two_qubit = QuantumCircuit(q) prepare_two_qubit.x(q[ancilla]) prepare_two_qubit.x(q[system]) prepare_two_qubit.h(q[ancilla]) prepare_two_qubit.cx(q[ancilla], q[system]) prepare_two_qubit.barrier() wext_ncp = [] for t in t_values: circ = prepare_two_qubit + pauli_channel(q, p_ncp(t, **params_ncp), system, pauli_ancillae) tomo_circuits_ncp = state_tomography_circuits(circ, [q[ancilla], q[system]]) job = execute(tomo_circuits_ncp, Aer.get_backend('qasm_simulator'), shots=SHOTS) result = job.result() tomo_fitter = StateTomographyFitter(result, tomo_circuits_ncp) rho = tomo_fitter.fit() wext_ncp.append(extractable_work(rho, 1, 0)) wext_enm = [] for t in t_values: circ = prepare_two_qubit + pauli_channel(q, p_enm(t, **params_enm), system, pauli_ancillae) tomo_circuits_enm = state_tomography_circuits(circ, [q[ancilla], q[system]]) job = execute(tomo_circuits_enm, Aer.get_backend('qasm_simulator'), shots=SHOTS) result = job.result() tomo_fitter = StateTomographyFitter(result, tomo_circuits_enm) rho = tomo_fitter.fit() wext_enm.append(extractable_work(rho, 1, 0)) plt.plot(t_values, wext_ncp, 'x', label='Non CP-div.') plt.plot(t_values, wext_enm, 'x', label='Et. Non-M') plt.legend() plt.xlabel('t') plt.ylabel('$W_{ex}$');
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
from qiskit import QuantumRegister, QuantumCircuit import numpy as np ####################### # ZZ pump on IBMQX2 # ####################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit zz = QuantumCircuit(q) # ZZ pump acting on system qubits ## Qubit identification system = [2, 1] a_zz = 0 ## Define pump efficiency ## and corresponding rotation p = 0.5 theta = 2 * np.arcsin(np.sqrt(p)) ## Construct circuit ### Map information to ancilla zz.cx(q[system[0]], q[system[1]]) zz.x(q[a_zz]) zz.cx(q[system[1]], q[a_zz]) ### Conditional rotation zz.cu3(theta, 0.0, 0.0, q[a_zz], q[system[1]]) ### Inverse mapping zz.cx(q[system[1]], q[a_zz]) zz.cx(q[system[0]], q[system[1]]) # Draw circuit zz.draw(output='mpl') ####################### # XX pump on IBMQX2 # ####################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit xx = QuantumCircuit(q) # XX pump acting on system qubits ## Qubit identification system = [2, 1] a_xx = 4 ## Define pump efficiency ## and corresponding rotation p = 0.5 theta = 2 * np.arcsin(np.sqrt(p)) ## Construct circuit ### Map information to ancilla xx.cx(q[system[0]], q[system[1]]) xx.h(q[system[0]]) xx.x(q[a_xx]) xx.cx(q[system[0]], q[a_xx]) ### Conditional rotation xx.cu3(theta, 0.0, 0.0, q[a_xx], q[system[0]]) ### Inverse mapping xx.cx(q[system[0]], q[a_xx]) xx.h(q[system[0]]) xx.cx(q[system[0]], q[system[1]]) # Draw circuit xx.draw(output='mpl') ########################### # ZZ-XX pumps on IBMQX2 # ########################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit zz_xx = QuantumCircuit(q) # ZZ and XX pumps acting on system qubits ## Qubit identification system = [2, 1] a_zz = 0 a_xx = 4 ## Define pump efficiency ## and corresponding rotation p = 0.5 theta = 2 * np.arcsin(np.sqrt(p)) ## Construct circuit ## ZZ pump ### Map information to ancilla zz_xx.cx(q[system[0]], q[system[1]]) zz_xx.x(q[a_zz]) zz_xx.cx(q[system[1]], q[a_zz]) ### Conditional rotation zz_xx.cu3(theta, 0.0, 0.0, q[a_zz], q[system[1]]) ### Inverse mapping zz_xx.cx(q[system[1]], q[a_zz]) #zz_xx.cx(q[system[0]], q[system[1]]) ## XX pump ### Map information to ancilla #zz_xx.cx(q[system[0]], q[system[1]]) zz_xx.h(q[system[0]]) zz_xx.x(q[a_xx]) zz_xx.cx(q[system[0]], q[a_xx]) ### Conditional rotation zz_xx.cu3(theta, 0.0, 0.0, q[a_xx], q[system[0]]) ### Inverse mapping zz_xx.cx(q[system[0]], q[a_xx]) zz_xx.h(q[system[0]]) zz_xx.cx(q[system[0]], q[system[1]]) # Draw circuit zz_xx.draw(output='mpl') def zz_pump(q, c, p, system, ancilla): """Returns a QuantumCircuit implementing the ZZ pump channel on the system qubits Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system qubits p (float): the efficiency for the channel, between 0 and 1 system (list): list of indices for the system qubits ancilla (int): index for the ancillary qubit Returns: A QuantumCircuit object """ def xx_pump(q, c, p, system, ancilla): """Returns a QuantumCircuit implementing the XX pump channel on the system qubits Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system qubits p (float): the efficiency for the channel, between 0 and 1 system (list): list of indices for the system qubits ancilla (int): index for the ancillary qubit Returns: A QuantumCircuit object """ def zz_xx_pump(q, c, p, system, ancillae): """Returns a QuantumCircuit implementing the composition channel on the system qubits Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system qubits p (float): the efficiency for both channels, between 0 and 1 system (list): list of indices for the system qubits ancillae (list): list of indices for the ancillary qubits Returns: A QuantumCircuit object """
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
# Imports import numpy as np import matplotlib.pyplot as plt from datetime import datetime import json import copy # Main qiskit imports from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ # Error mitigation from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter, MeasurementFilter) # Utility functions from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.providers.jobstatus import JobStatus # We use ibmqx2 IBMQ.load_account() backend = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend('ibmqx2') # Local simulator simulator = Aer.get_backend('qasm_simulator') def zz_pump(q, c, p, system, ancilla): """Returns a QuantumCircuit implementing the ZZ pump channel on the system qubits Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system qubits p (float): the efficiency for the channel, between 0 and 1 system (list): list of indices for the system qubits ancilla (int): index for the ancillary qubit Returns: A QuantumCircuit object """ zz = QuantumCircuit(q, c) theta = 2 * np.arcsin(np.sqrt(p)) # Map information to ancilla zz.cx(q[system[0]], q[system[1]]) zz.x(q[ancilla]) zz.cx(q[system][1], q[ancilla]) # Conditional rotation zz.cu3(theta, 0.0, 0.0, q[ancilla], q[system[1]]) # Inverse mapping zz.cx(q[system[1]], q[ancilla]) # Measurement zz.h(q[system[0]]) zz.measure(q[system[0]], c[0]) zz.measure(q[system[1]], c[1]) return zz def xx_pump(q, c, p, system, ancilla): """Returns a QuantumCircuit implementing the XX pump channel on the system qubits Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system qubits p (float): the efficiency for the channel, between 0 and 1 system (list): list of indices for the system qubits ancilla (int): index for the ancillary qubit Returns: A QuantumCircuit object """ xx = QuantumCircuit(q, c) theta = 2 * np.arcsin(np.sqrt(p)) # Map information to ancilla xx.cx(q[system[0]], q[system[1]]) xx.h(q[system[0]]) xx.x(q[ancilla]) xx.cx(q[system[0]], q[ancilla]) # Conditional rotation xx.cu3(theta, 0.0, 0.0, q[ancilla], q[system[0]]) # Inverse mapping xx.cx(q[system[0]], q[ancilla]) # Measurement xx.measure(q[system[0]], c[0]) xx.measure(q[system[1]], c[1]) return xx def zz_xx_pump(q, c, p, system, ancillae): """Returns a QuantumCircuit implementing the composition channel on the system qubits Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system qubits p (float): the efficiency for both channels, between 0 and 1 system (list): list of indices for the system qubits ancillae (list): list of indices for the ancillary qubits Returns: A QuantumCircuit object """ zx = QuantumCircuit(q, c) theta = 2 * np.arcsin(np.sqrt(p)) # ZZ pump ## Map information to ancilla zx.cx(q[system[0]], q[system[1]]) zx.x(q[ancillae[0]]) zx.cx(q[system[1]], q[ancillae[0]]) ## Conditional rotation zx.cu3(theta, 0.0, 0.0, q[ancillae[0]], q[system[1]]) ## Inverse mapping zx.cx(q[system[1]], q[ancillae[0]]) # XX pump ## Map information to ancilla zx.h(q[system[0]]) zx.x(q[ancillae[1]]) zx.cx(q[system[0]], q[ancillae[1]]) ## Conditional rotation zx.cu3(theta, 0.0, 0.0, q[ancillae[1]], q[system[0]]) ## Inverse mapping zx.cx(q[system[0]], q[ancillae[1]]) # Measurement zx.measure(q[system[0]], c[0]) zx.measure(q[system[1]], c[1]) return zx def initial_conditions(q, system): """Returns a dictionary containing four QuantumCircuit objects which prepare the two-qubit system in different initial states Args: q (QuantumRegister): the register to use for the circuit system (list): list of indices for the system qubits Returns: A dictionary with the initial state QuantumCircuit objects and a list of labels """ # State labels state_labels = ['00', '01', '10', '11'] ic = {} for ic_label in state_labels: ic[ic_label] = QuantumCircuit(q) # |01> ic['01'].x(q[system[0]]) # |10> ic['10'].x(q[system[1]]) # |11> ic['11'].x(q[system[0]]) ic['11'].x(q[system[1]]) return ic, state_labels SHOTS = 8192 # The values for p p_values = np.linspace(0, 1, 10) # We create the quantum circuits q = QuantumRegister(5, name='q') c = ClassicalRegister(2, name='c') ## Index of the system qubit system = [2, 1] ## Indices of the ancillary qubits a_zz = 0 a_xx = 4 ## Prepare the qubits in four initial conditions ic_circs, ic_state_labels = initial_conditions(q, system) ## Three different channels, each with ## four initial conditions and ten values of p pumps = ['ZZ', 'XX', 'ZZ_XX'] circuits = {} for pump in pumps: circuits[pump] = {} for ic in ic_state_labels: circuits[pump][ic] = [] for ic in ic_state_labels: for p in p_values: circuits['ZZ'][ic].append(ic_circs[ic]+zz_pump(q, c, p, system, a_zz)) circuits['XX'][ic].append(ic_circs[ic]+xx_pump(q, c, p, system, a_xx)) circuits['ZZ_XX'][ic].append(ic_circs[ic]+zz_xx_pump(q, c, p, system, [a_zz, a_xx])) circuits['ZZ_XX']['00'][1].draw(output='mpl') # Execute the circuits on the local simulator jobs_sim = {} for pump in pumps: jobs_sim[pump] = {} for ic in ic_state_labels: jobs_sim[pump][ic] = execute(circuits[pump][ic], backend = simulator, shots = SHOTS) # Analyse the outcomes overlaps_sim = {} for pump in pumps: overlaps_sim[pump] = {} for ic in ic_state_labels: overlaps_sim[pump][ic] = [0.0]*len(p_values) for i in range(len(p_values)): for ic in ic_state_labels: counts = jobs_sim[pump][ic].result().get_counts(i) for outcome in counts: overlaps_sim[pump][outcome][i] += counts[outcome]/(4.0 * float(SHOTS)) # Plot the results fig_idx = 131 plt.figure(figsize=(15,6)) bell_labels = {'00': r"$| \phi^{+} \rangle$", '01': r"$| \phi^{-} \rangle$", '10': r"$| \psi^{+} \rangle$", '11': r"$| \psi^{-} \rangle$"} for pump in pumps: plt.subplot(fig_idx) for outcome in overlaps_sim[pump]: plt.plot(p_values, overlaps_sim[pump][outcome], label = bell_labels[outcome]) plt.xlabel('p') plt.ylabel('Overlap') fig_idx += 1 plt.grid() plt.legend(); # Calibration circuits cal_circuits, state_labels = complete_meas_cal(system, q, c) # Run the calibration job calibration_job = execute(cal_circuits, backend, shots=SHOTS) # Run the circuits and save the jobs jobs = {} jobs_data = [] for pump in pumps: jobs[pump] = {} for ic in ic_state_labels: jobs[pump][ic] = execute(circuits[pump][ic], backend = backend, shots = SHOTS) # Use the calibration job to implement the error mitigation meas_fitter = CompleteMeasFitter(calibration_job.result(), ic_state_labels) meas_filter = meas_fitter.filter overlaps = {} for pump in pumps: overlaps[pump] = {} for ic in ic_state_labels: overlaps[pump][ic] = [0.0]*len(p_values) for i in range(len(p_values)): for ic in ic_state_labels: counts = meas_filter.apply(jobs[pump][ic].result()).get_counts(i) for outcome in counts: overlaps[pump][outcome][i] += counts[outcome]/(4 * float(SHOTS)) # Plot the results fig_idx = 131 plt.figure(figsize=(15,6)) bell_labels = {'00': r"$| \phi^{+} \rangle$", '01': r"$| \phi^{-} \rangle$", '10': r"$| \psi^{+} \rangle$", '11': r"$| \psi^{-} \rangle$"} for pump in pumps: plt.subplot(fig_idx) for outcome in overlaps[pump]: plt.plot(p_values, overlaps[pump][outcome], label = bell_labels[outcome]) plt.xlabel('p') plt.ylabel('Overlap') fig_idx += 1 plt.grid() plt.legend();
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit import numpy as np ########################################### # Amplitude damping channel on IBMQ_VIGO # ########################################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit ad = QuantumCircuit(q) # Amplitude damping channel acting on system qubit ## Qubit identification system = 1 environment = 2 # Define rotation angle theta = 0.0 # Construct circuit ad.x(q[system]) # Notice the extra factor 2 due to how qiskit defines the unitary angles ad.cu(theta, 0.0, 0.0, 0.0, q[system], q[environment]) ad.cx(q[environment], q[system]) # Draw circuit ad.draw(output='mpl') def c1(R,t): """Returns the coherence factor in the amplitude damping channel Args: R (float): value of R = \gamma_0/\lambda t (float): value of the time variable Returns: A float number """ def amplitude_damping_channel(q, c, sys, env, R, t): """Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system qubit sys (int): index for the system qubit env (int): index for the environment qubit R (float): value of R = \gamma_0/\lambda t (float): value of the time variable Returns: A QuantumCircuit object """ ####################################### # Amplitude damping channel # # with non-M. witness on IBMQ_VIGO # ####################################### # Quantum and classical register q = QuantumRegister(5, name='q') c = ClassicalRegister(2, name='c') # Quantum circuit ad = QuantumCircuit(q, c) # Amplitude damping channel acting on system qubit # with non-Markovianity witness ## Qubit identification system = 1 environment = 2 ancilla = 3 # Define rotation angle theta = 0.0 # Construct circuit ## Bell state between system and ancilla ad.h(q[system]) ad.cx(q[system], q[ancilla]) ## Channel acting on system qubit ad.cu3(theta, 0.0, 0.0, q[system], q[environment]) ad.cx(q[environment], q[system]) ## Local measurement for the witness ### Choose observable observable = 'YY' ### Change to the corresponding basis if observable == 'XX': ad.h(q[system]) ad.h(q[ancilla]) elif observable == 'YY': ad.sdg(q[system]) ad.h(q[system]) ad.sdg(q[ancilla]) ad.h(q[ancilla]) ### Measure ad.measure(q[system], c[0]) ad.measure(q[ancilla], c[1]) # Draw circuit ad.draw(output='mpl') def amplitude_damping_channel_witness(q, c, sys, env, anc, observable, R, t): """Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit with non-Markovianity witness Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system and ancilla qubits sys (int): index for the system qubit env (int): index for the environment qubit anc (int): index for the ancillary qubit observable (str): the observable to be measured. Possible values "XX", "YY", "ZZ" R (float): value of R = \gamma_0/\lambda t (float): value of the time variable Returns: A QuantumCircuit object """
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
# Imports import numpy as np import matplotlib.pyplot as plt from datetime import datetime import json import copy # Main qiskit imports from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ # Error mitigation from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter, MeasurementFilter) # Utility functions from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.providers.jobstatus import JobStatus # We use ibmq_vigo IBMQ.load_account() backend = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend('ibmq_quito') # Local simulator and vector simulator simulator = Aer.get_backend('qasm_simulator') def c1(R,t): """Returns the coherence factor in the amplitude damping channel Args: R (float): value of R = \gamma_0/\lambda t (float): value of the time variable Returns: A float number """ if R < 0.5: c1 = np.exp(- t / 2.0) * (np.cosh(t * np.sqrt(1.0 - 2.0 * R) / 2.0) + 1.0 / np.sqrt(1.0 - 2.0 * R) * np.sinh(t * np.sqrt(1.0 - 2.0 * R) / 2.0)) else: c1 = np.exp(- t / 2.0) * (np.cos(t * np.sqrt(2.0 * R - 1.0) / 2.0) + 1.0 / np.sqrt(2.0 * R - 1.0) * np.sin(t * np.sqrt(2.0 * R - 1.0) / 2.0)) return c1 def amplitude_damping_channel(q, c, sys, env, R, t): """Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system qubit sys (int): index for the system qubit env (int): index for the environment qubit R (float): value of R = \gamma_0/\lambda t (float): value of the time variable Returns: A QuantumCircuit object """ ad = QuantumCircuit(q, c) # Rotation angle theta = np.arccos(c1(R, t)) # Channel (notice the extra factor of 2 due to the definition # of the unitary gate in qiskit) ad.cu(2.0 * theta, 0.0, 0.0, 0.0, q[sys], q[env]) ad.cx(q[env], q[sys]) # Masurement in the computational basis ad.measure(q[sys], c[0]) return ad # We choose to add the initial condition elsewhere def initial_state(q, sys): """Returns a QuantumCircuit implementing the initial condition for the amplitude damping channel Args: q (QuantumRegister): the register to use for the circuit sys (int): index for the system qubit Returns: A QuantumCircuit object """ # Create circuit ic = QuantumCircuit(q) # System in |1> ic.x(q[sys]) return ic SHOTS = 8192 # The values for R and corresponding times R_values = [0.2, 100.0, 200.0, 400.0] npoints = 30 t_values = {} for R in R_values: t_values[R] = np.linspace(0.0, 6.0 * np.pi / np.sqrt(abs(2.0 * R - 1.0)), npoints) # We create the quantum circuits q = QuantumRegister(5, name="q") c = ClassicalRegister(1, name="c") ## Indices of the system and environment qubits sys = 1 env = 2 ## For values of R and thirty values of t for each circuits = {} for R in R_values: circuits[R] = [] for t in t_values[R]: circuits[R].append(initial_state(q, sys) + amplitude_damping_channel(q, c, sys, env, R, t)) circuits[0.2][1].draw(output='mpl') # Execute the circuits on the local simulator jobs_sim = {} for R in R_values: jobs_sim[R] = execute(circuits[R], backend = simulator, shots = SHOTS) # Analyse the outcomes populations_sim = {} for R in R_values: populations_sim[R] = [] current_job_res = jobs_sim[R].result() for i in range(npoints): counts = current_job_res.get_counts(i) if '1' in counts: sm = counts['1']/float(SHOTS) populations_sim[R].append(sm) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for R in R_values: plt.subplot(fig_idx) plt.plot(t_values[R], populations_sim[R], label=f"R = {R}") plt.xlabel('t') plt.ylabel('Population') plt.legend() fig_idx += 1 plt.grid() # Calibration circuits cal_circuits, state_labels = complete_meas_cal([sys], q, c) # Run the calibration job calibration_job = execute(cal_circuits, backend, shots=SHOTS) # Run the circuits and save the jobs jobs = {} for R in R_values: jobs[R] = execute(circuits[R], backend = backend, shots = SHOTS) # Use the calibration job to implement the error mitigation meas_fitter = CompleteMeasFitter(calibration_job.result(), state_labels) meas_filter = meas_fitter.filter # Analyse the outcomes populations = {} for R in jobs: populations[R] = [] current_job_res = jobs[R].result() for i in range(npoints): counts = meas_filter.apply(current_job_res).get_counts(i) if '1' in counts: sm = counts['1']/float(SHOTS) populations[R].append(sm) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for R in R_values: plt.subplot(fig_idx) plt.plot(t_values[R], populations[R], label='Experiment') plt.plot(t_values[R], populations_sim[R], label='Simulation') plt.xlabel('t') plt.ylabel('Population') fig_idx += 1 plt.grid() plt.legend(); def amplitude_damping_channel_witness(q, c, sys, env, anc, observable, R, t): """Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit with non-Markovianity witness Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system and ancilla qubits sys (int): index for the system qubit env (int): index for the environment qubit anc (int): index for the ancillary qubit observable (str): the observable to be measured R (float): value of R = \gamma_0/\lambda t (float): value of the time variable Returns: A QuantumCircuit object """ ad = QuantumCircuit(q, c) # Rotation angle theta = 2.0 * np.arccos(c1(R, t)) # Channel ad.cu3(theta, 0.0, 0.0, q[sys], q[env]) ad.cx(q[env], q[sys]) # Masurement of the corresponding observable if observable == 'xx': ad.h(sys) ad.h(anc) elif observable == 'yy': ad.sdg(sys) ad.h(sys) ad.sdg(anc) ad.h(anc) ad.measure(sys,c[0]) ad.measure(anc,c[1]) return ad # We set the initial entangled state separately def initial_state_witness(q, sys, anc): """Returns a QuantumCircuit implementing the initial condition for the amplitude damping channel with non-Markovianity witness Args: q (QuantumRegister): the register to use for the circuit sys (int): index for the system qubit anc (int): index for the ancilla qubit Returns: A QuantumCircuit object """ # Create circuit ic = QuantumCircuit(q) # System and ancilla in |\psi^+> ic.h(q[sys]) ic.cx(q[sys], q[anc]) return ic SHOTS = 8192 # The values for R and corresponding times, # as well as the observables needed for the witness observables = ['xx', 'yy', 'zz'] R_values = [0.2, 100.0] npoints = 30 t_values = {} for R in R_values: t_values[R] = np.linspace(0.0, 6.0 * np.pi / np.sqrt(abs(2.0 * R - 1.0)), npoints) # We create the quantum circuits q = QuantumRegister(5, name="q") c = ClassicalRegister(2, name="c") ## Indices of the system, environment and ancillary qubits sys = 1 env = 2 anc = 3 ## Two values of R and thirty values of t for each ## The witness requires measuring three observables per point circuits = {} for R in R_values: circuits[R] = {} for observable in observables: circuits[R][observable] = [] for t in t_values[R]: circuits[R][observable].append(initial_state_witness(q, sys, anc) +amplitude_damping_channel_witness(q, c, sys, env, anc, observable, R, t)) circuits[0.2]['yy'][1].draw(output='mpl') # Execute the circuits on the local simulator jobs_sim = {} for R in R_values: jobs_sim[R] = {} for observable in observables: jobs_sim[R][observable] = execute(circuits[R][observable], backend = simulator, shots = SHOTS) # Analyse the outcomes ## Compute expected values expected_sim = {} for R in R_values: expected_sim[R] = {} for observable in observables: expected_sim[R][observable] = [] current_job_res = jobs_sim[R][observable].result() for i in range(npoints): counts = current_job_res.get_counts(i) expc = 0.0 for outcome in counts: if outcome[0] == outcome[1]: expc += counts[outcome]/float(SHOTS) else: expc -= counts[outcome]/float(SHOTS) expected_sim[R][observable].append(expc) ## Compute witness witness_sim = {} for R in R_values: witness_sim[R] = [] for i in range(npoints): w = 0.25*(1.0+expected_sim[R]['xx'][i]-expected_sim[R]['yy'][i]+expected_sim[R]['zz'][i]) witness_sim[R].append(w) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for R in R_values: plt.subplot(fig_idx) plt.plot(t_values[R], witness_sim[R]) plt.xlabel('t') plt.ylabel('Population') fig_idx += 1 plt.grid() # Calibration circuits cal_circuits, state_labels = complete_meas_cal([sys, anc], q, c) # Run the calibration job calibration_job = execute(cal_circuits, backend, shots=SHOTS) # Run the circuits and save the jobs jobs = {} for R in R_values: jobs[R] = {} for observable in observables: jobs[R][observable] = execute(circuits[R][observable], backend = backend, shots = SHOTS) # Use the calibration job to implement the error mitigation meas_fitter = CompleteMeasFitter(calibration_job.result(), state_labels) meas_filter = meas_fitter.filter # Analyse the outcomes ## Compute expected values expected = {} for R in R_values: expected[R] = {} for observable in observables: expected[R][observable] = [] current_job_res = jobs[R][observable].result() mitigated_res = meas_filter.apply(current_job_res) for i in range(npoints): counts = mitigated_res.get_counts(i) expc = 0.0 for outcome in counts: if outcome[0] == outcome[1]: expc += counts[outcome]/float(SHOTS) else: expc -= counts[outcome]/float(SHOTS) expected[R][observable].append(expc) ## Compute witness witness = {} for R in R_values: witness[R] = [] for i in range(npoints): w = 0.25*(1.0+expected[R]['xx'][i]-expected[R]['yy'][i]+expected[R]['zz'][i]) witness[R].append(w) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for R in R_values: plt.subplot(fig_idx) plt.plot(t_values[R], witness[R], label='Experiment') plt.plot(t_values[R], witness_sim[R], label='Simulation') plt.xlabel('t') plt.ylabel('Witness') fig_idx += 1 plt.grid() plt.legend();
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
""" Circuit preparation for the amplitude damping channel """ from qiskit import QuantumCircuit import numpy as np from scipy.special import xlogy from scipy.optimize import minimize_scalar def initial_state(q, sys): """Returns a QuantumCircuit implementing the initial condition for the amplitude damping channel Args: q (QuantumRegister): the register to use for the circuit sys (int): index for the system qubit Returns: A QuantumCircuit object """ # Create circuit ic = QuantumCircuit(q) # System in |1> ic.x(q[sys]) return ic def initial_state_witness(q, sys, anc): """Returns a QuantumCircuit implementing the initial condition for the amplitude damping channel with non-Markovianity witness Args: q (QuantumRegister): the register to use for the circuit sys (int): index for the system qubit anc (int): index for the ancilla qubit Returns: A QuantumCircuit object """ # Create circuit ic = QuantumCircuit(q) # System and ancilla in |\psi^+> ic.h(q[sys]) ic.cx(q[sys], q[anc]) return ic def amplitude_damping_channel(q, c, sys, env, R, t): """Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system qubit sys (int): index for the system qubit env (int): index for the environment qubit R (float): value of R = \gamma_0/\lambda t (float): value of the time variable Returns: A QuantumCircuit object """ ad = QuantumCircuit(q, c) # Rotation angle theta = 2.0 * np.arccos(c1(R, t)) # Channel ad.cu3(theta, 0.0, 0.0, q[sys], q[env]) ad.cx(q[env], q[sys]) # Masurement in the computational basis ad.measure(q[sys], c[0]) return ad def amplitude_damping_channel_witness(q, c, sys, env, anc, observable, R, t): """Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit with non-Markovianity witness Args: q (QuantumRegister): the register to use for the circuit c (ClassicalRegister): the register to use for the measurement of the system and ancilla qubits sys (int): index for the system qubit env (int): index for the environment qubit anc (int): index for the ancillary qubit observable (str): the observable to be measured R (float): value of R = \gamma_0/\lambda t (float): value of the time variable Returns: A QuantumCircuit object """ ad = QuantumCircuit(q, c) # Rotation angle theta = 2.0 * np.arccos(c1(R, t)) # Channel ad.cu3(theta, 0.0, 0.0, q[sys], q[env]) ad.cx(q[env], q[sys]) # Masurement of the corresponding observable if observable == 'xx': ad.h(sys) ad.h(anc) elif observable == 'yy': ad.sdg(sys) ad.h(sys) ad.sdg(anc) ad.h(anc) ad.measure(sys,c[0]) ad.measure(anc,c[1]) return ad def c1(R,t): """Returns the coherence factor in the amplitude damping channel Args: R (float): value of R = \gamma_0/\lambda t (float): value of the time variable Returns: A float number """ if R < 0.5: c1 = np.exp(- t / 2.0) * (np.cosh(t * np.sqrt(1.0 - 2.0 * R) / 2.0) + 1.0 / np.sqrt(1.0 - 2.0 * R) * np.sinh(t * np.sqrt(1.0 - 2.0 * R) / 2.0)) else: c1 = np.exp(- t / 2.0) * (np.cos(t * np.sqrt(2.0 * R - 1.0) / 2.0) + 1.0 / np.sqrt(2.0 * R - 1.0) * np.sin(t * np.sqrt(2.0 * R - 1.0) / 2.0)) return c1 def H2(p): """Returns the binary Shannon entropy of its argument Args: p (float): value of p, between 0 and 1 Returns: A float number """ H2 = - xlogy(p, p) / np.log(2.0) - xlogy(1.0 - p, 1.0 - p) / np.log(2.0) return H2 def Qa(c): """Returns the quantum channel capacity (Eq. (14) in the paper) Args: c (float): value of |c_1(t)|^2 Returns: A float number """ Q = 0.0 if c > 0.5: f = lambda p: -H2(c * p) + H2((1.0 - c) * p) Q = -minimize_scalar(f, bounds=(0.0, 1.0), method='Bounded').fun return Q
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text, DataRange1d, Title from bokeh.plotting import Figure, show, output_file from bokeh.io import output_notebook from amplitude_damping import * R_values = np.geomspace(start=0.2, stop=500.0, num=100) R_values_str = [str(i) for i in range(len(R_values))] R_values_str_R = ['R = {:.2f}'.format(R) for R in R_values] # truncate to two decimals # make a dictionary of form {'0': 0.0, '1': 0.2, .. } R_values_dict = {R_values_str[i]:R_values.round(2)[i] for i,_ in enumerate(R_values)} # rounding to two decimals initial_r = R_values_str[len(R_values)//2] npoints = 400 ts_cap = np.linspace(0,1.1,200) ys_cap = {R: np.array([Qa(c1(R_values_dict[R],t)**2) for t in ts_cap]) for R in R_values_str} rs_cap = {R_values_str[i] : [R_values_str_R[i]] for i,_ in enumerate(R_values)} # Wrap the data in two ColumnDataSources #source_visible = ColumnDataSource(data=dict( # x = ts, y = ys[initial_r])) #source_available = ColumnDataSource(data=ys) source_visible = ColumnDataSource(data=dict( x = ts_cap, y = ys_cap[initial_r])) source_available = ColumnDataSource(data=ys_cap) # Define plot elements plot = Figure(plot_width=400, plot_height=400, x_range = DataRange1d(), y_range=(-.01, 1.01)) plot.line('x', 'y', source=source_visible, legend_label="Q(Φ(t))", line_width=3, line_alpha=0.6) # Add text text_source = ColumnDataSource({'r_value': [rs_cap[initial_r]]}) r_available = ColumnDataSource(data=rs_cap) text = Text(x=0, x_offset=315, y=.8, text='r_value', text_font_size='15pt', text_align='right') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys_cap.keys()]), end=np.max([int(i) for i in ys_cap.keys()]), step=1, show_value = False, title = 'R') # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available=source_available, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available = source_available.data; // Change y-axis data according to the selected value data_visible.y = data_available[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); """) layout = column(plot,slider) output_file("channel_cap.html", title="Channel Capacity") output_notebook() show(layout)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text from bokeh.plotting import Figure, show, output_file from bokeh.io import output_notebook def c1t(t, lam = 1., R = .25, c10 = 1.): expt = lam * t / 2 if R == .5: output = c10 * np.exp(-expt) * (1 + expt) #elif R == 0: # output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt) elif R < .5: sqt = np.sqrt(1-2*R) output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt) elif R > .5: sqt = np.sqrt(-1+2*R) output = c10 * np.exp(-expt) * (np.cos(expt * sqt) + np.sin(expt*sqt) / sqt) return output def lorentzian_J(w, R = .25, omega_0 = 0.): # assume gamma_0 = 1 if R == 0.: return 1 lam = 1. / R output = 1/(2*np.pi) * lam**2 / ((omega_0 - w)**2 + lam**2) return output ts = [t*0.02 for t in range(0, 500)] Rrange = [r*.02 for r in range(0,int(1/.02))] + [r * .1 for r in range(10,100)] + [r for r in range(10,100+1)] Rrange = np.array(Rrange) Rrange_str = [str(i) for i in range(len(Rrange))] Rrange_str_R = ['R = {:.2f}'.format(R) for R in Rrange] # truncate to two decimals # make a dictionary of form {'0': 0.0, '1': 0.2, .. } Rrange_dict = {Rrange_str[i]:Rrange.round(2)[i] for i,_ in enumerate(Rrange)} # rounding to two decimals ys = {r_str:[c1t(t, R = Rrange[int(r_str)])**2 for t in ts] for r_str in Rrange_str} #ys = {r_str:[c1t(t, R = Rrange_dict[r_str])**2 for t in ts] for r_str in Rrange_str} initial_r = Rrange_str[len(Rrange)//2] ws = [t*0.02 for t in range(-250, 250)] js = {r_str:[lorentzian_J(w, R = Rrange[int(r_str)]) for w in ws] for r_str in Rrange_str} rs = {Rrange_str[i] : [Rrange_str_R[i]] for i,_ in enumerate(Rrange)} # Wrap the data in two ColumnDataSources source_visible = ColumnDataSource(data=dict( x = ts, y = ys[initial_r])) source_available = ColumnDataSource(data=ys) # Wrap the data in two ColumnDataSources source_visible2 = ColumnDataSource(data=dict( x = ws, y = js[initial_r])) source_available2 = ColumnDataSource(data=js) # Define plot elements plot = Figure(plot_width=300, plot_height=300, x_range=(-.1, 10), y_range=(-.01, 1)) plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁(t)", line_width=3, line_alpha=0.6) plot2 = Figure(plot_width=300, plot_height=300, x_range=(-5, 5), y_range=(-.001, .2)) plot2.line('x', 'y', source=source_visible2, legend_label="J(ω)", line_width=3, line_alpha=0.6, line_color="#f01001") # Add text text_source = ColumnDataSource({'r_value': ['%s' % Rrange_str_R[1]]}) r_available = ColumnDataSource(data=rs) text = Text(x=9.5, y=.7, text='r_value', text_font_size='15pt', text_align='right') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False, title = 'R') # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available=source_available, source_visible2=source_visible2, source_available2=source_available2, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available = source_available.data; var data_visible2 = source_visible2.data; var data_available2 = source_available2.data; // Change y-axis data according to the selected value data_visible.y = data_available[r_idx]; data_visible2.y = data_available2[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); source_visible2.change.emit(); """) layout = row(column(plot,slider), plot2) output_file("jaynescummings.html", title="Jaynes-Cummings Model") output_notebook() show(layout)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np import matplotlib.pyplot as plt from datetime import datetime import json import copy # Main qiskit imports from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ # Error mitigation from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter, MeasurementFilter) # Utility functions from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.providers.jobstatus import JobStatus from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text, DataRange1d, Title from bokeh.plotting import Figure, show, output_file from bokeh.io import output_notebook import pickle #pickle.dump([ys,rs,ts,initial_r],open("witness_pop.p", "wb")) ys,rs,ts,initial_r = pickle.load(open( "witness_pop.p", "rb" )) ys_witness,rs_witness,ts_witness,initial_r = pickle.load(open( "nonmark_witness.p", "rb" )) initial_r = str(len(rs)//2) # Wrap the data in two ColumnDataSources #source_visible = ColumnDataSource(data=dict( # x = ts, y = ys[initial_r])) #source_available = ColumnDataSource(data=ys) source_visible = ColumnDataSource(data=dict( x = ts[initial_r], y = ys[initial_r])) source_available_x = ColumnDataSource(data=ts) source_available_y = ColumnDataSource(data=ys) source_visible2 = ColumnDataSource(data=dict( x = ts[initial_r], y = ys_witness[initial_r])) source_available2_x = ColumnDataSource(data=ts) source_available2_y = ColumnDataSource(data=ys_witness) # Define plot elements plot = Figure(plot_width=300, plot_height=300, x_range = DataRange1d(), y_range=(-.01, 1.01)) plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁(t)", line_width=3, line_alpha=0.6) plot2 = Figure(plot_width=300, plot_height=300, x_range = DataRange1d(), y_range=(-.01, 1.01)) plot2.line('x', 'y', source=source_visible2, legend_label="Non-Mark. Witness", line_width=3, line_alpha=0.6, line_color="#f01001") # Add text text_source = ColumnDataSource({'r_value': [rs[initial_r]]}) r_available = ColumnDataSource(data=rs) text = Text(x=0, x_offset=215, y=.7, text='r_value', text_font_size='15pt', text_align='right') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False, title = 'R') # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible = source_visible, source_available_x = source_available_x, source_available_y = source_available_y, source_visible2 = source_visible2, source_available2_x = source_available2_x, source_available2_y = source_available2_y, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available_x = source_available_x.data; var data_available_y = source_available_y.data; var data_visible2 = source_visible2.data; var data_available2_x = source_available_x.data; var data_available2_y = source_available2_y.data; // Change y-axis data according to the selected value data_visible.x = data_available_x[r_idx]; data_visible.y = data_available_y[r_idx]; data_visible2.x = data_available_x[r_idx]; data_visible2.y = data_available2_y[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); source_visible2.change.emit(); """) layout = row(column(plot,slider), plot2) output_file("nonmark_witness.html", title="Non-Markovianity Witness") output_notebook() show(layout)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import matplotlib.pyplot as plt import numpy as np import pandas as pd from bokeh.layouts import layout from bokeh.layouts import widgetbox from bokeh.embed import file_html from bokeh.io import show from bokeh.io import output_notebook from bokeh.models import Text from bokeh.models import Plot from bokeh.models import Slider from bokeh.models import Circle from bokeh.models import Range1d from bokeh.models import CustomJS from bokeh.models import HoverTool from bokeh.models import LinearAxis from bokeh.models import ColumnDataSource from bokeh.models import SingleIntervalTicker from bokeh.palettes import Spectral6 output_notebook() def gendata(): xs = np.linspace(0,6*np.pi) ws = np.linspace(.1,2.,20) ys = [np.sin(x*ws) for x in xs] return xs, ws, ys xs, ws, ys = gendata() ws_int = list(range(len(ws))) data = pd.DataFrame(ys) sources = {} for w, _ in enumerate(ws): new_df = pd.DataFrame({'x':xs,'fun':data[w]}) sources['_' + str(w)] = ColumnDataSource(new_df) dictionary_of_sources = dict(zip([w for w in ws_int], ['_%s' % w for w in ws_int])) dictionary_of_sources js_source_array = str(dictionary_of_sources).replace("'", "") js_source_array xdr = Range1d(min(xs), max(xs)) ydr = Range1d(-2, 2) plot = Plot( x_range=xdr, y_range=ydr, plot_width=800, plot_height=400, outline_line_color=None, toolbar_location=None, min_border=20, ) AXIS_FORMATS = dict( minor_tick_in=None, minor_tick_out=None, major_tick_in=None, major_label_text_font_size="10pt", major_label_text_font_style="normal", axis_label_text_font_size="10pt", axis_line_color='#AAAAAA', major_tick_line_color='#AAAAAA', major_label_text_color='#666666', major_tick_line_cap="round", axis_line_cap="round", axis_line_width=1, major_tick_line_width=1, ) xaxis = LinearAxis(ticker=SingleIntervalTicker(interval=1), axis_label="x", **AXIS_FORMATS) yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=20), axis_label="sin(w*x)", **AXIS_FORMATS) plot.add_layout(xaxis, 'below') plot.add_layout(yaxis, 'left') renderer_source = sources['_%s' % ws_int[0]] circle_glyph = Circle( x='x', y='fun', size=20, fill_alpha=0.8, fill_color='#7c7e71', line_color='#7c7e71', line_width=0.5, line_alpha=0.5) circle_renderer = plot.add_glyph(renderer_source, circle_glyph) # Add the slider code = """ var w = slider.value, sources = %s, new_source_data = sources[w].data; renderer_source.data = new_source_data; """ % js_source_array callback = CustomJS(args=sources, code=code) slider = Slider(start=ws_int[0], end=ws_int[-1], value=1, step=1, title="w", callback=callback) callback.args["renderer_source"] = renderer_source callback.args["slider"] = slider #callback.args["text_source"] = text_source show(layout([[plot], [slider]], sizing_mode='scale_width'))
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, TextAnnotation from bokeh.plotting import Figure, show from bokeh.io import output_notebook # Define data x = [x*0.05 for x in range(0, 500)] trigonometric_functions = { '0': np.sin(x), '1': np.cos(x), '2': np.tan(x), '3': np.arctan(x)} initial_function = '0' # Wrap the data in two ColumnDataSources source_visible = ColumnDataSource(data=dict( x=x, y=trigonometric_functions[initial_function])) source_available = ColumnDataSource(data=trigonometric_functions) # Define plot elements plot = Figure(plot_width=400, plot_height=400) plot.line('x', 'y', source=source_visible, line_width=3, line_alpha=0.6) slider = Slider(title='Trigonometric function', value=int(initial_function), start=np.min([int(i) for i in trigonometric_functions.keys()]), end=np.max([int(i) for i in trigonometric_functions.keys()]), step=1) # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available=source_available), code=""" var selected_function = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available = source_available.data; // Change y-axis data according to the selected value data_visible.y = data_available[selected_function]; // Update the plot source_visible.change.emit(); """) layout = row(plot, slider) output_notebook() show(layout) def c1t(t, lam = 1., R = .25, c10 = 1.): expt = lam * t / 2 if R == .5: output = c10 * np.exp(-expt) * (1 + expt) elif R == 0: output = c10 * np.exp(-expt) elif R < .5: sqt = np.sqrt(1-2*R) output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt) elif R > .5: sqt = np.sqrt(-1+2*R) output = c10 * np.exp(-expt) * (np.cos(expt * sqt) + np.sin(expt*sqt) / sqt) return output ts = [t*0.02 for t in range(0, 500)] Rmin = 0 Rmax = 10 Rstep = .2 Rrange = np.arange(Rmin, Rmax, Rstep) Rrange_str = [str(i) for i in range(len(Rrange))] #Rrange_str = ['{:.1f}'.format(i) for i in Rrange] # truncate to two decimals #Rrange_dict = {Rrange_str[i]:Rrange[i] for i,_ in enumerate(Rrange)} ys = {r_str:[c1t(t, R = Rrange[int(r_str)])**2 for t in ts] for r_str in Rrange_str} #ys = {r_str:[c1t(t, R = Rrange_dict[r_str])**2 for t in ts] for r_str in Rrange_str} initial_y = Rrange_str[1] # Wrap the data in two ColumnDataSources source_visible = ColumnDataSource(data=dict( x = ts, y = ys[initial_y])) source_available = ColumnDataSource(data=ys) # Define plot elements plot = Figure(plot_width=400, plot_height=400) plot.line('x', 'y', source=source_visible, line_width=3, line_alpha=0.6) slider = Slider(value=int(initial_function), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False) #slider = Slider(title='R = ', # value=float(initial_function), # start=float(Rrange_str[0]), # end=float(Rrange_str[-1]), # step=Rstep) # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available=source_available), code=""" var r_value = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available = source_available.data; // Change y-axis data according to the selected value data_visible.y = data_available[r_value]; // Update the plot source_visible.change.emit(); """) layout = row(plot, slider) output_notebook() show(layout)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text from bokeh.plotting import Figure, show from bokeh.io import output_notebook def c1t(t, lam = 1., R = .25, c10 = 1.): expt = lam * t / 2 if R == .5: output = c10 * np.exp(-expt) * (1 + expt) #elif R == 0: # output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt) elif R < .5: sqt = np.sqrt(1-2*R) output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt) elif R > .5: sqt = np.sqrt(-1+2*R) output = c10 * np.exp(-expt) * (np.cos(expt * sqt) + np.sin(expt*sqt) / sqt) return output def lorentzian_J(w, R = .25, omega_0 = 0.): # assume gamma_0 = 1 if R == 0.: return 1 lam = 1. / R output = 1/(2*np.pi) * lam**2 / ((omega_0 - w)**2 + lam**2) return output len(Rrange) ts = [t*0.02 for t in range(0, 500)] Rrange = [r*.02 for r in range(0,int(1/.02))] + [r * .1 for r in range(10,100)] + [r for r in range(10,100+1)] Rrange = np.array(Rrange) Rrange_str = [str(i) for i in range(len(Rrange))] Rrange_str_R = ['R = {:.2f}'.format(R) for R in Rrange] # truncate to two decimals # make a dictionary of form {'0': 0.0, '1': 0.2, .. } Rrange_dict = {Rrange_str[i]:Rrange.round(2)[i] for i,_ in enumerate(Rrange)} # rounding to two decimals ys = {r_str:[c1t(t, R = Rrange[int(r_str)])**2 for t in ts] for r_str in Rrange_str} #ys = {r_str:[c1t(t, R = Rrange_dict[r_str])**2 for t in ts] for r_str in Rrange_str} initial_r = Rrange_str[1] ys ws = [t*0.02 for t in range(-250, 250)] js = {r_str:[lorentzian_J(w, R = Rrange[int(r_str)]) for w in ws] for r_str in Rrange_str} rs = {Rrange_str[i] : [Rrange_str_R[i]] for i,_ in enumerate(Rrange)} # Wrap the data in two ColumnDataSources source_visible = ColumnDataSource(data=dict( x = ts, y = ys[initial_r])) source_available = ColumnDataSource(data=ys) # Wrap the data in two ColumnDataSources source_visible2 = ColumnDataSource(data=dict( x = ws, y = js[initial_r])) source_available2 = ColumnDataSource(data=js) # Define plot elements plot = Figure(plot_width=400, plot_height=400, x_range=(-.1, 10), y_range=(-.01, 1)) plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁", line_width=3, line_alpha=0.6) plot2 = Figure(plot_width=400, plot_height=400, x_range=(-5, 5), y_range=(-.001, .2)) plot2.line('x', 'y', source=source_visible2, legend_label="J(omega)", line_width=3, line_alpha=0.6, line_color="#f01001") # Add text text_source = ColumnDataSource({'r_value': ['%s' % Rrange_str_R[1]]}) r_available = ColumnDataSource(data=rs) text = Text(x=9.5, y=.8, text='r_value', text_font_size='15pt', text_align='right') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False, title = 'R') # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available=source_available, source_visible2=source_visible2, source_available2=source_available2, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available = source_available.data; var data_visible2 = source_visible2.data; var data_available2 = source_available2.data; // Change y-axis data according to the selected value data_visible.y = data_available[r_idx]; data_visible2.y = data_available2[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); source_visible2.change.emit(); """) layout = row(column(plot,slider), plot2) output_notebook() show(layout)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text from bokeh.plotting import Figure, show from bokeh.io import output_notebook def c1t(t, lam = 1., R = .25, c10 = 1.): expt = lam * t / 2 if R == .5: output = c10 * np.exp(-expt) * (1 + expt) #elif R == 0: # output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt) elif R < .5: sqt = np.sqrt(1-2*R) output = c10 * np.exp(-expt) * (np.cosh(expt * sqt) + np.sinh(expt*sqt) / sqt) elif R > .5: sqt = np.sqrt(-1+2*R) output = c10 * np.exp(-expt) * (np.cos(expt * sqt) + np.sin(expt*sqt) / sqt) return output ts = [t*0.02 for t in range(0, 500)] Rmin = 0 Rmax = 10 Rstep = .2 Rrange = np.arange(Rmin, Rmax, Rstep) Rrange_str = [str(i) for i in range(len(Rrange))] lamrange = np.arange(.1,2.,.1) lamrange_str = [str(lam) for lam in range(len(lamrange))] Rrange_str_R = ['R = {:.1f}'.format(R) for R in Rrange] #Rrange_str = ['{:.1f}'.format(i) for i in Rrange] # truncate to two decimals # make a dictionary of form {'0': 0.0, '1': 0.2, .. } Rrange_dict = {Rrange_str[i]:Rrange.round(2)[i] for i,_ in enumerate(Rrange)} # rounding to two decimals ys = {r_str:{lam_str:[c1t(t, R = Rrange[int(r_str)], lam = lamrange[int(lam_str)])**2 for t in ts] for lam_str in lamrange_str} for r_str in Rrange_str} #ys = {r_str:[c1t(t, R = Rrange_dict[r_str])**2 for t in ts] for r_str in Rrange_str} initial_r = Rrange_str[1] initial_lam = lamrange_str[1] rs = {Rrange_str[i] : [Rrange_str_R[i]] for i,_ in enumerate(Rrange)} ys['0'].keys() # Wrap the data in two ColumnDataSources source_visible = ColumnDataSource(data=dict( x = ts, y = ys[initial_r][initial_lam])) source_available = ColumnDataSource(data=ys) # Define plot elements plot = Figure(plot_width=400, plot_height=400, x_range=(-.1, 10), y_range=(-.01, 1)) plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁", line_width=3, line_alpha=0.6) #plot.text(10,10,text='lalala',source=) # Add text text_source = ColumnDataSource({'r_value': ['%s' % Rrange_str_R[1]]}) r_available = ColumnDataSource(data=rs) text = Text(x=7.5, y=.8, text='r_value', text_font_size='15pt') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False) slider2 = Slider(value=int(initial_lam), start=np.min([int(i) for i in ys['0'].keys()]), end=np.max([int(i) for i in ys['0'].keys()]), step=1, show_value = False) # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available=source_available, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available = source_available.data; // Change y-axis data according to the selected value data_visible.y = data_available[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); """) slider2.callback = CustomJS( args=dict(source_visible=source_visible, source_available=source_available, text_source = text_source, r_available = r_available), code=""" var lam_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available = source_available.data; // Change y-axis data according to the selected value data_visible.y = data_available[lam_idx]; // Update the plot source_visible.change.emit(); """) layout = row(plot, slider) output_notebook() show(layout)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np import matplotlib.pyplot as plt from datetime import datetime import json import copy # Main qiskit imports from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ # Error mitigation from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter, MeasurementFilter) # Utility functions from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.providers.jobstatus import JobStatus # Shows a window in the upper left part with real-time information # on the status of the jobs running on the IBM Q device #%qiskit_job_watcher # We use ibmq_vigo IBMQ.load_account() backend = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend('ibmq_vigo') # Local simulator and vector simulator simulator = Aer.get_backend('qasm_simulator') from amplitude_damping import * SHOTS = 200 # 8192 # The values for R and corresponding times R_values = [0.2, 100.0, 200.0, 400.0] #R_values = [r*.05 for r in range(1,int(1/.05))] + [r * .4 for r in range(10,25)] + [r * 4. for r in range(10,100+1)] R_values = np.array(R_values) npoints = 400 t_values = {} for idx, R in enumerate(R_values): t_values[str(idx)] = np.linspace(0.0, 6.0 * np.pi / np.sqrt(abs(2.0 * R - 1.0)), npoints) #t_values = np.linspace(0.0,5.0,npoints) # We create the quantum circuits q = QuantumRegister(5, name="q") c = ClassicalRegister(1, name="c") ## Indices of the system and environment qubits sys = 1 env = 2 ## For values of R and thirty values of t for each circuits = {} for idx, R in enumerate(R_values): circuits[R] = [] for t in t_values[str(idx)]: circuits[R].append(initial_state(q, sys) +amplitude_damping_channel(q, c, sys, env, R, t)) # Calibration circuits cal_circuits, state_labels = complete_meas_cal([sys], q, c) circuits[0.2][1].draw(output='mpl') # Execute the circuits on the local simulator jobs_sim = {} for R in R_values: jobs_sim[R] = execute(circuits[R], backend = simulator, shots = SHOTS) # Analyse the outcomes populations_sim = {} for idx, R in enumerate(R_values): populations_sim[str(idx)] = [] # changed to str(i) to comply with bokeh bullshit current_job_res = jobs_sim[R].result() for i in range(npoints): counts = current_job_res.get_counts(i) sm = 0.0 if '1' in counts: sm += counts['1']/float(SHOTS) populations_sim[str(idx)].append(sm) # changed to str(i) to comply with bokeh bullshit # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for idx, R in enumerate(R_values): plt.subplot(fig_idx) plt.plot(t_values[str(idx)], populations_sim[str(idx)]) # changed to str to comply with bokeh bullshit plt.xlabel('t') plt.ylabel('Population') fig_idx += 1 plt.grid() from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text, DataRange1d, Title from bokeh.plotting import Figure, show from bokeh.io import output_notebook R_values_str = [str(i) for i in range(len(R_values))] R_values_str_R = ['R = {:.2f}'.format(R) for R in R_values] # truncate to two decimals # make a dictionary of form {'0': 0.0, '1': 0.2, .. } R_values_dict = {R_values_str[i]:R_values.round(2)[i] for i,_ in enumerate(R_values)} # rounding to two decimals ys = populations_sim rs = {R_values_str[i] : [R_values_str_R[i]] for i,_ in enumerate(R_values)} ts = t_values initial_r = R_values_str[-1] initial_r rs # Wrap the data in two ColumnDataSources #source_visible = ColumnDataSource(data=dict( # x = ts, y = ys[initial_r])) #source_available = ColumnDataSource(data=ys) source_visible = ColumnDataSource(data=dict( x = ts[initial_r], y = ys[initial_r])) source_available_x = ColumnDataSource(data=ts) source_available_y = ColumnDataSource(data=ys) # Define plot elements plot = Figure(plot_width=400, plot_height=400, x_range = DataRange1d(), y_range=(-.01, 1)) plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁", line_width=3, line_alpha=0.6) # Add text text_source = ColumnDataSource({'r_value': [rs[initial_r]]}) r_available = ColumnDataSource(data=rs) text = Text(x=0, x_offset=315, y=.8, text='r_value', text_font_size='15pt', text_align='right') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False, title = 'R') # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available_x=source_available_x, source_available_y=source_available_y, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available_x = source_available_x.data; var data_available_y = source_available_y.data; // Change y-axis data according to the selected value data_visible.x = data_available_x[r_idx]; data_visible.y = data_available_y[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); """) layout = column(plot,slider) output_notebook() show(layout) # Run the calibration job calibration_job = execute(cal_circuits, backend, shots=SHOTS) # Run the circuits and save the jobs jobs = {} jobs_data = [] for R in R_values: jobs[R] = execute(circuits[R], backend = backend, shots = SHOTS) job_data = {'jobid': jobs[R].job_id(), 'description': 'Amplitude damping channel for R = '+str(R), 'metadata': {'t_values': list(t_values[R]), 'R': R}} jobs_data.append(job_data) experiment_data = [{ "backend": backend.name(), "calibration": calibration_job.job_id(), "description": "Circuits for the simulation of the amplitude damping channel", "jobs": jobs_data }] filename = 'amplitude_damping_{}.json'.format( datetime.now().strftime(("%Y_%m_%d-%H_%M"))) with open(filename,'w') as file: json.dump(experiment_data, file) # List the available experiment files import glob print("Available experiment files:") for f in glob.glob('*.json'): print(f) # Load the experiment file filename = "amplitude_damping_2019_11_18-17_15.json" with open(filename, 'r') as file: experiment_data = json.load(file) print(experiment_data[0]['description']) print("Run on", experiment_data[0]['backend']) # Get the backend backend = IBMQ.get_provider(hub='ibm-q-university', group='turku', project='main').get_backend(experiment_data[0]['backend']) # Use the calibration job to implement the error mitigation calibration_job = backend.retrieve_job(experiment_data[0]['calibration']) meas_fitter = CompleteMeasFitter(calibration_job.result(), state_labels) meas_filter = meas_fitter.filter # Analyse the outcomes t_values = {} jobs = {} for job in experiment_data[0]['jobs']: R = job['metadata']['R'] t_values[R] = np.array(job['metadata']['t_values']) jobs[R] = backend.retrieve_job(job['jobid']) populations = {} for R in jobs: populations[R] = [] current_job_res = jobs[R].result() for i in range(npoints): counts = meas_filter.apply(current_job_res).get_counts(i) sm = 0.0 if '1' in counts: sm += counts['1']/float(SHOTS) populations[R].append(sm) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for R in R_values: plt.subplot(fig_idx) plt.plot(t_values[R], populations[R], label='Experiment') plt.plot(t_values[R], populations_sim[R], label='Simulation') plt.xlabel('t') plt.ylabel('Population') fig_idx += 1 plt.grid() plt.legend(); # Compute the channel capacity Qa_exp = {} Qa_sim = {} t_sim = np.linspace(0, 0.7, 200) for R in populations: Qa_exp[R] = [] for i in range(len(t_values[R])): Qa_exp[R].append(Qa(populations[R][i]/populations[R][0])) Qa_sim[R] = [] for t in t_sim: Qa_sim[R].append(Qa(c1(R, t)**2)) # Plot the results plt.figure(figsize=(7,8)) for i, R in enumerate(R_values[1:]): c = ['r', 'g', 'b'][i] plt.plot(t_values[R], Qa_exp[R], marker = 's', lw = 0, c = c, label=r'R = ' + str(R)) plt.plot(t_sim, Qa_sim[R], c = c, ls = '--') plt.xlim(0., 0.7) plt.ylim(0., 1.) plt.xlabel('t') plt.ylabel(r'$Q_a$') plt.legend(); plt.grid() jobs[0.2].properties().qubits jobs[0.2].properties().gates
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np import matplotlib.pyplot as plt from datetime import datetime import json import copy # Main qiskit imports from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ # Error mitigation from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter, MeasurementFilter) # Utility functions from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.providers.jobstatus import JobStatus # Shows a window in the upper left part with real-time information # on the status of the jobs running on the IBM Q device #%qiskit_job_watcher # We use ibmq_vigo IBMQ.load_account() backend = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend('ibmq_vigo') # Local simulator and vector simulator simulator = Aer.get_backend('qasm_simulator') from amplitude_damping import * SHOTS = 200 #8192 # The values for R and corresponding times, # as well as the observables needed for the witness observables = ['xx', 'yy', 'zz'] R_values = np.array([0.2, 100.0]) npoints = 200 t_values = {} for idx, R in enumerate(R_values): t_values[str(idx)] = np.linspace(0.0, 6.0 * np.pi / np.sqrt(abs(2.0 * R - 1.0)), npoints) #t_values = np.linspace(0.0,5.0,npoints) # We create the quantum circuits q = QuantumRegister(5, name="q") c = ClassicalRegister(2, name="c") ## Indices of the system, environment and ancillary qubits sys = 1 env = 2 anc = 3 ## Two values of R and thirty values of t for each ## The witness requires measuring three observables per point circuits = {} for idx, R in enumerate(R_values): circuits[R] = {} for observable in observables: circuits[R][observable] = [] for t in t_values[str(idx)]: circuits[R][observable].append(initial_state_witness(q, sys, anc) +amplitude_damping_channel_witness(q, c, sys, env, anc, observable, R, t)) # Calibration circuits cal_circuits, state_labels = complete_meas_cal([sys, anc], q, c) circuits[0.2]['yy'][1].draw(output='mpl') # Execute the circuits on the local simulator jobs_sim = {} for R in R_values: jobs_sim[R] = {} for observable in observables: jobs_sim[R][observable] = execute(circuits[R][observable], backend = simulator, shots = SHOTS) # Analyse the outcomes ## Compute expected values expected_sim = {} for idx, R in enumerate(R_values): expected_sim[str(idx)] = {} for observable in observables: expected_sim[str(idx)][observable] = [] current_job_res = jobs_sim[R][observable].result() for i in range(npoints): counts = current_job_res.get_counts(i) expc = 0.0 for outcome in counts: if outcome[0] == outcome[1]: expc += counts[outcome]/float(SHOTS) else: expc -= counts[outcome]/float(SHOTS) expected_sim[str(idx)][observable].append(expc) ## Compute witness witness_sim = {} for idx, R in enumerate(R_values): witness_sim[str(idx)] = [] for i in range(npoints): w = 0.25*(1.0+expected_sim[str(idx)]['xx'][i]-expected_sim[str(idx)]['yy'][i]+expected_sim[str(idx)]['zz'][i]) witness_sim[str(idx)].append(w) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for idx, R in enumerate(R_values): plt.subplot(fig_idx) plt.plot(t_values[str(idx)], witness_sim[str(idx)]) plt.xlabel('t') plt.ylabel('Population') fig_idx += 1 plt.grid() from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text from bokeh.plotting import Figure, show from bokeh.io import output_notebook R_values_str = [str(i) for i in range(len(R_values))] R_values_str_R = ['R = {:.2f}'.format(R) for R in R_values] # truncate to two decimals # make a dictionary of form {'0': 0.0, '1': 0.2, .. } R_values_dict = {R_values_str[i]:R_values.round(2)[i] for i,_ in enumerate(R_values)} # rounding to two decimals ys = witness_sim rs = {R_values_str[i] : [R_values_str_R[i]] for i,_ in enumerate(R_values)} ts = t_values initial_r = R_values_str[1] # Wrap the data in two ColumnDataSources source_visible = ColumnDataSource(data=dict( x = ts[initial_r], y = ys[initial_r])) source_available_x = ColumnDataSource(data=ts) source_available_y = ColumnDataSource(data=ys) # Define plot elements plot = Figure(plot_width=400, plot_height=400, y_range=(-.01, 1)) plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁", line_width=3, line_alpha=0.6) # Add text text_source = ColumnDataSource({'r_value': [rs[initial_r]]}) r_available = ColumnDataSource(data=rs) text = Text(x=0, x_offset=315, y=.8, text='r_value', text_font_size='15pt', text_align='right') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False, title = 'R') # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available_x=source_available_x, source_available_y=source_available_y, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available_x = source_available_x.data; var data_available_y = source_available_y.data; // Change y-axis data according to the selected value data_visible.x = data_available_x[r_idx]; data_visible.y = data_available_y[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); """) layout = column(plot,slider) output_notebook() show(layout) # Run the calibration job calibration_job = execute(cal_circuits, backend, shots=SHOTS) # Run the circuits and save the jobs jobs = {} jobs_data = [] for R in R_values: jobs[R] = {} for observable in observables: jobs[R][observable] = execute(circuits[R][observable], backend = backend, shots = SHOTS) job_data = {'jobid': jobs[R][observable].job_id(), 'description': 'Amplitude damping channel for R = '+str(R)+'. Non-Markovianity witness observable: '+observable, 'metadata': {'t_values': list(t_values[R]), 'R': R, 'observable': observable}} jobs_data.append(job_data) experiment_data = [{ "backend": backend.name(), "calibration": calibration_job.job_id(), "description": "Circuits for the simulation of the amplitude damping channel with non-Markovianity witness", "jobs": jobs_data }] filename = 'amplitude_damping_witness_{}.json'.format( datetime.now().strftime(("%Y_%m_%d-%H_%M"))) with open(filename,'w') as file: json.dump(experiment_data, file) # List the available experiment files import glob print("Available experiment files:") for f in glob.glob('*.json'): print(f) # Load the experiment file filename = "amplitude_damping_witness_2019_11_19-14_48.json" with open(filename, 'r') as file: experiment_data = json.load(file) print(experiment_data[0]['description']) print("Run on", experiment_data[0]['backend']) # Get the backend backend = IBMQ.get_provider(hub='ibm-q-university', group='turku', project='main').get_backend(experiment_data[0]['backend']) # Use the calibration job to implement the error mitigation calibration_job = backend.retrieve_job(experiment_data[0]['calibration']) meas_fitter = CompleteMeasFitter(calibration_job.result(), state_labels) meas_filter = meas_fitter.filter # Analyse the outcomes t_values = {} ## Retrieve jobs jobs = {} for job in experiment_data[0]['jobs']: R = job['metadata']['R'] t_values[R] = np.array(job['metadata']['t_values']) observable = job['metadata']['observable'] if R not in jobs: jobs[R] = {} jobs[R][observable] = backend.retrieve_job(job['jobid']) ## Compute expected values expected = {} for R in R_values: expected[R] = {} for observable in observables: expected[R][observable] = [] current_job_res = jobs[R][observable].result() mitigated_res = meas_filter.apply(current_job_res) for i in range(npoints): counts = mitigated_res.get_counts(i) expc = 0.0 for outcome in counts: if outcome[0] == outcome[1]: expc += counts[outcome]/float(SHOTS) else: expc -= counts[outcome]/float(SHOTS) expected[R][observable].append(expc) ## Compute witness witness = {} for R in R_values: witness[R] = [] for i in range(npoints): w = 0.25*(1.0+expected[R]['xx'][i]-expected[R]['yy'][i]+expected[R]['zz'][i]) witness[R].append(w) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for R in R_values: plt.subplot(fig_idx) plt.plot(t_values[R], witness[R], label='Experiment') plt.plot(t_values[R], witness_sim[R], label='Simulation') plt.xlabel('t') plt.ylabel('Witness') fig_idx += 1 plt.grid() plt.legend(); jobs[0.2]['zz'].properties().qubits jobs[0.2]['zz'].properties().gates
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() from qiskit.quantum_info import Operator from qiskit import QuantumCircuit import numpy as np def phase_oracle(n, indices_to_mark, name = 'Oracle'): # create a quantum circuit on n qubits qc = QuantumCircuit(n, name=name) ### WRITE YOUR CODE BETWEEN THESE LINES - START for qubits in range(n): qc.h(qubits) for index, value in enumerate(indices_to_mark): if index == 0: for qubits in range(1, n): qc.x(qubits) qc.cz() for qubits in range(1, n): qc.x(qubits) oracle_matrix = qc.diagonal if index == 1: for qubits in range(1, n, 2): qc.x(qubits) qc.cz() for qubits in range(1, n, 2): qc.x(qubits) oracle_matrix = qc.diagonal ### WRITE YOUR CODE BETWEEN THESE LINES - END # convert your matrix (called oracle_matrix) into an operator, and add it to the quantum circuit qc.unitary(Operator(oracle_matrix), range(n)) return qc def diffuser(n): # create a quantum circuit on n qubits qc = QuantumCircuit(n, name='Diffuser') ### WRITE YOUR CODE BETWEEN THESE LINES - START ### WRITE YOUR CODE BETWEEN THESE LINES - END return qc def Grover(n, indices_of_marked_elements): # Create a quantum circuit on n qubits qc = QuantumCircuit(n, n) # Determine r r = int(np.floor(np.pi/4*np.sqrt(2**n/len(indices_of_marked_elements)))) print(f'{n} qubits, basis states {indices_of_marked_elements} marked, {r} rounds') # step 1: apply Hadamard gates on all qubits qc.h(range(n)) # step 2: apply r rounds of the phase oracle and the diffuser for _ in range(r): qc.append(phase_oracle(n, indices_of_marked_elements), range(n)) qc.append(diffuser(n), range(n)) # step 3: measure all qubits qc.measure(range(n), range(n)) return qc mycircuit = Grover(6, [1, 42]) mycircuit.draw(output='text') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') counts = execute(mycircuit, backend=simulator, shots=1000).result().get_counts(mycircuit) from qiskit.visualization import plot_histogram plot_histogram(counts) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' ### Do not change the lines below from qiskit import transpile mycircuit_t = transpile(mycircuit, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=0) from grading_tools import grade grade(answer=mycircuit_t, name=name, email=email, labid='lab2', exerciseid='ex1')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector excited = Statevector.from_int(1, 2) plot_bloch_multivector(excited.data) from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The Rabi sweep will be at the given qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") from qiskit import pulse, assemble # This is where we access all of our Pulse features! from qiskit.pulse import Play from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[0]) # Rabi experiment parameters # Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75 num_rabi_points = 50 drive_amp_min = 0 drive_amp_max = 0.75 drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points) # drive waveforms mush be in units of 16 drive_sigma = 80 # in dt drive_samples = 8*drive_sigma # in dt # Build the Rabi experiments: # A drive pulse at the qubit frequency, followed by a measurement, # where we vary the drive amplitude each time. rabi_schedules = [] for drive_amp in drive_amps: rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}") this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}") this_schedule += Play(rabi_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration this_schedule += measure << this_schedule.duration rabi_schedules.append(this_schedule) rabi_schedules[-1].draw(label=True, scaling=1.0) # assemble the schedules into a Qobj num_shots_per_point = 1024 rabi_experiment_program = assemble(rabi_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_point, schedule_los=[{drive_chan: center_frequency_Hz}] * num_rabi_points) # RUN the job on a real device #job = backend.run(rabi_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive result from previous run job = backend.retrieve_job("5ef3bf17dc3044001186c011") rabi_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') scale_factor = 1e-14 # center data around 0 def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = [] for i in range(num_rabi_points): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) rabi_values = np.real(baseline_remove(rabi_values)) plt.xlabel("Drive amp [a.u.]") plt.ylabel("Measured signal [a.u.]") plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(drive_amps, rabi_values, lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B), [10, 0.1, 0.6, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() pi_amp = abs(drive_period / 2) print(f"Pi Amplitude = {pi_amp}") # Drive parameters # The drive amplitude for pi/2 is simply half the amplitude of the pi pulse drive_amp = pi_amp / 2 # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 1.8 time_step_us = 0.025 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us") this_schedule += Play(x90_pulse, drive_chan) this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay) this_schedule += measure << this_schedule.duration ramsey_schedules.append(this_schedule) ramsey_schedules[-1].draw(label=True, scaling=1.0) # Execution settings num_shots = 256 detuning_MHz = 2 ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz ramsey_program = assemble(ramsey_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots, schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules) ) # RUN the job on a real device #job = backend.run(ramsey_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive job from previous run job = backend.retrieve_job('5ef3ed3a84b1b70012374317') ramsey_results = job.result() ramsey_values = [] for i in range(len(times_us)): ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor) fit_params, y_fit = fit_function(times_us, np.real(ramsey_values), lambda x, A, del_f_MHz, C, B: ( A * np.cos(2*np.pi*del_f_MHz*x - C) + B ), [5, 1./0.4, 0, 0.25] ) # Off-resonance component _, del_f_MHz, _, _, = fit_params # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz") plt.xlim(0, np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend() plt.show()
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib # the same spect pulse used in every schedule drive_amp = 0.9 drive_sigma = 16 drive_duration = 128 spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}") # Construct an np array of the frequencies for our experiment spec_freqs_GHz = np.arange(5.0, 5.2, 0.005) # Create the base schedule # Start with drive pulse acting on the drive channel spec_schedules = [] for freq in spec_freqs_GHz: sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt) spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq)) spec_schedule += Play(sb_spec_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration spec_schedule += measure << spec_schedule.duration spec_schedules.append(spec_schedule) spec_schedules[0].draw() from qiskit import assemble # assemble the schedules into a Qobj spec01_qobj = assemble(**helper.get_params('spec01', globals())) # run the simulation spec01_result = backend_sim.run(spec01_qobj, duffing_model).result() # retrieve the data from the experiment spec01_values = helper.get_values_from_result(spec01_result, qubit) fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0]) f01 = fit_params[1] plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values plt.plot(spec_freqs_GHz, y_fit, color='red') plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("01 Spectroscopy yields %f GHz"%f01) x180_amp = 0.629070 #from lab 6 Rabi experiment x_pulse = pulse_lib.gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') anharmonicity_guess_GHz = -0.3 def build_spec12_pulse_schedule(freq): sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt) ### create a 12 spectroscopy pulse schedule spec12_schedule (already done) ### play an x pulse on the drive channel ### play sidebanded spec pulse on the drive channel ### add measurement pulse to schedule spec12_schedule = pulse.Schedule() ### WRITE YOUR CODE BETWEEN THESE LINES - START spec12_schedule += Play(x_pulse, drive_chan) spec12_schedule += Play(sb12_spec_pulse, drive_chan) spec12_schedule += measure << spec12_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - STOP return spec12_schedule sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess # now vary the sideband frequency for each spec pulse spec_schedules = [] for freq in sb_freqs_GHz: spec_schedules.append(build_spec12_pulse_schedule(freq)) spec_schedules[0].draw() # assemble the schedules into a Qobj spec12_qobj = assemble(**helper.get_params('spec12', globals())) answer1 = spec12_qobj # run the simulation spec12_result = backend_sim.run(spec12_qobj, duffing_model).result() # retrieve the data from the experiment spec12_values = helper.get_values_from_result(spec12_result, qubit) anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3]) f12 = fit_params[1] plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red') plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("12 Spectroscopy yields %f GHz"%f12) print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz)) from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
# import SymPy and define symbols import sympy as sp sp.init_printing(use_unicode=True) wr = sp.Symbol('\omega_r') # resonator frequency wq = sp.Symbol('\omega_q') # qubit frequency g = sp.Symbol('g', real=True) # vacuum Rabi coupling Delta = sp.Symbol('Delta', real=True) # wr - wq; defined later # import operator relations and define them from sympy.physics.quantum.boson import BosonOp a = BosonOp('a') # resonator photon annihilation operator from sympy.physics.quantum import pauli, Dagger, Commutator from sympy.physics.quantum.operatorordering import normal_ordered_form # Pauli matrices sx = pauli.SigmaX() sy = pauli.SigmaY() sz = pauli.SigmaZ() # qubit raising and lowering operators splus = pauli.SigmaPlus() sminus = pauli.SigmaMinus() # define J-C Hamiltonian in terms of diagonal and non-block diagonal terms H0 = wr*Dagger(a)*a - (1/2)*wq*sz; H1 = 0 H2 = g*(Dagger(a)*sminus + a*splus); HJC = H0 + H1 + H2; HJC # print # using the above method for finding the ansatz eta = Commutator(H0, H2); eta pauli.qsimplify_pauli(normal_ordered_form(eta.doit().expand())) A = sp.Symbol('A') B = sp.Symbol('B') eta = A * Dagger(a) * sminus - B * a * splus; pauli.qsimplify_pauli(normal_ordered_form(Commutator(H0, eta).doit().expand())) H2 S1 = eta.subs(A, g/Delta) S1 = S1.subs(B, g/Delta); S1.factor() Heff = H0 + H1 + 0.5*pauli.qsimplify_pauli(normal_ordered_form(Commutator(H2, S1).doit().expand())).simplify(); Heff from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The sweep will be centered around the estimated qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") # scale factor to remove factors of 10 from the data scale_factor = 1e-14 # We will sweep 40 MHz around the estimated frequency frequency_span_Hz = 40 * MHz # in steps of 1 MHz. frequency_step_Hz = 1 * MHz # We will sweep 20 MHz above and 20 MHz below the estimated frequency frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 # Construct an np array of the frequencies for our experiment frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \ in steps of {frequency_step_Hz / MHz} MHz.") from qiskit import pulse # This is where we access all of our Pulse features! inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[qubit]) x_pulse = inst_sched_map.get('x', qubits=[qubit]) ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Create the base schedule # Start with drive pulse acting on the drive channel schedule = pulse.Schedule(name='Frequency sweep') schedule += x_pulse # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration schedule += measure << schedule.duration # Create the frequency settings for the sweep (MUST BE IN HZ) frequencies_Hz = frequencies_GHz*GHz schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz] schedule.draw(label=True, scaling=0.8) from qiskit import assemble frequency_sweep_program = assemble(schedule, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=schedule_frequencies) # RUN the job on a real device #job = backend.run(rabi_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive result from previous run job = backend.retrieve_job('5ef3b081fbc24b001275b03b') frequency_sweep_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') sweep_values = [] for i in range(len(frequency_sweep_results.results)): # Get the results from the ith experiment res = frequency_sweep_results.get_memory(i)*scale_factor # Get the results for `qubit` from this experiment sweep_values.append(res[qubit]) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') # plot real part of sweep values plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured signal [a.u.]") plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(frequencies_GHz, np.real(sweep_values), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, [5, 4.975, 1, 3] # initial parameters for curve_fit ) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') plt.plot(frequencies_GHz, y_fit, color='red') plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() # Create the schedules for 0 and 1 schedule_0 = pulse.Schedule(name='0') schedule_0 += measure schedule_1 = pulse.Schedule(name='1') schedule_1 += x_pulse schedule_1 += measure << schedule_1.duration schedule_0.draw() schedule_1.draw() frequency_span_Hz = 320 * kHz frequency_step_Hz = 8 * kHz center_frequency_Hz = backend_defaults.meas_freq_est[qubit] print(f"Qubit {qubit} has an estimated readout frequency of {center_frequency_Hz / GHz} GHz.") frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz\ in steps of {frequency_step_Hz / MHz} MHz.") num_shots_per_frequency = 2048 frequencies_Hz = frequencies_GHz*GHz schedule_los = [{meas_chan: freq} for freq in frequencies_Hz] cavity_sweep_0 = assemble(schedule_0, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) cavity_sweep_1 = assemble(schedule_1, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) # RUN the job on a real device #job_0 = backend.run(cavity_sweep_0) #job_monitor(job_0) #job_0.error_message() #job_1 = backend.run(cavity_sweep_1) #job_monitor(job_1) #job_1.error_message() # OR retreive result from previous run job_0 = backend.retrieve_job('5efa5b447c0d6800137fff1c') job_1 = backend.retrieve_job('5efa6b2720eee10013be46b4') cavity_sweep_0_results = job_0.result() cavity_sweep_1_results = job_1.result() scale_factor = 1e-14 sweep_values_0 = [] for i in range(len(cavity_sweep_0_results.results)): res_0 = cavity_sweep_0_results.get_memory(i)*scale_factor sweep_values_0.append(res_0[qubit]) sweep_values_1 = [] for i in range(len(cavity_sweep_1_results.results)): res_1 = cavity_sweep_1_results.get_memory(i)*scale_factor sweep_values_1.append(res_1[qubit]) plotx = frequencies_Hz/kHz ploty_0 = np.abs(sweep_values_0) ploty_1 = np.abs(sweep_values_1) plt.plot(plotx, ploty_0, color='blue', marker='.') # plot real part of sweep values plt.plot(plotx, ploty_1, color='red', marker='.') # plot real part of sweep values plt.legend([r'$\vert0\rangle$', r'$\vert1\rangle$']) plt.grid() plt.xlabel("Frequency [kHz]") plt.ylabel("Measured signal [a.u.]") plt.yscale('log') plt.show()
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib # the same spect pulse used in every schedule drive_amp = 0.9 drive_sigma = 16 drive_duration = 128 spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}") # Construct an np array of the frequencies for our experiment spec_freqs_GHz = np.arange(5.0, 5.2, 0.005) # Create the base schedule # Start with drive pulse acting on the drive channel spec_schedules = [] for freq in spec_freqs_GHz: sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt) spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq)) spec_schedule += Play(sb_spec_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration spec_schedule += measure << spec_schedule.duration spec_schedules.append(spec_schedule) spec_schedules[0].draw() from qiskit import assemble # assemble the schedules into a Qobj spec01_qobj = assemble(**helper.get_params('spec01', globals())) # run the simulation spec01_result = backend_sim.run(spec01_qobj, duffing_model).result() # retrieve the data from the experiment spec01_values = helper.get_values_from_result(spec01_result, qubit) fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0]) f01 = fit_params[1] plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values plt.plot(spec_freqs_GHz, y_fit, color='red') plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("01 Spectroscopy yields %f GHz"%f01) x180_amp = 0.629070 #from lab 6 Rabi experiment x_pulse = pulse_lib.gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') anharmonicity_guess_GHz = -0.3 def build_spec12_pulse_schedule(freq): sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt) ### create a 12 spectroscopy pulse schedule spec12_schedule (already done) ### play an x pulse on the drive channel ### play sidebanded spec pulse on the drive channel ### add measurement pulse to schedule spec12_schedule = pulse.Schedule() ### WRITE YOUR CODE BETWEEN THESE LINES - START spec12_schedule += Play(x_pulse, drive_chan) spec12_schedule += Play(sb12_spec_pulse, drive_chan) spec12_schedule += measure << spec12_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - STOP return spec12_schedule sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess # now vary the sideband frequency for each spec pulse spec_schedules = [] for freq in sb_freqs_GHz: spec_schedules.append(build_spec12_pulse_schedule(freq)) spec_schedules[0].draw() # assemble the schedules into a Qobj spec12_qobj = assemble(**helper.get_params('spec12', globals())) answer1 = spec12_qobj # run the simulation spec12_result = backend_sim.run(spec12_qobj, duffing_model).result() # retrieve the data from the experiment spec12_values = helper.get_values_from_result(spec12_result, qubit) anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3]) f12 = fit_params[1] plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red') plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("12 Spectroscopy yields %f GHz"%f12) print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz)) from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/SimoneGasperini/qiskit-symb
SimoneGasperini
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utils for using with Qiskit unit tests.""" import logging import os import unittest from enum import Enum from qiskit import __path__ as qiskit_path class Path(Enum): """Helper with paths commonly used during the tests.""" # Main SDK path: qiskit/ SDK = qiskit_path[0] # test.python path: qiskit/test/python/ TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python')) # Examples path: examples/ EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples')) # Schemas path: qiskit/schemas SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas')) # VCR cassettes path: qiskit/test/cassettes/ CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes')) # Sample QASMs path: qiskit/test/python/qasm QASMS = os.path.normpath(os.path.join(TEST, 'qasm')) def setup_test_logging(logger, log_level, filename): """Set logging to file and stdout for a logger. Args: logger (Logger): logger object to be updated. log_level (str): logging level. filename (str): name of the output file. """ # Set up formatter. log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(logger.name)) formatter = logging.Formatter(log_fmt) # Set up the file handler. file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(log_level, logging.INFO) logger.setLevel(level) class _AssertNoLogsContext(unittest.case._AssertLogsContext): """A context manager used to implement TestCase.assertNoLogs().""" # pylint: disable=inconsistent-return-statements def __exit__(self, exc_type, exc_value, tb): """ This is a modified version of TestCase._AssertLogsContext.__exit__(...) """ self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.watcher.records: msg = 'logs of level {} or higher triggered on {}:\n'.format( logging.getLevelName(self.level), self.logger.name) for record in self.watcher.records: msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, record.lineno, record.getMessage()) self._raiseFailure(msg)
https://github.com/SimoneGasperini/qiskit-symb
SimoneGasperini
"""Docstring.""" from qiskit import QuantumCircuit, execute, QuantumRegister, ClassicalRegister from qiskit_aer import Aer class Random: """Demo random.""" def __init__(self): """Demo random.""" self.pow = 2 self.qasm = Aer.get_backend("aer_simulator") def run(self, number: int) -> int: """Run method.""" nb_qubits = number print("Generate random number") circ = QuantumRegister(nb_qubits, "the number") meas = ClassicalRegister(nb_qubits, "measurement") quant_circ = QuantumCircuit(circ, meas) for i in range(0, nb_qubits): quant_circ.x(i) quant_circ.measure(circ, meas) job = execute(quant_circ, self.qasm, shots=1, memory=True) result_sim = job.result() memory = result_sim.get_memory() result = int(memory[0], 2) + 1 return result def __repr__(self): return f"Random(circuit of: {self.pow})"
https://github.com/SimoneGasperini/qiskit-symb
SimoneGasperini
"""Symbolic quantum base module""" import numpy import sympy from sympy import Symbol, lambdify from sympy.matrices import Matrix, matrix2numpy from qiskit import QuantumCircuit from qiskit.providers.basic_provider.basic_provider_tools import einsum_matmul_index class QuantumBase: """Abstract symbolic quantum base class""" def __init__(self, data, params): """todo""" # pylint: disable=no-member if isinstance(data, QuantumCircuit): params = list(data.parameters) data = self._get_data_from_circuit(circuit=data) self._data = data self._params = params @staticmethod def _get_circ_unitary(circ): """todo""" # pylint: disable=import-outside-toplevel # pylint: disable=protected-access from ..utils import transpile_circuit, flatten_circuit from ..circuit import Gate circ = transpile_circuit(flatten_circuit(circ)) layers = circ.draw(output='text').nodes dim = 2 ** circ.num_qubits newshape = (2, 2) * circ.num_qubits unitary = numpy.reshape(numpy.eye(dim), newshape=newshape) for layer in layers: for instruction in layer[::-1]: gate_tensor = Gate.get(instruction)._get_tensor() gate_indices = [qarg._index for qarg in instruction.qargs] indexing = einsum_matmul_index( gate_indices=gate_indices, number_of_qubits=circ.num_qubits) unitary = numpy.einsum(indexing, gate_tensor, unitary, dtype=object, casting='no', optimize='optimal') gph = sympy.exp(sympy.I * circ.global_phase) return gph * Matrix(numpy.reshape(unitary, newshape=(dim, dim))) @classmethod def from_label(cls, label): """todo""" # pylint: disable=no-member data = cls._get_data_from_label(label) return cls(data=data, params=[]) @classmethod def from_circuit(cls, circuit): """todo""" # pylint: disable=no-member data = cls._get_data_from_circuit(circuit) params = list(circuit.parameters) return cls(data=data, params=params) def to_sympy(self): """todo""" return self._data def to_numpy(self): """todo""" return matrix2numpy(self._data, dtype=complex) def to_lambda(self): """todo""" sympy_matrix = self._data name2symb = {symb.name: symb for symb in sympy_matrix.free_symbols} args = [name2symb[par.name] if par.name in name2symb else Symbol('_') for par in self._params] return lambdify(args=args, expr=sympy_matrix, modules='numpy', dummify=True, cse=True) def subs(self, params_dict): """todo""" par2val = {} for par, val in params_dict.items(): if hasattr(par, '__len__'): par2val.update(dict(zip(par, val))) else: par2val[par] = val sympy_matrix = self._data name2symb = {symb.name: symb for symb in sympy_matrix.free_symbols} symb2val = {name2symb[par.name]: val for par, val in par2val.items() if par.name in name2symb} data = sympy_matrix.subs(symb2val) params = [par for par in self._params if par not in par2val] return self.__class__(data=data, params=params) def transpose(self): """todo""" return self.__class__(data=self._data.T, params=self._params) def conjugate(self): """todo""" return self.__class__(data=self._data.conjugate(), params=self._params) def dagger(self): """todo""" return self.__class__(data=self._data.T.conjugate(), params=self._params)
https://github.com/SimoneGasperini/qiskit-symb
SimoneGasperini
"""Test controlled standard gates module""" import numpy from hypothesis import given, strategies, settings from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.circuit.library import ( XGate, CXGate, YGate, CYGate, ZGate, CZGate, HGate, CHGate, SXGate, CSXGate, SXdgGate, SGate, CSGate, SdgGate, CSdgGate, TGate, TdgGate, SwapGate, CSwapGate, iSwapGate ) from qiskit_symb.utils import get_random_controlled from qiskit_symb import Operator as symb_Operator from qiskit_symb.circuit.library import ( CXGate as symb_CXGate, CYGate as symb_CYGate, CZGate as symb_CZGate, CHGate as symb_CHGate, CSXGate as symb_CSXGate, CSXdgGate as symb_CSXdgGate, CSGate as symb_CSGate, CSdgGate as symb_CSdgGate, CTGate as symb_CTGate, CTdgGate as symb_CTdgGate, CSwapGate as symb_CSwapGate, CiSwapGate as symb_CiSwapGate ) def test_cx(): """todo""" arr1 = CXGate().to_matrix() arr2 = symb_CXGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mcx(seed): """todo""" circuit = get_random_controlled(base_gate=XGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_cy(): """todo""" arr1 = CYGate().to_matrix() arr2 = symb_CYGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mcy(seed): """todo""" circuit = get_random_controlled(base_gate=YGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_cz(): """todo""" arr1 = CZGate().to_matrix() arr2 = symb_CZGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mcz(seed): """todo""" circuit = get_random_controlled(base_gate=ZGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_ch(): """todo""" arr1 = CHGate().to_matrix() arr2 = symb_CHGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mch(seed): """todo""" circuit = get_random_controlled(base_gate=HGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_csx(): """todo""" arr1 = CSXGate().to_matrix() arr2 = symb_CSXGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mcsx(seed): """todo""" circuit = get_random_controlled(base_gate=SXGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_csxdg(): """todo""" circuit = QuantumCircuit(2) circuit.append(SXdgGate().control(), qargs=[0, 1]) arr1 = Operator(circuit).data arr2 = symb_CSXdgGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mcsxdg(seed): """todo""" circuit = get_random_controlled(base_gate=SXdgGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_cs(): """todo""" arr1 = CSGate().to_matrix() arr2 = symb_CSGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mcs(seed): """todo""" circuit = get_random_controlled(base_gate=SGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_csdg(): """todo""" arr1 = CSdgGate().to_matrix() arr2 = symb_CSdgGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mcsdg(seed): """todo""" circuit = get_random_controlled(base_gate=SdgGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_ct(): """todo""" circuit = QuantumCircuit(2) circuit.append(TGate().control(), qargs=[0, 1]) arr1 = Operator(circuit).data arr2 = symb_CTGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mct(seed): """todo""" circuit = get_random_controlled(base_gate=TGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_ctdg(): """todo""" circuit = QuantumCircuit(2) circuit.append(TdgGate().control(), qargs=[0, 1]) arr1 = Operator(circuit).data arr2 = symb_CTdgGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mctdg(seed): """todo""" circuit = get_random_controlled(base_gate=TdgGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_cswap(): """todo""" arr1 = CSwapGate().to_matrix() arr2 = symb_CSwapGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mcswap(seed): """todo""" circuit = get_random_controlled(base_gate=SwapGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2) def test_ciswap(): """todo""" circuit = QuantumCircuit(3) circuit.append(iSwapGate().control(), qargs=[0, 1, 2]) arr1 = Operator(circuit).data arr2 = symb_CiSwapGate().to_numpy() assert numpy.allclose(arr1, arr2) @settings(deadline=None, max_examples=10) @given(seed=strategies.integers(min_value=0)) def test_mciswap(seed): """todo""" circuit = get_random_controlled(base_gate=iSwapGate(), seed=seed) arr1 = Operator(circuit).data arr2 = symb_Operator(circuit).to_numpy() assert numpy.allclose(arr1, arr2)
https://github.com/Qiskit-Partners/partners
Qiskit-Partners
import qiskit_qasm2 project = 'Qiskit OpenQASM 2 Tools' copyright = '2022, Jake Lishman' author = 'Jake Lishman' version = qiskit_qasm2.__version__ extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", ] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Document the docstring for the class and the __init__ method together. autoclass_content = "both" html_theme = 'alabaster' intersphinx_mapping = { "qiskit-terra": ("https://qiskit.org/documentation", None), }
https://github.com/DylanLi272/QiskitFinalProject
DylanLi272
from qiskit import BasicAer, Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, ExactEigensolver, NumPyEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA, L_BFGS_B, SLSQP from qiskit.aqua.components.optimizers import SPSA, TNC, POWELL, P_BFGS from qiskit.aqua.components.optimizers import NFT, NELDER_MEAD, GSLS, CG from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError from qiskit.providers.aer.noise.errors import pauli_error from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit.providers.aer.noise.errors import thermal_relaxation_error from qiskit.providers.aer import noise from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy import warnings IBMQ.load_account() provider = IBMQ.get_provider(group='open') backend = least_busy(provider.backends(simulator=False, operational=True)) import numpy as np import matplotlib.pyplot as plt from functools import partial inter_dist = 1.5108585 driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') # please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order #Classically solve for the lowest eigenvalue def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref backend = BasicAer.get_backend('statevector_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates # Classically solve for the lowest eigenvalue # This is used just to compare how well you VQE approximation is performing def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref counts = [] values = [] params = [] deviation = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) # Define your function for computing the qubit operations of LiH def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'): # Specify details of our molecule driver = PySCFDriver(atom='Li 0 0 0; H 0 0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis) # Compute relevant 1 and 2 body integrals. molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 nuclear_repulsion_energy = molecule.nuclear_repulsion_energy print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) # Please be aware that the idx here with respective to original idx freeze_list = [0,1,6,7] remove_list = [0,1,4,5] # negative number denotes the reverse order # Prepare full idx of freeze_list and remove_list # Convert all negative idx to positive num_spin_orbitals -= len(remove_list) # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list)//2 if len(remove_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) qubitOp = ferOp.mapping(map_type) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy = compute_LiH_qubitOp(map_type, inter_dist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_spin_orbitals, num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. RY_var_form = RY(qubitOp.num_qubits, depth=2) # Choose where to run/simulate our circuit quantum_instance = backend max_eval = 1000 # Choose the classical optimizer SPSA_optimizer = SPSA(max_eval) warnings.filterwarnings("ignore") SPSA_vqe = VQE(qubitOp, RY_var_form, SPSA_optimizer, callback=store_intermediate_result) SPSA_vqe_eigenvalue = np.real(SPSA_vqe.run(backend)['eigenvalue']) # Now compare the results of different compositions of your VQE algorithm! SPSA_vqe_result = np.real(energy_shift + SPSA_vqe_eigenvalue) print("==================================================") print('Reference value: {}'.format(ref)) print("SPSA VQE energy: ", SPSA_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("SPSA Reference Value Percent Error: " + str(abs((SPSA_vqe_eigenvalue-ref)/ref)*100) + "%") print("SPSA Energy Value Percent Error: " + str(np.real(abs((SPSA_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================")
https://github.com/DylanLi272/QiskitFinalProject
DylanLi272
from qiskit import BasicAer, Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, ExactEigensolver, NumPyEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA, L_BFGS_B, SLSQP from qiskit.aqua.components.optimizers import SPSA, TNC, POWELL, P_BFGS from qiskit.aqua.components.optimizers import NFT, NELDER_MEAD, GSLS, CG from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError from qiskit.providers.aer.noise.errors import pauli_error from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit.providers.aer.noise.errors import thermal_relaxation_error from qiskit.providers.aer import noise from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy import warnings IBMQ.load_account() provider = IBMQ.get_provider(group='open') backend = least_busy(provider.backends(simulator=False, operational=True)) import numpy as np import matplotlib.pyplot as plt from functools import partial inter_dist = 1.5108585 driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') # please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order #Classically solve for the lowest eigenvalue def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref backend = BasicAer.get_backend('statevector_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates # Classically solve for the lowest eigenvalue # This is used just to compare how well you VQE approximation is performing def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref counts = [] values = [] params = [] deviation = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) # Define your function for computing the qubit operations of LiH def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'): # Specify details of our molecule driver = PySCFDriver(atom='Li 0 0 0; H 0 0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis) # Compute relevant 1 and 2 body integrals. molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 nuclear_repulsion_energy = molecule.nuclear_repulsion_energy print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) # Please be aware that the idx here with respective to original idx freeze_list = [0,1,6,7] remove_list = [0,1,4,5] # negative number denotes the reverse order # Prepare full idx of freeze_list and remove_list # Convert all negative idx to positive num_spin_orbitals -= len(remove_list) # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list)//2 if len(remove_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) qubitOp = ferOp.mapping(map_type) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy map_type = 'parity' qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy = compute_LiH_qubitOp(map_type, inter_dist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_spin_orbitals, num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. RY_var_form = RY(qubitOp.num_qubits, depth=2) # Choose where to run/simulate our circuit quantum_instance = backend max_eval = 1000 # Choose the classical optimizer POWELL_optimizer = POWELL(max_eval) warnings.filterwarnings("ignore") POWELL_vqe = VQE(qubitOp, RY_var_form, POWELL_optimizer, callback=store_intermediate_result) POWELL_vqe_eigenvalue = np.real(POWELL_vqe.run(backend)['eigenvalue']) # Now compare the results of different compositions of your VQE algorithm! POWELL_vqe_result = np.real(energy_shift + POWELL_vqe_eigenvalue + nuclear_repulsion_energy) print("==================================================") print('Reference value: {}'.format(ref)) print("POWELL VQE energy: ", POWELL_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("POWELL Reference Value Percent Error: " + str(abs((POWELL_vqe_eigenvalue-ref)/ref)*100) + "%") print("POWELL Energy Value Percent Error: " + str(np.real(abs((POWELL_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================") pinter_d = [] pex_list = [] pv_list = [] peref_list = [] paref_list = [] for inter_dist in range(5, 41): inter_dist /= 10.0 pinter_d.append(inter_dist) print(inter_dist) qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy = compute_LiH_qubitOp(map_type, inter_dist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_spin_orbitals, num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. RY_var_form = RY(qubitOp.num_qubits, depth=2) # Choose where to run/simulate our circuit quantum_instance = backend max_eval = 1000 # Choose the classical optimizer POWELL_optimizer = POWELL(max_eval) warnings.filterwarnings("ignore") POWELL_vqe = VQE(qubitOp, RY_var_form, POWELL_optimizer, callback=store_intermediate_result) POWELL_vqe_eigenvalue = np.real(POWELL_vqe.run(backend)['eigenvalue']) shift = energy_shift + nuclear_repulsion_energy # Now compare the results of different compositions of your VQE algorithm! POWELL_vqe_result = np.real(shift + POWELL_vqe_eigenvalue) pex_list.append(molecule.hf_energy) pv_list.append(POWELL_vqe_result) peref_list.append(ref) paref_list.append(POWELL_vqe_eigenvalue) plt.figure(figsize=(15, 10)) plt.title('') #pv_list + 2*(min(pex_list)-pv_list) plt.plot(pinter_d, pex_list, 'b-', label='Exact Energy') plt.plot(pinter_d, pv_list, 'r-', label='VQE Energy') #plt.plot(inter_d, eref_list, 'g-', label='expected_ref') #plt.plot(inter_d, aref_list, 'y-', label='actual_ref') plt.xlabel('Interatomic Distance (Angstrom)') plt.ylabel('Energy') plt.legend() plt.show()
https://github.com/DylanLi272/QiskitFinalProject
DylanLi272
from qiskit import BasicAer, Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, ExactEigensolver, NumPyEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA, L_BFGS_B, SLSQP from qiskit.aqua.components.optimizers import SPSA, TNC, POWELL, P_BFGS from qiskit.aqua.components.optimizers import NFT, NELDER_MEAD, GSLS, CG from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError from qiskit.providers.aer.noise.errors import pauli_error from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit.providers.aer.noise.errors import thermal_relaxation_error from qiskit.providers.aer import noise from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy import warnings IBMQ.load_account() provider = IBMQ.get_provider(group='open') backend = least_busy(provider.backends(simulator=False, operational=True)) import numpy as np import matplotlib.pyplot as plt from functools import partial distances = [] for inter_dist in range(5, 41): inter_dist /= 10.0 distances.append(inter_dist) map_type = 'parity' driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') # please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order #Classically solve for the lowest eigenvalue def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref backend = BasicAer.get_backend('statevector_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates # Classically solve for the lowest eigenvalue # This is used just to compare how well you VQE approximation is performing def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref def reset_values(): counts = [] values = [] params = [] deviation = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) # Define your function for computing the qubit operations of LiH def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'): # Specify details of our molecule driver = PySCFDriver(atom='Li 0 0 0; H 0 0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis) # Compute relevant 1 and 2 body integrals. molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 nuclear_repulsion_energy = molecule.nuclear_repulsion_energy print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) # Please be aware that the idx here with respective to original idx freeze_list = [0,1,6,7] remove_list = [0,1,4,5] # negative number denotes the reverse order # Prepare full idx of freeze_list and remove_list # Convert all negative idx to positive num_spin_orbitals -= len(remove_list) # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list)//2 if len(remove_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) qubitOp = ferOp.mapping(map_type) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy for inter_dist in distances: qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy = compute_LiH_qubitOp(map_type, inter_dist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_spin_orbitals, num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. RY_var_form = RY(qubitOp.num_qubits, depth=2) # Choose where to run/simulate our circuit quantum_instance = backend max_eval = 1000 # Choose the classical optimizer POWELL_optimizer = POWELL(max_eval) warnings.filterwarnings("ignore") COBYLA_vqe = VQE(qubitOp, RY_var_form, SPSA_optimizer, callback=store_intermediate_result) COBYLA_vqe_eigenvalue = np.real(COBYLA_vqe.run(backend)['eigenvalue']) list_of_values.append(values) reset_values() COBYLA_vqe_result = np.real(energy_shift + COBYLA_vqe_eigenvalue) print("==================================================") print('Reference value: {}'.format(ref)) print("COBYLA VQE value: ", COBYLA_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("Reference Value Percent Error: " + str(abs((COBYLA_vqe_eigenvalue-ref)/ref)*100) + "%") print("Energy Value Percent Error: " + str(np.real(abs((COBYLA_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================") POWELL_vqe = VQE(qubitOp, RY_var_form, POWELL_optimizer) POWELL_vqe_eigenvalue = np.real(POWELL_vqe.run(backend)['eigenvalue']) list_of_values.append(values) reset_values() POWELL_vqe_result = np.real(energy_shift + POWELL_vqe_eigenvalue) print('Reference value: {}'.format(ref)) print("POWELL VQE value: ", POWELL_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("Reference Value Percent Error: " + str(abs((POWELL_vqe_eigenvalue-ref)/ref)*100) + "%") print("Energy Value Percent Error: " + str(np.real(abs((POWELL_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================") SPSA_vqe = VQE(qubitOp, RY_var_form, SPSA_optimizer, callback=store_intermediate_result) SPSA_vqe_eigenvalue = np.real(SPSA_vqe.run(backend)['eigenvalue']) list_of_values.append(values) reset_values() # Now compare the results of different compositions of your VQE algorithm! SPSA_vqe_result = np.real(energy_shift + SPSA_vqe_eigenvalue) print('Reference value: {}'.format(ref)) print("SPSA VQE energy: ", SPSA_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("SPSA Reference Value Percent Error: " + str(abs((SPSA_vqe_eigenvalue-ref)/ref)*100) + "%") print("SPSA Energy Value Percent Error: " + str(np.real(abs((SPSA_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================") TNC_vqe = VQE(qubitOp, RY_var_form, TNC_optimizer) TNC_vqe_eigenvalue = np.real(TNC_vqe.run(backend)['eigenvalue']) list_of_values.append(values) reset_values() TNC_vqe_result = np.real(energy_shift + TNC_vqe_eigenvalue) print('Reference value: {}'.format(ref)) print("TNC VQE energy: ", TNC_vqe_eigenvalue) print("HF energy: {}".format(molecule.hf_energy)) print("TNC Reference Value Percent Error: " + str(abs((TNC_vqe_eigenvalue-ref)/ref)*100) + "%") print("TNC Energy Value Percent Error: " + str(np.real(abs((TNC_vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") print("==================================================") graph1 = plt.figure(figsize=(15,10)) names = ['COBYLA', 'POWELL', 'SPSA', 'TNC'] colors = ['r','g','b','y'] plt.xlabel('Evaluation Count') plt.ylabel('Logscale Error Difference from Reference Value') plt.title('Logscael Error of VQE Procedure: RY') plt.yscale('log') iterations = [] count = 0 for i in range(1000): iterations.append(i) COBYLA = [] SLSQP = [] SPSA = [] TNC = [] for i in iterations: COBYLA.append(((list_of_values[0][count] - ref)/ref)) count += 1 for i in iterations: SLSQP.append(((list_of_values[1][count]-ref)/ref)) count += 1 for i in iterations: SPSA.append(((list_of_values[2][count]-ref)/ref)) count += 1 for i in iterations: TNC.append(((list_of_values[3][count]-ref)/ref)) count += 1 plt.plot(iterations, COBYLA, 'r--', iterations, SLSQP, 'bs--', iterations, SPSA, 'g^--', iterations, TNC, 'y*--') plt.legend(names) graph2 = plt.figure(figsize=(15,10)) names = ['COBYLA', 'POWELL', 'SPSA', 'TNC'] colors = ['r','g','b','y'] plt.xlabel('Evaluation Count') plt.ylabel('Energy Minimization for Various Optimizers') plt.title('Energy Convergence VQE Procedure: RY') iterations = [] count = 0 for i in range(1000): iterations.append(i) COBYLA = [] SLSQP = [] SPSA = [] TNC = [] for i in iterations: COBYLA.append(energy_shift + list_of_values[0][count]) count += 1 for i in iterations: SLSQP.append(energy_shift + list_of_values[1][count]) count += 1 for i in iterations: SPSA.append(energy_shift + list_of_values[2][count]) count += 1 for i in iterations: TNC.append(energy_shift + list_of_values[3][count]) count += 1 plt.plot(iterations, COBYLA, 'r--', iterations, SLSQP, 'bs--', iterations, SPSA, 'g^--', iterations, TNC, 'y*--') plt.legend(names)
https://github.com/DylanLi272/QiskitFinalProject
DylanLi272
from qiskit import BasicAer, Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, ExactEigensolver, NumPyEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA, CRS from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError from qiskit.providers.aer.noise.errors import pauli_error from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit.providers.aer.noise.errors import thermal_relaxation_error from qiskit.providers.aer import noise from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy import warnings IBMQ.load_account() provider = IBMQ.get_provider(group='open') backend = least_busy(provider.backends(simulator=False, operational=True)) import numpy as np import matplotlib.pyplot as plt from functools import partial inter_dist = 1.5108585 driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') # please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order #Classically solve for the lowest eigenvalue def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref backend = BasicAer.get_backend('statevector_simulator') #Define our noise model based on the ibmq_essex chip chip_name = 'ibmq_essex' device = provider.get_backend(chip_name) coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(device.properties()) basis_gates = noise_model.basis_gates # Classically solve for the lowest eigenvalue # This is used just to compare how well you VQE approximation is performing def exact_solver(qubitOp): ee = ExactEigensolver(qubitOp) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref)) return ref counts = [] values = [] params = [] deviation = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) # Define your function for computing the qubit operations of LiH def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'): # Specify details of our molecule driver = PySCFDriver(atom='Li 0 0 0; H 0 0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis) # Compute relevant 1 and 2 body integrals. molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 nuclear_repulsion_energy = molecule.nuclear_repulsion_energy print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) # Please be aware that the idx here with respective to original idx freeze_list = [0,1,6,7] remove_list = [0,1,4,5] # negative number denotes the reverse order # Prepare full idx of freeze_list and remove_list # Convert all negative idx to positive num_spin_orbitals -= len(remove_list) # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list)//2 if len(freeze_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) qubitOp = ferOp.mapping(map_type) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy map_type = "parity" qubitOp, num_spin_orbitals, num_particles, qubit_reduction, molecule, energy_shift, nuclear_repulsion_energy = compute_LiH_qubitOp(map_type, inter_dist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp) # Specify your initial state init_state = HartreeFock(num_spin_orbitals, num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. UCCSD_var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=map_type, initial_state=init_state, two_qubit_reduction=qubit_reduction, reps=2) # Choose where to run/simulate our circuit quantum_instance = backend max_eval = 10000 # Choose the classical optimizer optimizer = SPSA(max_eval) warnings.filterwarnings("ignore") vqe = VQE(qubitOp, UCCSD_var_form, optimizer, callback=store_intermediate_result) vqe_eigenvalue = np.real(vqe.run(backend)['eigenvalue']) # Now compare the results of different compositions of your VQE algorithm! print("VQE value: ", vqe_eigenvalue) vqe_result = np.real(energy_shift + vqe_eigenvalue) print("VQE energy: ", vqe_result) print("HF energy: {}".format(molecule.hf_energy)) print("Reference Value Percent Error: " + str(abs((vqe_eigenvalue-ref)/ref)*100) + "%") print("Energy Value Percent Error: " + str(np.real(abs((vqe_result-molecule.hf_energy)/molecule.hf_energy))*100) + "%") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
import warnings warnings.filterwarnings("ignore") from matplotlib import pyplot as plt import numpy as np from qiskit.circuit.library import TwoLocal from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter import sys sys.path.append("../../") from entanglement_forging import EntanglementForgedGroundStateSolver from entanglement_forging import EntanglementForgedConfig 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=molecule) problem = ElectronicStructureProblem(driver) problem.second_q_ops() converter = QubitConverter(JordanWignerMapper()) from qiskit_nature.algorithms.ground_state_solvers import ( GroundStateEigensolver, NumPyMinimumEigensolverFactory, ) solver = GroundStateEigensolver( converter, NumPyMinimumEigensolverFactory(use_default_filter_criterion=False) ) result = solver.solve(problem) print("Classical energy = ", result.total_energies[0]) bitstrings = [[1, 0], [0, 1]] ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1) ansatz.draw() from qiskit import Aer backend = Aer.get_backend("statevector_simulator") config = EntanglementForgedConfig( backend=backend, maxiter=200, initial_params=[0, 0.5 * np.pi] ) calc = EntanglementForgedGroundStateSolver( qubit_converter=converter, ansatz=ansatz, bitstrings_u=bitstrings, config=config ) res = calc.solve(problem) res print("Energies (from only one paramset in each iteration):") plt.plot([e[0] for e in res.get_energies_history()]) plt.plot([e[1] for e in res.get_energies_history()[0:-1]]) plt.show() print("Schmidts (from only one paramset in each iteration):") plt.plot([s[0] for s in res.get_schmidts_history()]) plt.show() print("Parameters (from only one paramset in each iteration):") plt.plot([p[0] for p in res.get_parameters_history()]) plt.plot([p[1] for p in res.get_parameters_history()[0:-1]]) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
import warnings warnings.filterwarnings("ignore") import numpy as np from matplotlib import pyplot as plt from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit import Aer import sys sys.path.append("../../") from entanglement_forging import EntanglementForgedGroundStateSolver from entanglement_forging import EntanglementForgedConfig radius_1 = 0.958 # position for the first H atom radius_2 = 0.958 # position for the second H atom thetas_in_deg = 104.478 # bond angles. H1_x = radius_1 H2_x = radius_2 * np.cos(np.pi / 180 * thetas_in_deg) H2_y = radius_2 * np.sin(np.pi / 180 * thetas_in_deg) molecule = Molecule( geometry=[ ["O", [0.0, 0.0, 0.0]], ["H", [H1_x, 0.0, 0.0]], ["H", [H2_x, H2_y, 0.0]], ], charge=0, multiplicity=1, ) driver = PySCFDriver.from_molecule(molecule=molecule, basis="sto6g") problem = ElectronicStructureProblem(driver) converter = QubitConverter(JordanWignerMapper()) from qiskit_nature.algorithms.ground_state_solvers import ( GroundStateEigensolver, NumPyMinimumEigensolverFactory, ) solver = GroundStateEigensolver( converter, NumPyMinimumEigensolverFactory(use_default_filter_criterion=False) ) result = solver.solve(problem) print("Classical energy = ", result.total_energies[0]) orbitals_to_reduce = [0, 3] from entanglement_forging import reduce_bitstrings bitstrings = [[1, 1, 1, 1, 1, 0, 0], [1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 1, 1, 0]] reduced_bitstrings = reduce_bitstrings(bitstrings, orbitals_to_reduce) print(f"Bitstrings: {bitstrings}") print(f"Bitstrings after orbital reduction: {reduced_bitstrings}") from qiskit.circuit import Parameter, QuantumCircuit theta = Parameter("θ") hop_gate = QuantumCircuit(2, name="Hop gate") hop_gate.h(0) hop_gate.cx(1, 0) hop_gate.cx(0, 1) hop_gate.ry(-theta, 0) hop_gate.ry(-theta, 1) hop_gate.cx(0, 1) hop_gate.h(0) hop_gate.draw() theta_1, theta_2, theta_3, theta_4 = ( Parameter("θ1"), Parameter("θ2"), Parameter("θ3"), Parameter("θ4"), ) ansatz = QuantumCircuit(5) ansatz.append(hop_gate.to_gate({theta: theta_1}), [0, 1]) ansatz.append(hop_gate.to_gate({theta: theta_2}), [3, 4]) ansatz.append(hop_gate.to_gate({theta: 0}), [1, 4]) ansatz.append(hop_gate.to_gate({theta: theta_3}), [0, 2]) ansatz.append(hop_gate.to_gate({theta: theta_4}), [3, 4]) ansatz.draw("text", justify="right", fold=-1) from entanglement_forging import Log Log.VERBOSE = False backend = Aer.get_backend("statevector_simulator") config = EntanglementForgedConfig( backend=backend, maxiter=350, spsa_c0=20 * np.pi, initial_params=[0, 0, 0, 0] ) calc = EntanglementForgedGroundStateSolver( qubit_converter=converter, ansatz=ansatz, bitstrings_u=reduced_bitstrings, config=config, orbitals_to_reduce=orbitals_to_reduce, ) res = calc.solve(problem) res print("Energies (from only one paramset in each iteration):") plt.plot([e[0] for e in res.get_energies_history()]) plt.show() print("Schmidts (from only one paramset in each iteration):") plt.plot([s[0] for s in res.get_schmidts_history()]) plt.show() print("Parameters (from only one paramset in each iteration):") plt.plot([p[0] for p in res.get_parameters_history()]) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
import warnings warnings.filterwarnings("ignore") from matplotlib import pyplot as plt import numpy as np from qiskit.circuit.library import TwoLocal from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter import sys sys.path.append("../../") from entanglement_forging import ( EntanglementForgedConfig, EntanglementForgedDriver, EntanglementForgedGroundStateSolver, ) # Coefficients that define the one-body terms of the Hamiltonain hcore = np.array([[-1.12421758, -0.9652574], [-0.9652574, -1.12421758]]) # Coefficients that define the two-body terms of the Hamiltonian mo_coeff = np.array([[0.54830202, 1.21832731], [0.54830202, -1.21832731]]) # Coefficients for the molecular orbitals eri = np.array( [ [ [[0.77460594, 0.44744572], [0.44744572, 0.57187698]], [[0.44744572, 0.3009177], [0.3009177, 0.44744572]], ], [ [[0.44744572, 0.3009177], [0.3009177, 0.44744572]], [[0.57187698, 0.44744572], [0.44744572, 0.77460594]], ], ] ) driver = EntanglementForgedDriver( hcore=hcore, mo_coeff=mo_coeff, eri=eri, num_alpha=1, num_beta=1, nuclear_repulsion_energy=0.7199689944489797, ) problem = ElectronicStructureProblem(driver) problem.second_q_ops() converter = QubitConverter(JordanWignerMapper()) bitstrings = [[1, 0], [0, 1]] ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1) ansatz.draw() from qiskit import Aer backend = Aer.get_backend("statevector_simulator") config = EntanglementForgedConfig( backend=backend, maxiter=200, initial_params=[0, 0.5 * np.pi] ) calc = EntanglementForgedGroundStateSolver( qubit_converter=converter, ansatz=ansatz, bitstrings_u=bitstrings, config=config ) res = calc.solve(problem) res print("Energies (from only one paramset in each iteration):") plt.plot([e[0] for e in res.get_energies_history()]) plt.plot([e[1] for e in res.get_energies_history()[0:-1]]) plt.show() print("Schmidts (from only one paramset in each iteration):") plt.plot([s[0] for s in res.get_schmidts_history()]) plt.show() print("Parameters (from only one paramset in each iteration):") plt.plot([p[0] for p in res.get_parameters_history()]) plt.plot([p[1] for p in res.get_parameters_history()[0:-1]]) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
import warnings warnings.filterwarnings("ignore") from matplotlib import pyplot as plt import numpy as np from qiskit.circuit.library import TwoLocal from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter import sys sys.path.append("../../") from entanglement_forging import EntanglementForgedGroundStateSolver from entanglement_forging import EntanglementForgedConfig # We start by setting up the chemical problem. 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, basis="sto3g") problem = ElectronicStructureProblem(driver) problem.second_q_ops() converter = QubitConverter(JordanWignerMapper()) # Prepare the bitstrings and the ansatz bitstrings = [[1, 0], [0, 1]] ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1) from qiskit import Aer backend = Aer.get_backend("qasm_simulator") config = EntanglementForgedConfig(backend=backend, copysample_job_size=100) calc = EntanglementForgedGroundStateSolver( qubit_converter=converter, ansatz=ansatz, bitstrings_u=bitstrings, config=config ) res = calc.solve(problem) res print("Energies (from only one paramset in each iteration):") plt.plot([e[0] for e in res.get_energies_history()]) plt.show() print("Schmidts (from only one paramset in each iteration):") plt.plot([s[0] for s in res.get_schmidts_history()]) plt.show() print("Parameters (from only one paramset in each iteration):") plt.plot([p[0] for p in res.get_parameters_history()]) plt.show() res import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
import warnings warnings.filterwarnings("ignore") from matplotlib import pyplot as plt import numpy as np from qiskit.circuit.library import TwoLocal from qiskit_nature.drivers import UnitsType, Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit import Aer import sys sys.path.append("../../") from entanglement_forging import EntanglementForgedVQE from entanglement_forging import EntanglementForgedGroundStateSolver from entanglement_forging import EntanglementForgedConfig distances = np.arange(0.3, 1.5, 0.1) molecules = [] for dist in distances: molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, dist]]], charge=0, multiplicity=1, ) molecules = molecules + [molecule] bitstrings = [[1, 0], [0, 1]] ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1) backend = Aer.get_backend("statevector_simulator") converter = QubitConverter(JordanWignerMapper()) config = EntanglementForgedConfig(backend=backend, maxiter=100) calc = EntanglementForgedGroundStateSolver( qubit_converter=converter, ansatz=ansatz, bitstrings_u=bitstrings, config=config ) energies = [] for molecule, distance in zip(molecules, distances): driver = PySCFDriver.from_molecule(molecule, basis="sto3g") problem = ElectronicStructureProblem(driver) problem.second_q_ops() res = calc.solve(problem) energies_history = res.get_energies_history() energy = [None] if len(energies_history) > 0: energy = res.get_energies_history()[-1] energies = energies + energy print(f"Distance = {distance}, Energy = {energy[0]}") plt.plot(distances, energies) plt.xlabel("Atomic distance (Angstrom)") plt.ylabel("Energy") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# 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. """Ground state computation using a minimum eigensolver with entanglement forging.""" import time import warnings from typing import List, Iterable, Union, Dict, Optional, Tuple import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import MinimumEigensolver from qiskit.circuit import Instruction from qiskit.opflow import OperatorBase, PauliSumOp from qiskit.quantum_info import Statevector from qiskit.result import Result from qiskit_nature import ListOrDictType from qiskit_nature.algorithms.ground_state_solvers import ( GroundStateSolver, MinimumEigensolverFactory, ) from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.operators.second_quantization import SecondQuantizedOp from qiskit_nature.problems.second_quantization import BaseProblem from qiskit_nature.problems.second_quantization.electronic import ( ElectronicStructureProblem, ) from entanglement_forging.core.classical_energies import ClassicalEnergies from entanglement_forging.core.forged_operator import ForgedOperator from entanglement_forging.core.entanglement_forged_config import ( EntanglementForgedConfig, ) from entanglement_forging.core.wrappers.entanglement_forged_vqe import ( EntanglementForgedVQE, ) from entanglement_forging.core.wrappers.entanglement_forged_vqe_result import ( EntanglementForgedVQEResult, OptimalParams, ) from entanglement_forging.utils.log import Log # pylint: disable=too-many-arguments,protected-access class EntanglementForgedGroundStateSolver(GroundStateSolver): """Ground state computation using a minimum solver with entanglement forging. Attr: transformation: Qubit Operator Transformation ansatz (Two): orbitals_to_reduce (list of int): Orbital list to be frozen or removed. """ def __init__( self, qubit_converter: QubitConverter, ansatz: QuantumCircuit, bitstrings_u: Iterable[Iterable[int]], config: EntanglementForgedConfig, bitstrings_v: Iterable[Iterable[int]] = None, orbitals_to_reduce: bool = None, ): # Ensure the bitstrings are well formed if any(len(bitstrings_u[0]) != len(bitstr) for bitstr in bitstrings_u): raise ValueError("All U bitstrings must be the same length.") if bitstrings_v: if len(bitstrings_u) != len(bitstrings_v): raise ValueError( "The same number of bitstrings should be passed for U and V." ) if len(bitstrings_u[0]) != len(bitstrings_v[0]): raise ValueError("Bitstrings for U and V should be the same length.") if any(len(bitstrings_v[0]) != len(bitstr) for bitstr in bitstrings_v): raise ValueError("All V bitstrings must be the same length.") # Initialize the GroundStateSolver super().__init__(qubit_converter) # Set which orbitals to ignore when calculating the Hamiltonian if orbitals_to_reduce is None: orbitals_to_reduce = [] self.orbitals_to_reduce = orbitals_to_reduce # Set private class fields self._ansatz = ansatz self._bitstrings_u = bitstrings_u self._config = config # pylint: disable=arguments-differ # Prevent unnecessary duplication of circuits if subsystems are identical if (bitstrings_v is None) or (bitstrings_u == bitstrings_v): self._bitstrings_v = [] else: self._bitstrings_v = bitstrings_v # pylint: disable=arguments-differ def solve( self, problem: ElectronicStructureProblem, ) -> EntanglementForgedVQEResult: """Compute Ground State properties of chemical problem. Args: problem: a qiskit_nature.problems.second_quantization .electronic.electronic_structure_problem object. aux_operators: additional auxiliary operators to evaluate **kwargs: keyword args to pass to solver Raises: ValueError: If the transformation is not of the type FermionicTransformation. ValueError: If the qubit mapping is not of the type JORDAN_WIGNER. Returns: An eigenstate result. """ if not isinstance(problem, ElectronicStructureProblem): raise ValueError( "This version only supports an ElectronicStructureProblem." ) if not isinstance(self.qubit_converter.mapper, JordanWignerMapper): raise ValueError("This version only supports the JordanWignerMapper.") start_time = time.time() problem.driver.run() # Decompose the Hamiltonian operators into a form appropraite for EF forged_operator = ForgedOperator( problem, self.orbitals_to_reduce, self._calculate_tensor_cross_terms() ) # Calculate energies clasically using pySCF classical_energies = ClassicalEnergies(problem, self.orbitals_to_reduce) self._solver = EntanglementForgedVQE( ansatz=self._ansatz, bitstrings_u=self._bitstrings_u, bitstrings_v=self._bitstrings_v, config=self._config, forged_operator=forged_operator, classical_energies=classical_energies, ) result = self._solver.compute_minimum_eigenvalue(forged_operator.h_1_op) elapsed_time = time.time() - start_time Log.log(f"VQE for this problem took {elapsed_time} seconds") res = EntanglementForgedVQEResult( parameters_history=self._solver._paramsets_each_iteration, energies_history=self._solver._energy_each_iteration_each_paramset, schmidts_history=self._solver._schmidt_coeffs_each_iteration_each_paramset, energy_std_each_parameter_set=self._solver.energy_std_each_parameter_set, energy_offset=self._solver._add_this_to_energies_displayed, eval_count=self._solver._eval_count, ) res.combine(result) return res def _calculate_tensor_cross_terms(self) -> bool: """ Determine whether circuits should be generated to account for the special superposition terms needed when bn==bm for two bitstrings within a given subsystem's (U or V) bitstring list. """ bsu = self._bitstrings_u bsv = self._bitstrings_u # Search for any duplicate bitstrings within the subsystem lists for i, bu1 in enumerate(bsu): for j, bu2 in enumerate(bsu): if i == j: continue if bu1 == bu2: return True for i, bv1 in enumerate(bsv): for j, bv2 in enumerate(bsv): if i == j: continue if bv1 == bv2: return True return False def returns_groundstate(self) -> bool: """Whether this class returns only the ground state energy or also the ground state itself. Returns: True, if this class also returns the ground state in the results object. False otherwise. """ return True def evaluate_operators( self, state: Union[ str, dict, Result, list, np.ndarray, Statevector, QuantumCircuit, Instruction, OperatorBase, ], operators: Union[PauliSumOp, OperatorBase, list, dict], ) -> Union[float, Iterable[float], Dict[str, Iterable[float]]]: """Evaluates additional operators at the given state.""" warnings.warn( "evaluate_operators not implemented for " "forged EntanglementForgedGroundStateSolver." ) return [] @property def solver(self) -> Union[MinimumEigensolver, MinimumEigensolverFactory]: """Returns the minimum eigensolver or factory.""" return self._solver def get_qubit_operators( self, problem: BaseProblem, aux_operators: Optional[ ListOrDictType[Union[SecondQuantizedOp, PauliSumOp]] ] = None, ) -> Tuple[PauliSumOp, Optional[ListOrDictType[PauliSumOp]]]: """Gets the operator and auxiliary operators, and transforms the provided auxiliary operators""" raise NotImplementedError( "get_qubit_operators has not been implemented in EntanglementForgedGroundStateEigensolver" )
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# 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. """Entanglement forged VQE.""" import datetime import time import warnings from typing import Iterable, Tuple, Callable, Union import numpy as np from qiskit import transpile, QuantumCircuit from qiskit.algorithms import VQE from qiskit.utils.mitigation import complete_meas_cal from qiskit.quantum_info import Pauli from qiskit.utils import QuantumInstance from qiskit.opflow import OperatorBase from entanglement_forging.core.entanglement_forged_config import ( EntanglementForgedConfig, ) from entanglement_forging.core.forged_operator import ForgedOperator from entanglement_forging.core.classical_energies import ClassicalEnergies from entanglement_forging.core.wrappers.entanglement_forged_vqe_result import ( DataResults, Bootstrap, AuxiliaryResults, ) from entanglement_forging.utils.bootstrap_result import resample_result from entanglement_forging.utils.copysample_circuits import ( copysample_circuits, combine_copysampled_results, ) from entanglement_forging.utils.forging_subroutines import ( prepare_circuits_to_execute, make_stateprep_circuits, eval_forged_op_with_result, get_optimizer_instance, ) from entanglement_forging.utils.generic_execution_subroutines import execute_with_retry from entanglement_forging.utils.legacy.op_converter import ( to_tpb_grouped_weighted_pauli_operator, ) from entanglement_forging.utils.legacy.tpb_grouped_weighted_pauli_operator import ( TPBGroupedWeightedPauliOperator, ) from entanglement_forging.utils.legacy.weighted_pauli_operator import ( WeightedPauliOperator, ) from entanglement_forging.utils.log import Log from entanglement_forging.utils.meas_mit_fitters_faster import CompleteMeasFitter from entanglement_forging.utils.pseudorichardson import make_pseudorichardson_circuits # pylint: disable=too-many-branches,too-many-arguments,too-many-locals,too-many-instance-attributes,too-many-statements class EntanglementForgedVQE(VQE): """A class for Entanglement Forged VQE <https://arxiv.org/abs/2104.10220>.""" def __init__( self, ansatz: QuantumCircuit, bitstrings_u: Iterable[Iterable[int]], config: EntanglementForgedConfig, forged_operator: ForgedOperator, classical_energies: ClassicalEnergies, bitstrings_v: Iterable[Iterable[int]] = None, ): """Initialize the EntanglementForgedVQE class.""" if ansatz.num_qubits != len(bitstrings_u[0]): raise ValueError( "The number of qubits in ansatz does " "not match the number of bits in reduced_bitstrings." ) if any(len(bitstrings_u[0]) != len(bitstr) for bitstr in bitstrings_u): raise ValueError("All U bitstrings must be the same length.") if bitstrings_v: if len(bitstrings_u) != len(bitstrings_v): raise ValueError( "The same number of bitstrings should be passed for U and V." ) if len(bitstrings_u[0]) != len(bitstrings_v[0]): raise ValueError("Bitstrings for U and V should be the same length.") if any(len(bitstrings_v[0]) != len(bitstr) for bitstr in bitstrings_v): raise ValueError("All V bitstrings must be the same length.") super().__init__( ansatz=ansatz, optimizer=get_optimizer_instance(config), initial_point=config.initial_params, max_evals_grouped=config.max_evals_grouped, callback=None, ) # Prevent unnecessary duplication if subsystems are equivalent if (bitstrings_v is None) or (bitstrings_u == bitstrings_v): self.bitstrings_v = [] else: self.bitstrings_v = bitstrings_v self.ansatz = ansatz self.config = config self._energy_each_iteration_each_paramset = [] self._paramsets_each_iteration = [] self._schmidt_coeffs_each_iteration_each_paramset = [] self._zero_noise_extrap = config.zero_noise_extrap self.bitstrings_u = bitstrings_u self._bitstrings_s_u = np.asarray(bitstrings_u) # Make circuits which prepare states U|b_n_u> and U|phi^p_nm_u> ( self._tensor_prep_circuits_u, self._superpos_prep_circuits_u, hybrid_superpos_coeffs_u, ) = make_stateprep_circuits( bitstrings_u, config.fix_first_bitstring, suffix="u" ) self._tensor_prep_circuits_v = [] self._superpos_prep_circuits_v = [] hybrid_superpos_coeffs_v = [] self._bitstrings_s_v = np.array([]) if self.bitstrings_v: # Make circuits which prepare states V|b_n_v> and V|phi^p_nm_v> # Where U = V but bitstring |b_n_v> does not necessarily equal |b_n_u> self._bitstrings_s_v = np.asarray(bitstrings_v) ( self._tensor_prep_circuits_v, self._superpos_prep_circuits_v, hybrid_superpos_coeffs_v, ) = make_stateprep_circuits( bitstrings_v, config.fix_first_bitstring, suffix="v" ) hybrid_superpos_coeffs_u.update(hybrid_superpos_coeffs_v) self._hybrid_superpos_coeffs = hybrid_superpos_coeffs_u self._iteration_start_time = np.nan self._running_estimate_of_schmidts = np.array( [1.0] + [0.1] * (len(self._bitstrings_s_u) - 1) ) self._running_estimate_of_schmidts /= np.linalg.norm( self._running_estimate_of_schmidts ) self.copysample_job_size = config.copysample_job_size self._backend = config.backend self.quantum_instance = QuantumInstance(backend=self._backend) self._initial_layout = config.qubit_layout self._shots = config.shots self._meas_error_mit = config.meas_error_mit self._meas_error_shots = config.meas_error_shots self._meas_error_refresh_period_minutes = ( config.meas_error_refresh_period_minutes ) self._meas_error_refresh_timestamp = None self._coupling_map = self._backend.configuration().coupling_map self._meas_fitter = None self._bootstrap_trials = config.bootstrap_trials self._no_bs0_circuits = config.fix_first_bitstring self._rep_delay = config.rep_delay self.forged_operator = forged_operator self._add_this_to_energies_displayed = classical_energies.shift self._hf_energy = classical_energies.HF self.aux_results: Iterable[Tuple[str, AuxiliaryResults]] = [] self.parameter_sets = [] self.energy_mean_each_parameter_set = [] self.energy_std_each_parameter_set = [] # Paramters for get_energy_evaluation. Moved them here to match parent function signature self._shots_multiplier = 1 self._bootstrap_trials = 0 statevector_sims = ["aer_simulator_statevector", "statevector_simulator"] if self._backend.name() in statevector_sims: self._is_sv_sim = True else: self._is_sv_sim = False # Load the two circuit generation operations self._pauli_names_for_tensor_states = None self._pauli_names_for_superpos_states = None self._w_ij_tensor_states = None self._w_ab_superpos_states = None self._op_for_generating_tensor_circuits = None self._op_for_generating_superpos_circuits = None self._load_ops() @property def shots_multiplier(self): """Return the shots multiplier.""" return self._shots_multiplier @shots_multiplier.setter def shots_multiplier(self, multiplier): """Set the shots multiplier.""" self._shots_multiplier = multiplier @property def bootstrap_trials(self): """Return the bootstrap trials.""" return self._bootstrap_trials @bootstrap_trials.setter def bootstrap_trials(self, trials): """Set the bootstrap trials.""" self._bootstrap_trials = trials def _load_ops(self): # Get the weighted Pauli deconstruction of the operator ( pauli_names_for_tensor_states, pauli_names_for_superpos_states, w_ij_tensor_states, w_ab_superpos_states, ) = self.forged_operator.construct() self._pauli_names_for_tensor_states = pauli_names_for_tensor_states self._pauli_names_for_superpos_states = pauli_names_for_superpos_states self._w_ij_tensor_states = w_ij_tensor_states self._w_ab_superpos_states = w_ab_superpos_states op_for_generating_tensor_circuits = to_tpb_grouped_weighted_pauli_operator( WeightedPauliOperator( paulis=[ [1, Pauli(pname)] for pname in self._pauli_names_for_tensor_states ] ), TPBGroupedWeightedPauliOperator.sorted_grouping, ) if len(self._pauli_names_for_superpos_states) > 0: op_for_generating_superpos_circuits = ( to_tpb_grouped_weighted_pauli_operator( WeightedPauliOperator( paulis=[ [1, Pauli(pname)] for pname in self._pauli_names_for_superpos_states ] ), TPBGroupedWeightedPauliOperator.sorted_grouping, ) ) else: op_for_generating_superpos_circuits = None self._op_for_generating_tensor_circuits = op_for_generating_tensor_circuits self._op_for_generating_superpos_circuits = op_for_generating_superpos_circuits def get_energy_evaluation( self, operator: OperatorBase, return_expectation: bool = False ) -> Callable[[np.ndarray], Union[float, Iterable[float]]]: if self._is_sv_sim: self._shots_multiplier = 1 ansatz_params = self.ansatz.parameters _, expectation = self.construct_expectation( ansatz_params, operator, return_expectation=True ) def energy_evaluation(parameters): Log.log("------ new iteration energy evaluation -----") # num_parameter_sets = len(parameters) // self.ansatz.num_parameters # parameter_sets = np.split(parameters, num_parameter_sets) parameter_sets = np.reshape(parameters, (-1, self.ansatz.num_parameters)) new_iteration_start_time = time.time() Log.log( "duration of last iteration:", new_iteration_start_time - self._iteration_start_time, ) self._iteration_start_time = new_iteration_start_time Log.log("Parameter sets:", parameter_sets) # Compute the expectation value of the forged operator with respect # to the ansatz at the given parameters eval_forged_result = self._evaluate_forged_operator( parameter_sets=parameter_sets, hf_value=self._hf_energy, add_this_to_mean_values_displayed=self._add_this_to_energies_displayed, shots_multiplier=self._shots_multiplier, bootstrap_trials=self._bootstrap_trials, ) ( energy_mean_each_parameter_set, bootstrap_means_each_parameter_set, energy_mean_raw_each_parameter_set, energy_mean_sv_each_parameter_set, schmidt_coeffs_each_parameter_set, schmidt_coeffs_raw_each_parameter_set, schmidt_coeffs_sv_each_parameter_set, ) = eval_forged_result self._schmidt_coeffs_each_iteration_each_paramset.append( schmidt_coeffs_each_parameter_set ) # TODO Not Implemented # pylint: disable=fixme energy_std_each_parameter_set = [0] * len(energy_mean_each_parameter_set) # TODO Not Implemented # pylint: disable=fixme energy_std_raw_each_parameter_set = [0] * len( energy_mean_each_parameter_set ) energy_std_sv_each_parameter_set = [0] * len(energy_mean_each_parameter_set) self._energy_each_iteration_each_paramset.append( energy_mean_each_parameter_set ) self._paramsets_each_iteration.append(parameter_sets) timestamp_string = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") # additional results for params, bootstrap_means in zip( parameter_sets, bootstrap_means_each_parameter_set ): self.aux_results.append( ( "bootstrap", Bootstrap( eval_count=self._eval_count, eval_timestamp=timestamp_string, parameters=params, bootstrap_values=[ v + self._add_this_to_energies_displayed for v in bootstrap_means ], ), ) ) data_titles = ["data", "data_noextrapolation", "data_statevec"][:-1] for ( filename, energies_each_paramset, stds_each_paramset, schmidts_each_paramset, ) in zip( data_titles, [ energy_mean_each_parameter_set, energy_mean_raw_each_parameter_set, energy_mean_sv_each_parameter_set, ], [ energy_std_each_parameter_set, energy_std_raw_each_parameter_set, energy_std_sv_each_parameter_set, ], [ schmidt_coeffs_each_parameter_set, schmidt_coeffs_raw_each_parameter_set, schmidt_coeffs_sv_each_parameter_set, ], ): for params, energy_mean, energy_std, schmidts in zip( parameter_sets, energies_each_paramset, stds_each_paramset, schmidts_each_paramset, ): self.aux_results.append( ( filename, DataResults( eval_count=self._eval_count, eval_timestamp=timestamp_string, energy_hartree=( energy_mean + self._add_this_to_energies_displayed ), energy_std=energy_std, parameters=parameters, schmidts=schmidts, ), ) ) for params, energy_mean, energy_std in zip( parameter_sets, energy_mean_each_parameter_set, energy_std_each_parameter_set, ): self._eval_count += 1 if self._callback is not None: self._callback(self._eval_count, params, energy_mean, energy_std) self.parameter_sets = parameter_sets self.energy_mean_each_parameter_set = energy_mean_each_parameter_set self.energy_std_each_parameter_set = energy_std_each_parameter_set return ( np.array(energy_mean_each_parameter_set) if len(energy_mean_each_parameter_set) > 1 else energy_mean_each_parameter_set[0] ) if return_expectation: return energy_evaluation, expectation return energy_evaluation def _evaluate_forged_operator( self, parameter_sets, hf_value=0, add_this_to_mean_values_displayed=0, shots_multiplier=1, bootstrap_trials=0, ): """Computes the expectation value of the forged operator with respect to the ansatz at the given parameters.""" # These calculations are parameter independent for # a given operator so could be moved outside the optimization loop: circuits_to_execute = [] for params_idx, params in enumerate(parameter_sets): Log.log("Constructing the circuits for parameter set", params, "...") # Get all the tensor circuits associated with ansatz U tensor_circuits_to_execute_u = prepare_circuits_to_execute( params, self._tensor_prep_circuits_u, self._op_for_generating_tensor_circuits, self._ansatz, self._is_sv_sim, ) # Get all tensor circuits associated with ansatz V tensor_circuits_to_execute_v = prepare_circuits_to_execute( params, self._tensor_prep_circuits_v, self._op_for_generating_tensor_circuits, self._ansatz, self._is_sv_sim, ) # Combine all tensor circuits into a single list tensor_circuits_to_execute = ( tensor_circuits_to_execute_u + tensor_circuits_to_execute_v ) if len(self._pauli_names_for_superpos_states) > 0: # Get superposition circuits associated with ansatz U superpos_circuits_to_execute_u = prepare_circuits_to_execute( params, self._superpos_prep_circuits_u, self._op_for_generating_superpos_circuits, self._ansatz, self._is_sv_sim, ) # Get superposition circuits associated with ansatz V superpos_circuits_to_execute_v = prepare_circuits_to_execute( params, self._superpos_prep_circuits_v, self._op_for_generating_superpos_circuits, self._ansatz, self._is_sv_sim, ) # Combine all superposition circuits into a single list superpos_circuits_to_execute = ( superpos_circuits_to_execute_u + superpos_circuits_to_execute_v ) else: superpos_circuits_to_execute_u = [] superpos_circuits_to_execute_v = [] superpos_circuits_to_execute = [] if params_idx == 0: Log.log( "inferred number of pauli groups for tensor statepreps:", len(tensor_circuits_to_execute) / ( len(self._tensor_prep_circuits_u) + len(self._tensor_prep_circuits_v) ), ) if self._superpos_prep_circuits_u: Log.log( "inferred number of pauli groups for superposition statepreps:", len(superpos_circuits_to_execute) / ( len(self._superpos_prep_circuits_u) + len(self._superpos_prep_circuits_v) ), ) circuits_to_execute += ( tensor_circuits_to_execute + superpos_circuits_to_execute ) Log.log("Transpiling circuits...") Log.log(self._initial_layout) circuits_to_execute = transpile( circuits_to_execute, self._backend, initial_layout=self._initial_layout, coupling_map=self._coupling_map, ) if not isinstance(circuits_to_execute, list): circuits_to_execute = [circuits_to_execute] Log.log("Building pseudo-richardson circuits...") circuits_to_execute = make_pseudorichardson_circuits( circuits_to_execute, simple_richardson_orders=[ int(x) for x in (np.asarray(self._zero_noise_extrap) - 1) / 2 ], ) if self.copysample_job_size: Log.log("Copysampling circuits...") Log.log( "num circuits to execute before copysampling:", len(circuits_to_execute) ) weight_each_stateprep = np.abs( np.array(self._running_estimate_of_schmidts)[:, np.newaxis] * np.array(self._running_estimate_of_schmidts)[np.newaxis, :] ) if self._no_bs0_circuits: ## IMPORTANT: assumes special-case of NOT executing HF bitstring state-prep weight_each_stateprep[0, 0] = 0 weight_each_circuit = [] for qcirc in circuits_to_execute: name_parts = qcirc.name.split("_") stretch_factor = float(name_parts[-2].split("richardson")[1]) indices_of_involved_bitstrings = [ int("".join(c for c in x if c.isdigit())) for x in name_parts[1].split("bs")[1:] ] if len(indices_of_involved_bitstrings) == 1: i, j = ( indices_of_involved_bitstrings[0], indices_of_involved_bitstrings[0], ) elif len(indices_of_involved_bitstrings) == 2: i, j = indices_of_involved_bitstrings else: raise ValueError( "Circuit name should be of form [params]_bs#_... " "or [params]_bs#bs#_... indicating which 1 or 2 " "bitstrings it involves, but instead name is:", qcirc.name, ) if len(self._zero_noise_extrap) <= 2: weight_each_circuit.append( weight_each_stateprep[i, j] / stretch_factor ) else: warnings.warn( "Weighted sampling when more than 2 stretch factors are present " "is not supported (may or may not just work, haven't " "looked into it). Reverting to uniform sampling of stretch factors." ) weight_each_circuit.append(weight_each_stateprep[i, j] / 1) circuits_to_execute = copysample_circuits( circuits_to_execute, weights=weight_each_circuit, new_job_size=self.copysample_job_size * len(parameter_sets), ) Log.log( "num circuits to execute after copysampling:", len(circuits_to_execute) ) if self._meas_error_mit: if (not self._meas_fitter) or ( (time.time() - self._meas_error_refresh_timestamp) / 60 > self._meas_error_refresh_period_minutes ): Log.log("Generating measurement fitter...") physical_qubits = np.asarray(self._initial_layout).tolist() cal_circuits, state_labels = complete_meas_cal( range(len(physical_qubits)) ) result = execute_with_retry( cal_circuits, self._backend, self._meas_error_shots, self._rep_delay ) self._meas_fitter = CompleteMeasFitter(result, state_labels) self._meas_error_refresh_timestamp = time.time() Log.log("Executing", len(circuits_to_execute), "circuits...") result = execute_with_retry( circuits_to_execute, self._backend, self._shots * shots_multiplier, self._rep_delay, ) if self._meas_error_mit: Log.log("Applying meas fitter/filter...") result = self._meas_fitter.filter.apply(result) Log.log("Done executing. Analyzing results...") op_mean_each_parameter_set = [None] * len(parameter_sets) op_std_each_parameter_set = [None] * len(parameter_sets) schmidt_coeffs_each_parameter_set = [None] * len(parameter_sets) op_mean_raw_each_parameter_set = [None] * len(parameter_sets) op_std_raw_each_parameter_set = [None] * len(parameter_sets) schmidt_coeffs_raw_each_parameter_set = [None] * len(parameter_sets) op_mean_sv_each_parameter_set = [None] * len(parameter_sets) schmidt_coeffs_sv_each_parameter_set = [None] * len(parameter_sets) if self.copysample_job_size: result = combine_copysampled_results(result) if bootstrap_trials: Log.log(f"Bootstrap: resampling result {bootstrap_trials} times...") bootstrap_results = [ resample_result(result) for _ in range(bootstrap_trials) ] Log.log( "Done bootstrapping new counts, starting analysis of bootstrapped data." ) else: bootstrap_results = [] bootstrap_means_each_parameter_set = [] for idx, params in enumerate(parameter_sets): bootstrap_means = [] for is_bootstrap_index, res in enumerate([result] + bootstrap_results): results_extrap, results_raw = eval_forged_op_with_result( res, self._w_ij_tensor_states, self._w_ab_superpos_states, params, self._bitstrings_s_u, self._op_for_generating_tensor_circuits, self._op_for_generating_superpos_circuits, self._zero_noise_extrap, bitstrings_s_v=self._bitstrings_s_v, hf_value=hf_value, statevector_mode=self._is_sv_sim, hybrid_superpos_coeffs=self._hybrid_superpos_coeffs, add_this_to_mean_values_displayed=add_this_to_mean_values_displayed, no_bs0_circuits=self._no_bs0_circuits, ) op_mean, op_std, schmidts = results_extrap op_mean_raw, op_std_raw, schmidts_raw = results_raw if not is_bootstrap_index: op_mean_each_parameter_set[idx] = op_mean op_std_each_parameter_set[idx] = op_std op_mean_raw_each_parameter_set[idx] = op_mean_raw op_std_raw_each_parameter_set[idx] = op_std_raw schmidt_coeffs_raw_each_parameter_set[idx] = schmidts_raw Log.log("Optimal schmidt coeffs sqrt(p) =", schmidts) schmidt_coeffs_each_parameter_set[idx] = schmidts else: bootstrap_means.append(op_mean) bootstrap_means_each_parameter_set.append(bootstrap_means) self._running_estimate_of_schmidts = np.mean( schmidt_coeffs_each_parameter_set, axis=0 ) return ( op_mean_each_parameter_set, bootstrap_means_each_parameter_set, op_mean_raw_each_parameter_set, op_mean_sv_each_parameter_set, schmidt_coeffs_each_parameter_set, schmidt_coeffs_raw_each_parameter_set, schmidt_coeffs_sv_each_parameter_set, ) def get_optimal_vector(self): """Prevents the VQE superclass version of this function from running.""" warnings.warn( "get_optimal_vector not implemented for forged VQE. Returning None." )
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# 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. """ A set of subroutines that are used by the VQE_forged_entanglement class, which is defined in the vqe_forged_entanglement module """ import inspect import warnings import re from typing import Iterable, Dict, Tuple import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import optimizers from qiskit.algorithms.optimizers import SPSA from qiskit.algorithms.optimizers.spsa import powerseries from qiskit_nature import QiskitNatureError from .generic_execution_subroutines import compute_pauli_means_and_cov_for_one_basis from .log import Log from .prepare_bitstring import prepare_bitstring from .pseudorichardson import richardson_extrapolate from .legacy.weighted_pauli_operator import WeightedPauliOperator Matrix = Iterable[Iterable[float]] # pylint: disable=too-many-locals,too-many-arguments,too-many-branches,invalid-name def make_stateprep_circuits( bitstrings: Iterable[Iterable[int]], no_bs0_circuits: bool = True, suffix: str = "" ): """Builds the circuits preparing states |b_n> and |phi^p_nm> as defined in <https://arxiv.org/abs/2104.10220>. Also returns a list of tuples which describe any superposition terms which carry a coefficient. Assumes that the operator amplitudes are real, thus does not construct superposition states with odd p. """ # If empty, just return if len(bitstrings) == 0: return [], [], [] # If the spin-up and spin-down spin orbitals are together a 2*N qubit system, # the bitstring should be N bits long. bitstrings = np.asarray(bitstrings) tensor_prep_circuits = [ prepare_bitstring(bs, name="bs" + suffix + str(bs_idx)) for bs_idx, bs in enumerate(bitstrings) ] if no_bs0_circuits: # Drops the HF bitstring, which is assumed to be first, # since hops in our ansatz are chosen to leave it unchanged! (IMPORTANT) tensor_prep_circuits = tensor_prep_circuits[1:] superpos_prep_circuits = [] hybrid_superpos_coeffs = {} for bs1_idx, bs1 in enumerate(bitstrings): for bs2_relative_idx, bs2 in enumerate(bitstrings[bs1_idx + 1 :]): diffs = np.where(bs1 != bs2)[0] # TODO implement p -> -p as needed for problems with complex amplitudes # pylint: disable=fixme if len(diffs) > 0: i = diffs[0] if bs1[i]: x = bs2 y = bs1 # pylint: disable=unused-variable else: x = bs1 y = bs2 # pylint: disable=unused-variable S = np.delete(diffs, 0) qcirc = prepare_bitstring(np.concatenate((x[:i], [0], x[i + 1 :]))) qcirc.h(i) psi_xplus, psi_xmin = [ qcirc.copy( name=f"bs{suffix}{bs1_idx}bs{suffix}{bs1_idx+1+bs2_relative_idx}{name}" ) for name in ["xplus", "xmin"] ] psi_xmin.z(i) for psi in [psi_xplus, psi_xmin]: for target in S: psi.cx(i, target) superpos_prep_circuits.append(psi) # If the two bitstrings are equivalent -- bn==bm else: qcirc = prepare_bitstring(bs1) psi_xplus, psi_xmin = [ qcirc.copy( name=f"bs{suffix}{bs1_idx}bs{suffix}{bs1_idx+1+bs2_relative_idx}{name}" ) for name in ["xplus", "xmin"] ] hybrid_superpos_coeffs[ (suffix, str(bs1_idx), str(bs1_idx + 1 + bs2_relative_idx)) ] = True superpos_prep_circuits += [psi_xplus, psi_xmin] return tensor_prep_circuits, superpos_prep_circuits, hybrid_superpos_coeffs def prepare_circuits_to_execute( params: Iterable[float], stateprep_circuits: Iterable[QuantumCircuit], op_for_generating_circuits: WeightedPauliOperator, var_form: QuantumCircuit, statevector_mode: bool, ): """Given a set of variational parameters and list of 6qb state-preps, this function returns all (unique) circuits that must be run to evaluate those samples. """ # If circuits are empty, just return if len(stateprep_circuits) == 0: return [] circuits_to_execute = [] # Generate the requisite circuits: # pylint: disable=unidiomatic-typecheck param_bindings = dict(zip(var_form.parameters, params)) u_circuit = var_form.bind_parameters(param_bindings) for prep_circ in [qc.copy() for qc in stateprep_circuits]: circuit_name_prefix = str(params) + "_" + str(prep_circ.name) + "_" wavefn_circuit = prep_circ.compose(u_circuit) if statevector_mode: circuits_to_execute.append( wavefn_circuit.copy(name=circuit_name_prefix + "psi") ) else: circuits_this_stateprep = ( op_for_generating_circuits.construct_evaluation_circuit( wave_function=wavefn_circuit.copy(), statevector_mode=statevector_mode, # <-- False, here. use_simulator_snapshot_mode=False, circuit_name_prefix=circuit_name_prefix, ) ) circuits_to_execute += circuits_this_stateprep return circuits_to_execute # pylint: disable=unbalanced-tuple-unpacking def eval_forged_op_with_result( result, w_ij_tensor_states: Matrix, w_ab_superpos_states: Matrix, params: Iterable[float], bitstrings_s_u: np.ndarray, op_for_generating_tensor_circuits: WeightedPauliOperator, op_for_generating_superpos_circuits: WeightedPauliOperator, richardson_stretch_factors: Iterable[float], statevector_mode: bool, hf_value: float, add_this_to_mean_values_displayed: float, bitstrings_s_v: np.ndarray = None, hybrid_superpos_coeffs: Dict[Tuple[int, int, str], bool] = None, no_bs0_circuits: bool = True, verbose: bool = False, ): """Evaluates the forged operator. Extracts necessary expectation values from the result object, then combines those pieces to compute the configuration-interaction Hamiltonian (Hamiltonian in the basis of determinants/bitstrings). For reference, also computes mean value obtained without Richardson """ if bitstrings_s_v is None: bitstrings_s_v = [] tensor_state_prefixes_u = [f"bsu{idx}" for idx in range(len(bitstrings_s_u))] tensor_state_prefixes_v = [] if len(bitstrings_s_v) > 0: tensor_state_prefixes_v = [f"bsv{idx}" for idx in range(len(bitstrings_s_v))] tensor_state_prefixes = tensor_state_prefixes_u + tensor_state_prefixes_v tensor_expvals = _get_pauli_expectations_from_result( result, params, tensor_state_prefixes, op_for_generating_tensor_circuits, richardson_stretch_factors=richardson_stretch_factors, hybrid_superpos_coeffs=hybrid_superpos_coeffs, statevector_mode=statevector_mode, no_bs0_circuits=no_bs0_circuits, ) tensor_expvals_extrap = richardson_extrapolate( tensor_expvals, richardson_stretch_factors, axis=2 ) superpos_state_prefixes_u = [] superpos_state_prefixes_v = [] lin_combos = ["xplus", "xmin"] # ,'yplus','ymin'] # num_bitstrings is the number of bitstring combos we have num_bitstrings = len(bitstrings_s_u) for x in range(num_bitstrings): for y in range(num_bitstrings): if x == y: continue bsu_string = f"bsu{min(x,y)}bsu{max(x,y)}" superpos_state_prefixes_u += [ bsu_string + lin_combo for lin_combo in lin_combos ] # Determine whether we are handling the two subsystems separately asymmetric_bitstrings = False if len(bitstrings_s_v) > 0: asymmetric_bitstrings = True bsv_string = f"bsv{min(x,y)}bsv{max(x,y)}" superpos_state_prefixes_v += [ bsv_string + lin_combo for lin_combo in lin_combos ] superpos_state_prefixes = superpos_state_prefixes_u + superpos_state_prefixes_v superpos_expvals = _get_pauli_expectations_from_result( result, params, superpos_state_prefixes, op_for_generating_superpos_circuits, hybrid_superpos_coeffs=hybrid_superpos_coeffs, richardson_stretch_factors=richardson_stretch_factors, statevector_mode=statevector_mode, no_bs0_circuits=no_bs0_circuits, ) superpos_expvals_extrap = richardson_extrapolate( superpos_expvals, richardson_stretch_factors, axis=2 ) forged_op_results_w_and_wo_extrapolation = [] for (tensor_expvals_real, superpos_expvals_real) in [ [tensor_expvals_extrap, superpos_expvals_extrap], [tensor_expvals[:, :, 0], superpos_expvals[:, :, 0]], ]: h_schmidt = compute_h_schmidt( tensor_expvals_real, superpos_expvals_real, w_ij_tensor_states, w_ab_superpos_states, asymmetric_bitstrings, ) if no_bs0_circuits: # IMPORTANT: ASSUMING HOPGATES CHOSEN S.T. HF BITSTRING # (FIRST BITSTRING) IS UNAFFECTED, ALLOWING CORRESPONDING # ENERGY TO BE FIXED AT HF VALUE CALCULATED BY QISKIT/PYSCF. h_schmidt[0, 0] = hf_value - add_this_to_mean_values_displayed # Update Schmidt coefficients to minimize operator (presumably energy): if verbose: Log.log( "Operator as Schmidt matrix: (diagonals have been shifted by given offset", add_this_to_mean_values_displayed, ")", ) Log.log( h_schmidt + np.eye(len(h_schmidt)) * add_this_to_mean_values_displayed ) evals, evecs = np.linalg.eigh(h_schmidt) schmidts = evecs[:, 0] op_mean = evals[0] op_std = None forged_op_results_w_and_wo_extrapolation.append([op_mean, op_std, schmidts]) ( forged_op_results_extrap, forged_op_results_raw, ) = forged_op_results_w_and_wo_extrapolation # pylint: disable=unbalanced-tuple-unpacking return forged_op_results_extrap, forged_op_results_raw def _get_pauli_expectations_from_result( result, params, stateprep_strings, op_for_generating_circuits, statevector_mode, hybrid_superpos_coeffs=None, richardson_stretch_factors=None, no_bs0_circuits=True, ): """Returns array containing ordered expectation values of Pauli strings evaluated for the various wavefunctions. Axes are [stateprep_idx, Pauli_idx, richardson_stretch_factor_idx, mean_or_variance] """ if richardson_stretch_factors is None: richardson_stretch_factors = [1] if not op_for_generating_circuits: return np.empty((0, 0, len(richardson_stretch_factors), 2)) params_string = str(params) + "_" if statevector_mode: op_matrices = np.asarray( [op.to_matrix() for op in [p[1] for p in op_for_generating_circuits.paulis]] ) pauli_vals = np.zeros( ( len(stateprep_strings), len(op_for_generating_circuits._paulis), # pylint: disable=protected-access len(richardson_stretch_factors), 2, ) ) pauli_names_temp = [p[1].to_label() for p in op_for_generating_circuits.paulis] for prep_idx, prep_string in enumerate(stateprep_strings): suffix = prep_string[2] if suffix not in ["u", "v"]: raise ValueError(f"Invalid stateprep circuit name: {prep_string}") bitstring_pair = [0, 0] tensor_circuit = True num_bs_terms = prep_string.count("bs") if (num_bs_terms > 2) or (num_bs_terms == 0): raise ValueError(f"Invalid stateprep circuit name: {prep_string}") elif num_bs_terms == 2: tensor_circuit = False prep_string_digits = [ int(float(s)) for s in re.findall(r"-?\d+\.?\d*", prep_string) ] bitstring_pair = [prep_string_digits[0], prep_string_digits[1]] if no_bs0_circuits and (prep_string == "bsu0" or prep_string == "bsv0"): # IMPORTANT: ASSUMING HOPGATES CHOSEN S.T. # HF BITSTRING (FIRST BITSTRING) IS UNAFFECTED, # ALLOWING CORRESPONDING ENERGY TO BE FIXED AT H # F VALUE CALCULATED BY QISKIT/PYSCF. pauli_vals[prep_idx, :, :, :] = np.nan continue circuit_prefix_prefix = "".join([params_string, prep_string]) for rich_idx, stretch_factor in enumerate(richardson_stretch_factors): circuit_name_prefix = "".join( [circuit_prefix_prefix, f"_richardson{stretch_factor:.2f}", "_"] ) if statevector_mode: psi = result.get_statevector(circuit_name_prefix + "psi") pauli_vals_temp = np.real( np.einsum("i,Mij,j->M", np.conj(psi), op_matrices, psi) ) else: pauli_vals_temp, _ = _eval_each_pauli_with_result( tpbgwpo=op_for_generating_circuits, result=result, statevector_mode=statevector_mode, use_simulator_snapshot_mode=False, circuit_name_prefix=circuit_name_prefix, ) pauli_vals_alphabetical = [ x[1] for x in sorted(list(zip(pauli_names_temp, pauli_vals_temp))) ] if not np.all(np.isreal(pauli_vals_alphabetical)): warnings.warn( "Computed Pauli expectation value has nonzero " "imaginary part which will be discarded." ) pauli_vals[prep_idx, :, rich_idx, 0] = np.real(pauli_vals_alphabetical) key = (suffix, str(bitstring_pair[0]), str(bitstring_pair[1])) if key in hybrid_superpos_coeffs.keys(): if prep_string[-4:] == "xmin": pauli_vals[prep_idx] *= 0 elif prep_string[-5:] == "xplus": pass else: raise ValueError(f"Invalid circuit name: {prep_string}") elif not tensor_circuit: pauli_vals[prep_idx] *= 1 / 2 return pauli_vals # pylint: disable=protected-access def _eval_each_pauli_with_result( tpbgwpo, result, statevector_mode, use_simulator_snapshot_mode=False, circuit_name_prefix="", ): """Ignores the weights of each pauli operator.""" if tpbgwpo.is_empty(): raise QiskitNatureError("Operator is empty, check the operator.") if statevector_mode or use_simulator_snapshot_mode: raise NotImplementedError() num_paulis = len(tpbgwpo._paulis) means = np.zeros(num_paulis) cov = np.zeros((num_paulis, num_paulis)) for basis, p_indices in tpbgwpo._basis: counts = result.get_counts(circuit_name_prefix + basis.to_label()) paulis = [tpbgwpo._paulis[idx] for idx in p_indices] paulis = [p[1] for p in paulis] ## DISCARDING THE WEIGHTS means_this_basis, cov_this_basis = compute_pauli_means_and_cov_for_one_basis( paulis, counts ) for p_idx, p_mean in zip(p_indices, means_this_basis): means[p_idx] = p_mean cov[np.ix_(p_indices, p_indices)] = cov_this_basis return means, cov def compute_h_schmidt( tensor_expvals, superpos_expvals, w_ij_tensor_weights, w_ab_superpos_weights, asymmetric_bitstrings, ): """Computes the schmidt decomposition of the Hamiltonian. TODO checkthis. # pylint: disable=fixme Pauli val arrays contain expectation values <x|P|x> and their standard deviations. Axes are [x_idx, P_idx, mean_or_variance] Coefficients w_ij/w_ab: Axes: [index of Pauli string for eta, index of Pauli string for tau]. asymmetric_bitstrings: A boolean which signifies whether the U and V subsystems have different ansatze. """ # Number of tensor stateprep circuits num_tensor_terms = int(np.shape(tensor_expvals)[0]) if asymmetric_bitstrings: num_tensor_terms = int( num_tensor_terms / 2 ) # num_tensor_terms should always be even here tensor_exp_vals_u = tensor_expvals[:num_tensor_terms, :, 0] tensor_exp_vals_v = tensor_expvals[num_tensor_terms:, :, 0] else: # Use the same expectation values for both subsystem calculations tensor_exp_vals_u = tensor_expvals[:, :, 0] tensor_exp_vals_v = tensor_expvals[:, :, 0] # Calculate the schmidt summation over the U and V subsystems and diagonalize the values h_schmidt_diagonal = np.einsum( "ij,xi,xj->x", w_ij_tensor_weights, tensor_exp_vals_u, tensor_exp_vals_v, ) h_schmidt = np.diag(h_schmidt_diagonal) # If including the +/-Y superpositions (omitted at time of writing # since they typically have 0 net contribution) would change this to 4 instead of 2. num_lin_combos = 2 num_superpos_terms = int(np.shape(superpos_expvals)[0]) if asymmetric_bitstrings: num_superpos_terms = int( num_superpos_terms / 2 ) # num_superpos_terms should always be even here pvss_u = superpos_expvals[:num_superpos_terms, :, 0] pvss_v = superpos_expvals[num_superpos_terms:, :, 0] else: pvss_u = superpos_expvals[:, :, 0] pvss_v = superpos_expvals[:, :, 0] # Calculate delta for U subsystem p_plus_x_u = pvss_u[0::num_lin_combos, :] p_minus_x_u = pvss_u[1::num_lin_combos, :] p_delta_x_u = p_plus_x_u - p_minus_x_u # Calculate delta for V subsystem if asymmetric_bitstrings: p_plus_x_v = pvss_v[0::num_lin_combos, :] p_minus_x_v = pvss_v[1::num_lin_combos, :] p_delta_x_v = p_plus_x_v - p_minus_x_v else: p_delta_x_v = p_delta_x_u h_schmidt_off_diagonals = np.einsum( "ab,xa,xb->x", w_ab_superpos_weights, p_delta_x_u, p_delta_x_v ) superpos_state_indices = [ (x, y) for x in range(h_schmidt.shape[0]) for y in range(h_schmidt.shape[0]) if x != y ] for element, indices in zip(h_schmidt_off_diagonals, superpos_state_indices): h_schmidt[indices] = element return h_schmidt # , H_schmidt_vars) def get_optimizer_instance(config): """Returns optimizer instance based on config.""" # Addressing some special cases for compatibility with various Qiskit optimizers: if config.optimizer_name == "adaptive_SPSA": optimizer = SPSA else: optimizer = getattr(optimizers, config.optimizer_name) optimizer_config = {} optimizer_arg_names = inspect.signature(optimizer).parameters.keys() iter_kw = [kw for kw in ["maxiter", "max_trials"] if kw in optimizer_arg_names][0] optimizer_config[iter_kw] = config.maxiter if "skip_calibration" in optimizer_arg_names: optimizer_config["skip_calibration"] = config.skip_any_optimizer_cal if "last_avg" in optimizer_arg_names: optimizer_config["last_avg"] = config.spsa_last_average if "tol" in optimizer_arg_names: optimizer_config["tol"] = config.optimizer_tol if "c0" in optimizer_arg_names: optimizer_config["c0"] = config.spsa_c0 if "c1" in optimizer_arg_names: optimizer_config["c1"] = config.spsa_c1 if "learning_rate" in optimizer_arg_names: optimizer_config["learning_rate"] = lambda: powerseries( config.spsa_c0, 0.602, 0 ) if "perturbation" in optimizer_arg_names: optimizer_config["perturbation"] = lambda: powerseries(config.spsa_c1, 0.101, 0) if config.initial_spsa_iteration_idx: if "int_iter" in optimizer_arg_names: optimizer_config["int_iter"] = config.initial_spsa_iteration_idx if "bootstrap_trials" in optimizer_arg_names: optimizer_config["bootstrap_trials"] = config.bootstrap_trials Log.log(optimizer_config) optimizer_instance = optimizer(**optimizer_config) return optimizer_instance
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# 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. """Execution subroutines.""" import time import numpy as np from qiskit import assemble from qiskit.providers.ibmq.job import ( IBMQJobFailureError, IBMQJobApiError, IBMQJobInvalidStateError, ) from entanglement_forging.utils.legacy.common import measure_pauli_z, covariance def compute_pauli_means_and_cov_for_one_basis(paulis, counts): """Compute Pauli means and cov for one basis.""" means = np.array([measure_pauli_z(counts, pauli) for pauli in paulis]) cov = np.array( [ [ covariance(counts, pauli_1, pauli_2, avg_1, avg_2) for pauli_2, avg_2 in zip(paulis, means) ] for pauli_1, avg_1 in zip(paulis, means) ] ) return means, cov def execute_with_retry(circuits, backend, shots, rep_delay=None, noise_model=None): """Executes job with retry.""" global result # pylint: disable=global-variable-undefined,invalid-name trials = 0 ran_job_ok = False while not ran_job_ok: try: if backend.name() in [ "statevector_simulator", "aer_simulator_statevector", ]: job = backend.run( circuits, seed_simulator=42, ) elif backend.name() == "qasm_simulator": job = backend.run(circuits, shots=shots, noise_model=noise_model) else: job = backend.run(circuits, shots=shots, rep_delay=rep_delay) result = job.result() ran_job_ok = True except (IBMQJobFailureError, IBMQJobApiError, IBMQJobInvalidStateError) as err: print("Error running job, will retry in 5 mins.") print("Error:", err) # Wait 5 mins and try again. Hopefully this handles network outages etc, # and also if user cancels a (stuck) job through IQX. # Add more error types to the exception as new ones crop up (as appropriate). time.sleep(300) trials += 1 # pylint: disable=raise-missing-from if trials > 100: raise RuntimeError( "Timed out trying to run job successfully (100 attempts)" ) return result def reduce_bitstrings(bitstrings, orbitals_to_reduce): """Returns reduced bitstrings.""" return np.delete(bitstrings, orbitals_to_reduce, axis=-1).tolist()
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# -*- coding: utf-8 -*- # 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. # pylint: disable=cell-var-from-loop,invalid-name """ Measurement correction filters. """ from copy import deepcopy import numpy as np import qiskit import scipy.linalg as la from qiskit import QiskitError from qiskit.utils.mitigation.circuits import count_keys from qiskit.tools import parallel_map from scipy.optimize import minimize # pylint: disable=too-many-locals,too-many-branches,too-many-nested-blocks,too-many-statements class MeasurementFilter: """ Measurement error mitigation filter. Produced from a measurement calibration fitter and can be applied to data. """ def __init__(self, cal_matrix: np.matrix, state_labels: list): """ Initialize a measurement error mitigation filter using the cal_matrix from a measurement calibration fitter. Args: cal_matrix: the calibration matrix for applying the correction state_labels: the states for the ordering of the cal matrix """ self._cal_matrix = cal_matrix self._state_labels = state_labels @property def cal_matrix(self): """Return cal_matrix.""" return self._cal_matrix @property def state_labels(self): """return the state label ordering of the cal matrix""" return self._state_labels @state_labels.setter def state_labels(self, new_state_labels): """set the state label ordering of the cal matrix""" self._state_labels = new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix): """Set cal_matrix.""" self._cal_matrix = new_cal_matrix def apply(self, raw_data, method="least_squares"): """Apply the calibration matrix to results. Args: raw_data (dict or list): The data to be corrected. Can be in a number of forms: Form 1: a counts dictionary from results.get_counts Form 2: a list of counts of `length==len(state_labels)` I have no idea what this is. I'm not supporting it here. --> Form 3: a list of counts of `length==M*len(state_labels)` where M is an integer (e.g. for use with the tomography data) Form 4: a qiskit Result method (str): fitting method. If `None`, then least_squares is used. ``pseudo_inverse``: direct inversion of the A matrix ``least_squares``: constrained to have physical probabilities Returns: dict or list: The corrected data in the same form as `raw_data` Raises: QiskitError: if `raw_data` is not an integer multiple of the number of calibrated states. """ raw_data = deepcopy(raw_data) output_type = None if isinstance(raw_data, qiskit.result.result.Result): output_Result = deepcopy(raw_data) output_type = "result" raw_data = raw_data.get_counts() if isinstance(raw_data, dict): raw_data = [raw_data] elif isinstance(raw_data, list): output_type = "list" elif isinstance(raw_data, dict): raw_data = [raw_data] output_type = "dict" assert output_type unique_data_labels = {key for data_row in raw_data for key in data_row.keys()} if not unique_data_labels.issubset(set(self._state_labels)): raise QiskitError( "Unexpected state label '" + unique_data_labels + "', verify the fitter's state labels correpsond to the input data" ) raw_data_array = np.zeros((len(raw_data), len(self._state_labels)), dtype=float) corrected_data_array = np.zeros( (len(raw_data), len(self._state_labels)), dtype=float ) for expt_idx, data_row in enumerate(raw_data): for stateidx, state in enumerate(self._state_labels): raw_data_array[expt_idx][stateidx] = data_row.get(state, 0) if method == "pseudo_inverse": pinv_cal_mat = la.pinv(self._cal_matrix) # pylint: disable=unused-variable corrected_data = np.einsum("ij,xj->xi", pinv_cal_mat, raw_data_array) elif method == "least_squares": nshots_each_expt = np.sum(raw_data_array, axis=1) for expt_idx, (nshots, raw_data_row) in enumerate( zip(nshots_each_expt, raw_data_array) ): cal_mat = self._cal_matrix nlabels = len(raw_data_row) # pylint: disable=unused-variable def fun(estimated_corrected_data): return np.sum( (raw_data_row - cal_mat.dot(estimated_corrected_data)) ** 2 ) def gradient(estimated_corrected_data): return 2 * ( cal_mat.dot(estimated_corrected_data) - raw_data_row ).dot(cal_mat) cons = { "type": "eq", "fun": lambda x: nshots - np.sum(x), "jac": lambda x: -1 * np.ones_like(x), } bnds = tuple((0, nshots) for x in raw_data_row) res = minimize( fun, raw_data_row, method="SLSQP", constraints=cons, bounds=bnds, tol=1e-6, jac=gradient, ) # def fun(angles): # # for bounding between 0 and 1 # cos2 = np.cos(angles)**2 # # form should constrain so sum always = nshots. # estimated_corrected_data = nshots * \ # (1/nlabels + (nlabels*cos2 - # np.sum(cos2))/(nlabels-1)) # return np.sum( (raw_data_row - # cal_mat.dot(estimated_corrected_data) )**2) # # def gradient(estimated_corrected_data): # return 2 * (cal_mat.dot(estimated_corrected_data) - # raw_data_row).dot(cal_mat) # # bnds = tuple((0, nshots) for x in raw_data_this_idx) # res = minimize(fun, raw_data_row, # method='SLSQP', constraints=cons, # bounds=bnds, tol=1e-6, jac=gradient) corrected_data_array[expt_idx] = res.x else: raise QiskitError("Unrecognized method.") # time_finished_correction = time.time() # convert back into a counts dictionary corrected_dicts = [] for corrected_data_row in corrected_data_array: new_count_dict = {} for stateidx, state in enumerate(self._state_labels): if corrected_data_row[stateidx] != 0: new_count_dict[state] = corrected_data_row[stateidx] corrected_dicts.append(new_count_dict) if output_type == "dict": assert len(corrected_dicts) == 1 # converting back to a single counts dict, to match input provided by user output = corrected_dicts[0] elif output_type == "list": output = corrected_dicts elif output_type == "result": for resultidx, new_counts in enumerate(corrected_dicts): output_Result.results[resultidx].data.counts = new_counts output = output_Result else: raise TypeError() return output class TensoredFilter: """ Tensored measurement error mitigation filter. Produced from a tensored measurement calibration fitter and can be applied to data. """ def __init__(self, cal_matrices: np.matrix, substate_labels_list: list): """ Initialize a tensored measurement error mitigation filter using the cal_matrices from a tensored measurement calibration fitter. Args: cal_matrices: the calibration matrices for applying the correction. substate_labels_list: for each calibration matrix a list of the states (as strings, states in the subspace) """ self._cal_matrices = cal_matrices self._qubit_list_sizes = [] self._indices_list = [] self._substate_labels_list = [] self.substate_labels_list = substate_labels_list @property def cal_matrices(self): """Return cal_matrices.""" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices): """Set cal_matrices.""" self._cal_matrices = deepcopy(new_cal_matrices) @property def substate_labels_list(self): """Return _substate_labels_list""" return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): """Return _substate_labels_list""" self._substate_labels_list = new_substate_labels_list # get the number of qubits in each subspace self._qubit_list_sizes = [] for _, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append(int(np.log2(len(substate_label_list)))) # get the indices in the calibration matrix self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append({lab: ind for ind, lab in enumerate(sub_labels)}) @property def qubit_list_sizes(self): """Return _qubit_list_sizes.""" return self._qubit_list_sizes @property def nqubits(self): """Return the number of qubits. See also MeasurementFilter.apply()""" return sum(self._qubit_list_sizes) def apply(self, raw_data, method="least_squares"): """ Apply the calibration matrices to results. Args: raw_data (dict or Result): The data to be corrected. Can be in one of two forms: * A counts dictionary from results.get_counts * A Qiskit Result method (str): fitting method. The following methods are supported: * 'pseudo_inverse': direct inversion of the cal matrices. * 'least_squares': constrained to have physical probabilities. * If `None`, 'least_squares' is used. Returns: dict or Result: The corrected data in the same form as raw_data Raises: QiskitError: if raw_data is not in a one of the defined forms. """ all_states = count_keys(self.nqubits) num_of_states = 2**self.nqubits # check forms of raw_data if isinstance(raw_data, dict): # counts dictionary # convert to list raw_data2 = [np.zeros(num_of_states, dtype=float)] for state, count in raw_data.items(): stateidx = int(state, 2) raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method), ) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else: raise QiskitError("Unrecognized type for raw_data.") if method == "pseudo_inverse": pinv_cal_matrices = [] for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) # Apply the correction for data_idx, _ in enumerate(raw_data2): if method == "pseudo_inverse": inv_mat_dot_raw = np.zeros([num_of_states], dtype=float) for state1_idx, state1 in enumerate(all_states): for state2_idx, state2 in enumerate(all_states): if raw_data2[data_idx][state2_idx] == 0: continue product = 1.0 end_index = self.nqubits for p_ind, pinv_mat in enumerate(pinv_cal_matrices): start_index = end_index - self._qubit_list_sizes[p_ind] state1_as_int = self._indices_list[p_ind][ state1[start_index:end_index] ] state2_as_int = self._indices_list[p_ind][ state2[start_index:end_index] ] end_index = start_index product *= pinv_mat[state1_as_int][state2_as_int] if product == 0: break inv_mat_dot_raw[state1_idx] += ( product * raw_data2[data_idx][state2_idx] ) raw_data2[data_idx] = inv_mat_dot_raw elif method == "least_squares": def fun(x): mat_dot_x = np.zeros([num_of_states], dtype=float) for state1_idx, state1 in enumerate(all_states): mat_dot_x[state1_idx] = 0.0 for state2_idx, state2 in enumerate(all_states): if x[state2_idx] != 0: product = 1.0 end_index = self.nqubits for c_ind, cal_mat in enumerate(self._cal_matrices): start_index = ( end_index - self._qubit_list_sizes[c_ind] ) state1_as_int = self._indices_list[c_ind][ state1[start_index:end_index] ] state2_as_int = self._indices_list[c_ind][ state2[start_index:end_index] ] end_index = start_index product *= cal_mat[state1_as_int][state2_as_int] if product == 0: break mat_dot_x[state1_idx] += product * x[state2_idx] return sum((raw_data2[data_idx] - mat_dot_x) ** 2) x0 = np.random.rand(num_of_states) x0 = x0 / sum(x0) nshots = sum(raw_data2[data_idx]) cons = {"type": "eq", "fun": lambda x: nshots - sum(x)} bnds = tuple((0, nshots) for x in x0) res = minimize( fun, x0, method="SLSQP", constraints=cons, bounds=bnds, tol=1e-6 ) raw_data2[data_idx] = res.x else: raise QiskitError("Unrecognized method.") # convert back into a counts dictionary new_count_dict = {} for state_idx, state in enumerate(all_states): if raw_data2[0][state_idx] != 0: new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict def _apply_correction(self, resultidx, raw_data, method): """Wrapper to call apply with a counts dictionary.""" new_counts = self.apply(raw_data.get_counts(resultidx), method=method) return resultidx, new_counts
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# -*- coding: utf-8 -*- # 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. # pylint: disable=cell-var-from-loop """ Measurement correction fitters. """ import copy import re from typing import List, Union import numpy as np from qiskit import QiskitError from qiskit.utils.mitigation.circuits import count_keys from qiskit.result import Result from entanglement_forging.utils.meas_mit_filters_faster import MeasurementFilter try: from matplotlib import pyplot as plt HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False # pylint: disable=too-many-locals,too-many-branches class CompleteMeasFitter: """ Measurement correction fitter for a full calibration """ def __init__( self, results: Union[Result, List[Result]], state_labels: List[str], qubit_list: List[int] = None, circlabel: str = "", ): """ Initialize a measurement calibration matrix from the results of running the circuits returned by `measurement_calibration_circuits` A wrapper for the tensored fitter Args: results: the results of running the measurement calibration circuits. If this is `None` the user will set a calibration matrix later. state_labels: list of calibration state labels returned from `measurement_calibration_circuits`. The output matrix will obey this ordering. qubit_list: List of the qubits (for reference and if the subset is needed). If `None`, the qubit_list will be created according to the length of state_labels[0]. circlabel: if the qubits were labeled. """ if qubit_list is None: qubit_list = range(len(state_labels[0])) self._qubit_list = qubit_list self._tens_fitt = TensoredMeasFitter( results, [qubit_list], [state_labels], circlabel ) @property def cal_matrix(self): """Return cal_matrix.""" return self._tens_fitt.cal_matrices[0] @cal_matrix.setter def cal_matrix(self, new_cal_matrix): """set cal_matrix.""" self._tens_fitt.cal_matrices = [copy.deepcopy(new_cal_matrix)] @property def state_labels(self): """Return state_labels.""" return self._tens_fitt.substate_labels_list[0] @property def qubit_list(self): """Return list of qubits.""" return self._qubit_list @state_labels.setter def state_labels(self, new_state_labels): """Set state label.""" self._tens_fitt.substate_labels_list[0] = new_state_labels @property def filter(self): """Return a measurement filter using the cal matrix.""" return MeasurementFilter(self.cal_matrix, self.state_labels) def add_data(self, new_results, rebuild_cal_matrix=True): """ Add measurement calibration data Args: new_results (list or qiskit.result.Result): a single result or list of result objects. rebuild_cal_matrix (bool): rebuild the calibration matrix """ self._tens_fitt.add_data(new_results, rebuild_cal_matrix) def subset_fitter(self, qubit_sublist=None): """ Return a fitter object that is a subset of the qubits in the original list. Args: qubit_sublist (list): must be a subset of qubit_list Returns: CompleteMeasFitter: A new fitter that has the calibration for a subset of qubits Raises: QiskitError: If the calibration matrix is not initialized """ if self._tens_fitt.cal_matrices is None: raise QiskitError("Calibration matrix is not initialized") if qubit_sublist is None: raise QiskitError("Qubit sublist must be specified") for qubit in qubit_sublist: if qubit not in self._qubit_list: raise QiskitError("Qubit not in the original set of qubits") # build state labels new_state_labels = count_keys(len(qubit_sublist)) # mapping between indices in the state_labels and the qubits in # the sublist qubit_sublist_ind = [] for sqb in qubit_sublist: for qbind, qubit in enumerate(self._qubit_list): if qubit == sqb: qubit_sublist_ind.append(qbind) # states in the full calibration which correspond # to the reduced labels q_q_mapping = [] state_labels_reduced = [] for label in self.state_labels: tmplabel = [label[index] for index in qubit_sublist_ind] state_labels_reduced.append("".join(tmplabel)) for sub_lab_ind, _ in enumerate(new_state_labels): q_q_mapping.append([]) for labelind, label in enumerate(state_labels_reduced): if label == new_state_labels[sub_lab_ind]: q_q_mapping[-1].append(labelind) new_fitter = CompleteMeasFitter( results=None, state_labels=new_state_labels, qubit_list=qubit_sublist ) new_cal_matrix = np.zeros([len(new_state_labels), len(new_state_labels)]) # do a partial trace for i in range(len(new_state_labels)): for j in range(len(new_state_labels)): for q_q_i_map in q_q_mapping[i]: for q_q_j_map in q_q_mapping[j]: new_cal_matrix[i, j] += self.cal_matrix[q_q_i_map, q_q_j_map] new_cal_matrix[i, j] /= len(q_q_mapping[i]) new_fitter.cal_matrix = new_cal_matrix return new_fitter def readout_fidelity(self, label_list=None): """ Based on the results, output the readout fidelity which is the normalized trace of the calibration matrix Args: label_list (bool): If `None`, returns the average assignment fidelity of a single state. Otherwise it returns the assignment fidelity to be in any one of these states averaged over the second index. Returns: numpy.array: readout fidelity (assignment fidelity) Additional Information: The on-diagonal elements of the calibration matrix are the probabilities of measuring state 'x' given preparation of state 'x' and so the normalized trace is the average assignment fidelity """ return self._tens_fitt.readout_fidelity(0, label_list) def plot_calibration(self, ax=None, show_plot=True): # pylint: disable=invalid-name """ Plot the calibration matrix (2D color grid plot) Args: show_plot (bool): call plt.show() ax (matplotlib.axes.Axes): An optional Axes object to use for the plot """ self._tens_fitt.plot_calibration( 0, ax, show_plot ) # pylint: disable=invalid-name class TensoredMeasFitter: """ Measurement correction fitter for a tensored calibration. """ def __init__( self, results: Union[Result, List[Result]], mit_pattern: List[List[int]], substate_labels_list: List[List[str]] = None, circlabel: str = "", ): """ Initialize a measurement calibration matrix from the results of running the circuits returned by `measurement_calibration_circuits`. Args: results: the results of running the measurement calibration circuits. If this is `None`, the user will set calibration matrices later. mit_pattern: qubits to perform the measurement correction on, divided to groups according to tensors substate_labels_list: for each calibration matrix, the labels of its rows and columns. If `None`, the labels are ordered lexicographically circlabel: if the qubits were labeled Raises: ValueError: if the mit_pattern doesn't match the substate_labels_list """ self._result_list = [] self._cal_matrices = None self._circlabel = circlabel self._qubit_list_sizes = [len(qubit_list) for qubit_list in mit_pattern] self._indices_list = [] if substate_labels_list is None: self._substate_labels_list = [] for list_size in self._qubit_list_sizes: self._substate_labels_list.append(count_keys(list_size)) else: self._substate_labels_list = substate_labels_list if len(self._qubit_list_sizes) != len(substate_labels_list): raise ValueError( "mit_pattern does not match \ substate_labels_list" ) self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append({lab: ind for ind, lab in enumerate(sub_labels)}) self.add_data(results) @property def cal_matrices(self): """Returns cal_matrices.""" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_mat): """Sets _cal_matrices.""" self._cal_matrices = copy.deepcopy(new_cal_mat) @property def substate_labels_list(self): """Return _substate_labels_list.""" return self._substate_labels_list @property def nqubits(self): """Return _qubit_list_sizes.""" return sum(self._qubit_list_sizes) def add_data(self, new_results, rebuild_cal_matrix=True): """ Add measurement calibration data Args: new_results (list or qiskit.result.Result): a single result or list of Result objects. rebuild_cal_matrix (bool): rebuild the calibration matrix """ if new_results is None: return if not isinstance(new_results, list): new_results = [new_results] for result in new_results: self._result_list.append(result) if rebuild_cal_matrix: self._build_calibration_matrices() def readout_fidelity(self, cal_index=0, label_list=None): """ Based on the results, output the readout fidelity, which is the average of the diagonal entries in the calibration matrices. Args: cal_index(integer): readout fidelity for this index in _cal_matrices label_list (list): Returns the average fidelity over of the groups f states. In the form of a list of lists of states. If `None`, then each state used in the construction of the calibration matrices forms a group of size 1 Returns: numpy.array: The readout fidelity (assignment fidelity) Raises: QiskitError: If the calibration matrix has not been set for the object. Additional Information: The on-diagonal elements of the calibration matrices are the probabilities of measuring state 'x' given preparation of state 'x'. """ if self._cal_matrices is None: raise QiskitError("Cal matrix has not been set") if label_list is None: label_list = [[label] for label in self._substate_labels_list[cal_index]] state_labels = self._substate_labels_list[cal_index] fidelity_label_list = [] if label_list is None: fidelity_label_list = [[label] for label in state_labels] else: for fid_sublist in label_list: fidelity_label_list.append([]) for fid_statelabl in fid_sublist: for label_idx, label in enumerate(state_labels): if fid_statelabl == label: fidelity_label_list[-1].append(label_idx) continue # fidelity_label_list is a 2D list of indices in the # cal_matrix, we find the assignment fidelity of each # row and average over the list assign_fid_list = [] for fid_label_sublist in fidelity_label_list: assign_fid_list.append(0) for state_idx_i in fid_label_sublist: for state_idx_j in fid_label_sublist: assign_fid_list[-1] += self._cal_matrices[cal_index][state_idx_i][ state_idx_j ] assign_fid_list[-1] /= len(fid_label_sublist) return np.mean(assign_fid_list) def _build_calibration_matrices(self): """ Build the measurement calibration matrices from the results of running the circuits returned by `measurement_calibration`. """ # initialize the set of empty calibration matrices self._cal_matrices = [] for list_size in self._qubit_list_sizes: self._cal_matrices.append( np.zeros([2**list_size, 2**list_size], dtype=float) ) # go through for each calibration experiment for result in self._result_list: for experiment in result.results: circ_name = experiment.header.name # extract the state from the circuit name # this was the prepared state circ_search = re.search( "(?<=" + self._circlabel + "cal_)\\w+", circ_name ) # this experiment is not one of the calcs so skip if circ_search is None: continue state = circ_search.group(0) # get the counts from the result state_cnts = result.get_counts(circ_name) for measured_state, counts in state_cnts.items(): end_index = self.nqubits for cal_ind, cal_mat in enumerate(self._cal_matrices): start_index = end_index - self._qubit_list_sizes[cal_ind] substate_index = self._indices_list[cal_ind][ state[start_index:end_index] ] measured_substate_index = self._indices_list[cal_ind][ measured_state[start_index:end_index] ] end_index = start_index cal_mat[measured_substate_index][substate_index] += counts for mat_index, _ in enumerate(self._cal_matrices): sums_of_columns = np.sum(self._cal_matrices[mat_index], axis=0) # pylint: disable=assignment-from-no-return self._cal_matrices[mat_index] = np.divide( self._cal_matrices[mat_index], sums_of_columns, out=np.zeros_like(self._cal_matrices[mat_index]), where=sums_of_columns != 0, ) def plot_calibration(self, cal_index=0, axes=None, show_plot=True): """ Plot one of the calibration matrices (2D color grid plot). Args: cal_index(integer): calibration matrix to plot axes(matplotlib.axes): settings for the graph show_plot (bool): call plt.show() Raises: QiskitError: if _cal_matrices was not set. ImportError: if matplotlib was not installed. """ if self._cal_matrices is None: raise QiskitError("Cal matrix has not been set") if not HAS_MATPLOTLIB: raise ImportError( "The function plot_rb_data needs matplotlib. " 'Run "pip install matplotlib" before.' ) if axes is None: plt.figure() axes = plt.gca() axim = axes.matshow( self.cal_matrices[cal_index], cmap=plt.cm.binary, # pylint: disable=no-member clim=[0, 1], ) axes.figure.colorbar(axim) axes.set_xlabel("Prepared State") axes.xaxis.set_label_position("top") axes.set_ylabel("Measured State") axes.set_xticks(np.arange(len(self._substate_labels_list[cal_index]))) axes.set_yticks(np.arange(len(self._substate_labels_list[cal_index]))) axes.set_xticklabels(self._substate_labels_list[cal_index]) axes.set_yticklabels(self._substate_labels_list[cal_index]) if show_plot: plt.show()
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# 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. """Bitstring functions.""" from qiskit import QuantumCircuit def prepare_bitstring(bitstring, name=None): """Prepares bitstrings.""" # First bit in bitstring is the first qubit in the circuit. qcirc = QuantumCircuit(len(bitstring), name=name) for qb_idx, bit in enumerate(bitstring): if bit: qcirc.x(qb_idx) return qcirc
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# 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. """ pauli common functions """ import logging import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.algorithms import AlgorithmError from qiskit.circuit import Parameter, ParameterExpression from qiskit.qasm import pi from qiskit.quantum_info import Pauli # pylint: disable=unused-import logger = logging.getLogger(__name__) # pylint: disable=too-many-arguments,too-many-branches,too-many-locals def pauli_measurement(circuit, pauli, qreg, creg, barrier=False): """ Add the proper post-rotation gate on the circuit. Args: circuit (QuantumCircuit): the circuit to be modified. pauli (Pauli): the pauli will be added. qreg (QuantumRegister): the quantum register associated with the circuit. creg (ClassicalRegister): the classical register associated with the circuit. barrier (bool, optional): whether or not add barrier before measurement. Returns: QuantumCircuit: the original circuit object with post-rotation gate """ num_qubits = pauli.num_qubits for qubit_idx in range(num_qubits): if pauli.x[qubit_idx]: if pauli.z[qubit_idx]: # Measure Y circuit.sdg(qreg[qubit_idx]) # sdg circuit.h(qreg[qubit_idx]) # h else: # Measure X circuit.h(qreg[qubit_idx]) # h if barrier: circuit.barrier(qreg[qubit_idx]) circuit.measure(qreg[qubit_idx], creg[qubit_idx]) return circuit def measure_pauli_z(data, pauli): """ Appropriate post-rotations on the state are assumed. Args: data (dict): a dictionary of the form data = {'00000': 10} ({str: int}) pauli (Pauli): a Pauli object Returns: float: Expected value of paulis given data """ observable = 0.0 num_shots = sum(data.values()) p_z_or_x = np.logical_or(pauli.z, pauli.x) for key, value in data.items(): bitstr = np.asarray(list(key))[::-1].astype(int).astype(bool) # pylint: disable=no-member sign = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p_z_or_x)) else 1.0 observable += sign * value observable /= num_shots return observable def covariance(data, pauli_1, pauli_2, avg_1, avg_2): """ Compute the covariance matrix element between two Paulis, given the measurement outcome. Appropriate post-rotations on the state are assumed. Args: data (dict): a dictionary of the form data = {'00000': 10} ({str:int}) pauli_1 (Pauli): a Pauli class member pauli_2 (Pauli): a Pauli class member avg_1 (float): expectation value of pauli_1 on `data` avg_2 (float): expectation value of pauli_2 on `data` Returns: float: the element of the covariance matrix between two Paulis """ cov = 0.0 num_shots = sum(data.values()) if num_shots == 1: return cov p1_z_or_x = np.logical_or(pauli_1.z, pauli_1.x) p2_z_or_x = np.logical_or(pauli_2.z, pauli_2.x) for key, value in data.items(): bitstr = np.asarray(list(key))[::-1].astype(int).astype(bool) # pylint: disable=no-member sign_1 = ( -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p1_z_or_x)) else 1.0 ) sign_2 = ( -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p2_z_or_x)) else 1.0 ) cov += (sign_1 - avg_1) * (sign_2 - avg_2) * value cov /= num_shots - 1 return cov # pylint: disable=invalid-name def suzuki_expansion_slice_pauli_list(pauli_list, lam_coef, expansion_order): """ Compute the list of pauli terms for a single slice of the suzuki expansion following the paper https://arxiv.org/pdf/quant-ph/0508139.pdf. Args: pauli_list (list[list[complex, Pauli]]): The slice's weighted Pauli list for the suzuki expansion lam_coef (float): The parameter lambda as defined in said paper, adjusted for the evolution time and the number of time slices expansion_order (int): The order for suzuki expansion Returns: list: slice pauli list """ if expansion_order == 1: half = [[lam_coef / 2 * c, p] for c, p in pauli_list] res = half + list(reversed(half)) else: p_k = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1 side_base = suzuki_expansion_slice_pauli_list( pauli_list, lam_coef * p_k, expansion_order - 1 ) side = side_base * 2 middle = suzuki_expansion_slice_pauli_list( pauli_list, lam_coef * (1 - 4 * p_k), expansion_order - 1 ) res = side + middle + side return res def check_commutativity(op_1, op_2, anti=False): """ Check the (anti-)commutativity between two operators. Args: op_1 (WeightedPauliOperator): operator op_2 (WeightedPauliOperator): operator anti (bool): if True, check anti-commutativity, otherwise check commutativity. Returns: bool: whether or not two operators are commuted or anti-commuted. """ com = op_1 * op_2 - op_2 * op_1 if not anti else op_1 * op_2 + op_2 * op_1 com.simplify() return bool(com.is_empty()) # pylint: disable=too-many-statements def evolution_instruction( pauli_list, evo_time, num_time_slices, controlled=False, power=1, use_basis_gates=True, shallow_slicing=False, barrier=False, ): """ Construct the evolution circuit according to the supplied specification. Args: pauli_list (list([[complex, Pauli]])): The list of pauli terms corresponding to a single time slice to be evolved evo_time (Union(complex, float, Parameter, ParameterExpression)): The evolution time num_time_slices (int): The number of time slices for the expansion controlled (bool, optional): Controlled circuit or not power (int, optional): The power to which the unitary operator is to be raised use_basis_gates (bool, optional): boolean flag for indicating only using basis gates when building circuit. shallow_slicing (bool, optional): boolean flag for indicating using shallow qc.data reference repetition for slicing barrier (bool, optional): whether or not add barrier for every slice Returns: Instruction: The Instruction corresponding to specified evolution. Raises: AlgorithmError: power must be an integer and greater or equal to 1 ValueError: Unrecognized pauli """ if not isinstance(power, int) or power < 1: raise AlgorithmError("power must be an integer and greater or equal to 1.") state_registers = QuantumRegister(pauli_list[0][1].num_qubits) if controlled: inst_name = f"Controlled-Evolution^{power}" ancillary_registers = QuantumRegister(1) qc_slice = QuantumCircuit(state_registers, ancillary_registers, name=inst_name) else: inst_name = f"Evolution^{power}" qc_slice = QuantumCircuit(state_registers, name=inst_name) # for each pauli [IXYZ]+, record the list of qubit pairs needing CX's cnot_qubit_pairs = [None] * len(pauli_list) # for each pauli [IXYZ]+, record the highest index of the nontrivial pauli gate (X,Y, or Z) top_xyz_pauli_indices = [-1] * len(pauli_list) for pauli_idx, pauli in enumerate(reversed(pauli_list)): n_qubits = pauli[1].num_qubits # changes bases if necessary nontrivial_pauli_indices = [] for qubit_idx in range(n_qubits): # pauli I if not pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]: continue if cnot_qubit_pairs[pauli_idx] is None: nontrivial_pauli_indices.append(qubit_idx) if pauli[1].x[qubit_idx]: # pauli X if not pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.h(state_registers[qubit_idx]) else: qc_slice.h(state_registers[qubit_idx]) # pauli Y elif pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u(pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx]) else: qc_slice.rx(pi / 2, state_registers[qubit_idx]) # pauli Z elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]: pass else: raise ValueError(f"Unrecognized pauli: {pauli[1]}") if nontrivial_pauli_indices: top_xyz_pauli_indices[pauli_idx] = nontrivial_pauli_indices[-1] # insert lhs cnot gates if cnot_qubit_pairs[pauli_idx] is None: cnot_qubit_pairs[pauli_idx] = list( zip( sorted(nontrivial_pauli_indices)[:-1], sorted(nontrivial_pauli_indices)[1:], ) ) for pair in cnot_qubit_pairs[pauli_idx]: qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]]) # insert Rz gate if top_xyz_pauli_indices[pauli_idx] >= 0: # Because Parameter does not support complexity number operation; thus, we do # the following tricks to generate parameterized instruction. # We assume the coefficient in the pauli is always real. and can not do imaginary time # evolution if isinstance(evo_time, (Parameter, ParameterExpression)): lam = 2.0 * pauli[0] / num_time_slices lam = lam.real if lam.imag == 0 else lam lam = lam * evo_time else: lam = (2.0 * pauli[0] * evo_time / num_time_slices).real if not controlled: if use_basis_gates: qc_slice.p(lam, state_registers[top_xyz_pauli_indices[pauli_idx]]) else: qc_slice.rz(lam, state_registers[top_xyz_pauli_indices[pauli_idx]]) else: if use_basis_gates: qc_slice.p( lam / 2, state_registers[top_xyz_pauli_indices[pauli_idx]] ) qc_slice.cx( ancillary_registers[0], state_registers[top_xyz_pauli_indices[pauli_idx]], ) qc_slice.p( -lam / 2, state_registers[top_xyz_pauli_indices[pauli_idx]] ) qc_slice.cx( ancillary_registers[0], state_registers[top_xyz_pauli_indices[pauli_idx]], ) else: qc_slice.crz( lam, ancillary_registers[0], state_registers[top_xyz_pauli_indices[pauli_idx]], ) # insert rhs cnot gates for pair in reversed(cnot_qubit_pairs[pauli_idx]): qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]]) # revert bases if necessary for qubit_idx in range(n_qubits): if pauli[1].x[qubit_idx]: # pauli X if not pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.h(state_registers[qubit_idx]) else: qc_slice.h(state_registers[qubit_idx]) # pauli Y elif pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u(-pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx]) else: qc_slice.rx(-pi / 2, state_registers[qubit_idx]) # repeat the slice if shallow_slicing: logger.info( "Under shallow slicing mode, the qc.data reference is repeated shallowly. " "Thus, changing gates of one slice of the output circuit might affect " "other slices." ) if barrier: qc_slice.barrier(state_registers) qc_slice.data *= num_time_slices * power qc = qc_slice else: qc = QuantumCircuit(*qc_slice.qregs, name=inst_name) for _ in range(num_time_slices * power): qc.append(qc_slice, qc.qubits) if barrier: qc.barrier(state_registers) return qc.to_instruction()
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# 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. """ Weighted Pauli Operator """ import itertools import json import logging import sys from copy import deepcopy from operator import add as op_add, sub as op_sub from typing import List, Optional, Tuple, Union import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.algorithms import AlgorithmError from qiskit.quantum_info import Pauli from qiskit.tools import parallel_map from qiskit.tools.events import TextProgressBar from qiskit.utils import algorithm_globals from .base_operator import LegacyBaseOperator from .common import ( measure_pauli_z, covariance, pauli_measurement, suzuki_expansion_slice_pauli_list, check_commutativity, evolution_instruction, ) logger = logging.getLogger(__name__) # pylint: disable=invalid-name,too-many-lines,too-many-arguments,protected-access,no-else-return,too-many-locals # pylint: disable=too-many-branches,too-many-public-methods # pylint: disable=duplicate-code class WeightedPauliOperator(LegacyBaseOperator): """Weighted Pauli Operator""" def __init__( self, paulis: List[List[Union[complex, Pauli]]], basis: Optional[List[Tuple[object, List[int]]]] = None, z2_symmetries: "Z2Symmetries" = None, atol: float = 1e-12, name: Optional[str] = None, ) -> None: """ Args: paulis: the list of weighted Paulis, where a weighted pauli is composed of a length-2 list and the first item is the weight and the second item is the Pauli object. basis: the grouping basis, each element is a tuple composed of the basis and the indices to paulis which belong to that group. e.g., if tpb basis is used, the object will be a pauli. By default, the group is equal to non-grouping, each pauli is its own basis. z2_symmetries: recording the z2 symmetries info atol: the threshold used in truncating paulis name: the name of operator. """ super().__init__(basis, z2_symmetries, name) # plain store the paulis, the group information is store in the basis self._paulis_table = None self._paulis = paulis self._basis = ( [(pauli[1], [i]) for i, pauli in enumerate(paulis)] if basis is None else basis ) # combine the paulis and remove those with zero weight self.simplify() self._atol = atol @classmethod def from_list(cls, paulis, weights=None, name=None): """ Create a WeightedPauliOperator via a pair of list. Args: paulis (list[Pauli]): the list of Paulis weights (list[complex], optional): the list of weights, if it is None, all weights are 1. name (str, optional): name of the operator. Returns: WeightedPauliOperator: operator Raises: ValueError: The length of weights and paulis must be the same """ if weights is not None and len(weights) != len(paulis): raise ValueError("The length of weights and paulis must be the same.") if weights is None: weights = [1.0] * len(paulis) return cls(paulis=[[w, p] for w, p in zip(weights, paulis)], name=name) # pylint: disable=arguments-differ def to_opflow(self, reverse_endianness=False): """to op flow""" # pylint: disable=import-outside-toplevel from qiskit.opflow import PrimitiveOp pauli_ops = [] for [w, p] in self.paulis: pauli = Pauli(str(p)[::-1]) if reverse_endianness else p # This weighted pauli operator has the coeff stored as a complex type # irrespective of whether the value has any imaginary part or not. # For many operators the coeff will be real. Hence below the coeff is made real, # when creating the PrimitiveOp, since it can be stored then as a float, if its # value is real, i.e. has no imaginary part. This avoids any potential issues around # complex - but if there are complex coeffs then maybe that using the opflow # later will fail if it happens to be used where complex is not supported. # Now there are imaginary coefficients in UCCSD that would need to be handled # when this is converted to opflow (evolution of hopping operators) where currently # Terra does not handle complex. # TODO fix these or add support for them in Terra # pylint: disable=fixme coeff = np.real(w) if np.isreal(w) else w pauli_ops += [PrimitiveOp(pauli, coeff=coeff)] return sum(pauli_ops) @property def paulis(self): """get paulis""" return self._paulis @property def atol(self): """get atol""" return self._atol @atol.setter def atol(self, new_value): """set atol""" self._atol = new_value @property def num_qubits(self): """ Number of qubits required for the operator. Returns: int: number of qubits """ if not self.is_empty(): res = self._paulis[0][1].num_qubits else: logger.warning("Operator is empty, Return 0.") res = 0 return res def __eq__(self, other): """Overload == operation""" # need to clean up the zeros self.simplify() other.simplify() if len(self._paulis) != len(other.paulis): return False for weight, pauli in self._paulis: found_pauli = False other_weight = 0.0 for weight2, pauli2 in other.paulis: if pauli == pauli2: found_pauli = True other_weight = weight2 break if ( not found_pauli and other_weight != 0.0 ): # since we might have 0 weights of paulis. return False if weight != other_weight: return False return True def _add_or_sub(self, other, operation, copy=True): """ Add two operators either extend (in-place) or combine (copy) them. The addition performs optimized combination of two operators. If `other` has identical basis, the coefficient are combined rather than appended. Args: other (WeightedPauliOperator): to-be-combined operator operation (callable or str): add or sub callable from operator copy (bool): working on a copy or self Returns: WeightedPauliOperator: operator Raises: AlgorithmError: two operators have different number of qubits. """ if not self.is_empty() and not other.is_empty(): if self.num_qubits != other.num_qubits: raise AlgorithmError( "Can not add/sub two operators " "with different number of qubits." ) ret_op = self.copy() if copy else self for pauli in other.paulis: pauli_label = pauli[1].to_label() idx = ret_op._paulis_table.get(pauli_label, None) if idx is not None: ret_op._paulis[idx][0] = operation(ret_op._paulis[idx][0], pauli[0]) else: new_pauli = deepcopy(pauli) ret_op._paulis_table[pauli_label] = len(ret_op._paulis) ret_op._basis.append((new_pauli[1], [len(ret_op._paulis)])) new_pauli[0] = operation(0.0, pauli[0]) ret_op._paulis.append(new_pauli) return ret_op def add(self, other, copy=False): """ Perform self + other. Args: other (WeightedPauliOperator): to-be-combined operator copy (bool): working on a copy or self, if False, the results are written back to self. Returns: WeightedPauliOperator: operator """ return self._add_or_sub(other, op_add, copy=copy) def sub(self, other, copy=False): """ Perform self - other. Args: other (WeightedPauliOperator): to-be-combined operator copy (bool): working on a copy or self, if False, the results are written back to self. Returns: WeightedPauliOperator: operator """ return self._add_or_sub(other, op_sub, copy=copy) def __add__(self, other): """Overload + operator""" return self.add(other, copy=True) def __iadd__(self, other): """Overload += operator""" return self.add(other, copy=False) def __sub__(self, other): """Overload - operator""" return self.sub(other, copy=True) def __isub__(self, other): """Overload -= operator""" return self.sub(other, copy=False) def _scaling_weight(self, scaling_factor, copy=False): """ Constantly scaling all weights of paulis. Args: scaling_factor (complex): the scaling factor copy (bool): return a copy or modify in-place Returns: WeightedPauliOperator: a copy of the scaled one. Raises: ValueError: the scaling factor is not a valid type. """ if not isinstance(scaling_factor, (int, float, complex)): raise ValueError( f"Type of scaling factor is a valid type. {scaling_factor.__class__} if given." ) ret = self.copy() if copy else self for idx in range(len(ret._paulis)): # pylint: disable=consider-using-enumerate ret._paulis[idx] = [ ret._paulis[idx][0] * scaling_factor, ret._paulis[idx][1], ] return ret def multiply(self, other): """ Perform self * other, and the phases are tracked. Args: other (WeightedPauliOperator): an operator Returns: WeightedPauliOperator: the multiplied operator """ ret_op = WeightedPauliOperator(paulis=[]) for existed_weight, existed_pauli in self.paulis: for weight, pauli in other.paulis: p = existed_pauli.dot(pauli) new_pauli, sign = p[:], (-1j) ** p.phase new_weight = existed_weight * weight * sign pauli_term = [new_weight, new_pauli] ret_op += WeightedPauliOperator(paulis=[pauli_term]) return ret_op def __rmul__(self, other): """Overload other * self""" if isinstance(other, (int, float, complex)): return self._scaling_weight(other, copy=True) else: return other.multiply(self) def __mul__(self, other): """Overload self * other""" if isinstance(other, (int, float, complex)): return self._scaling_weight(other, copy=True) else: return self.multiply(other) def __neg__(self): """Overload unary -""" return self._scaling_weight(-1.0, copy=True) def __str__(self): """Overload str()""" curr_repr = "paulis" length = len(self._paulis) name = "" if self._name == "" else f"{self._name}: " ret = f"{name}Representation: {curr_repr}, qubits: {self.num_qubits}, size: {length}" return ret def print_details(self): """ Print out the operator in details. Returns: str: a formatted string describes the operator. """ if self.is_empty(): return "Operator is empty." ret = "" for weight, pauli in self._paulis: ret = "".join([ret, f"{pauli.to_label()}\t{weight}\n"]) return ret def copy(self): """Get a copy of self""" return deepcopy(self) def simplify(self, copy=False): """ Merge the paulis whose bases are identical and the pauli with zero coefficient would be removed. Note: This behavior of this method is slightly changed, it will remove the paulis whose weights are zero. Args: copy (bool): simplify on a copy or self Returns: WeightedPauliOperator: the simplified operator """ op = self.copy() if copy else self new_paulis = [] new_paulis_table = {} old_to_new_indices = {} curr_idx = 0 for curr_weight, curr_pauli in op.paulis: pauli_label = curr_pauli.to_label() new_idx = new_paulis_table.get(pauli_label, None) if new_idx is not None: new_paulis[new_idx][0] += curr_weight old_to_new_indices[curr_idx] = new_idx else: new_paulis_table[pauli_label] = len(new_paulis) old_to_new_indices[curr_idx] = len(new_paulis) new_paulis.append([curr_weight, curr_pauli]) curr_idx += 1 op._paulis = new_paulis op._paulis_table = new_paulis_table # update the grouping info, since this method only reduce the number # of paulis, we can handle it here for both # pauli and tpb grouped pauli # should have a better way to rebuild the basis here. new_basis = [] for basis, indices in op.basis: new_indices = [] found = False if new_basis: for b, ind in new_basis: if b == basis: new_indices = ind found = True break for idx in indices: new_idx = old_to_new_indices[idx] if new_idx is not None and new_idx not in new_indices: new_indices.append(new_idx) if new_indices and not found: new_basis.append((basis, new_indices)) op._basis = new_basis op.chop(0.0) return op def rounding(self, decimals, copy=False): """ Rounding the weight. Args: decimals (int): rounding the weight to the decimals. copy (bool): chop on a copy or self Returns: WeightedPauliOperator: operator """ op = self.copy() if copy else self op._paulis = [ [np.around(weight, decimals=decimals), pauli] for weight, pauli in op.paulis ] return op def chop(self, threshold=None, copy=False): """ Eliminate the real and imagine part of weight in each pauli by `threshold`. If pauli's weight is less then `threshold` in both real and imaginary parts, the pauli is removed. Note: If weight is real-only, the imaginary part is skipped. Args: threshold (float): the threshold is used to remove the paulis copy (bool): chop on a copy or self Returns: WeightedPauliOperator: if copy is True, the original operator is unchanged; otherwise, the operator is mutated. """ threshold = self._atol if threshold is None else threshold def chop_real_imag(weight): temp_real = weight.real if np.absolute(weight.real) >= threshold else 0.0 temp_imag = weight.imag if np.absolute(weight.imag) >= threshold else 0.0 if temp_real == 0.0 and temp_imag == 0.0: return 0.0 else: new_weight = temp_real + 1j * temp_imag return new_weight op = self.copy() if copy else self if op.is_empty(): return op paulis = [] old_to_new_indices = {} curr_idx = 0 for idx, weighted_pauli in enumerate(op.paulis): weight, pauli = weighted_pauli new_weight = chop_real_imag(weight) if new_weight != 0.0: old_to_new_indices[idx] = curr_idx curr_idx += 1 paulis.append([new_weight, pauli]) op._paulis = paulis op._paulis_table = { weighted_pauli[1].to_label(): i for i, weighted_pauli in enumerate(paulis) } # update the grouping info, since this method only remove pauli, # we can handle it here for both # pauli and tpb grouped pauli new_basis = [] for basis, indices in op.basis: new_indices = [] for idx in indices: new_idx = old_to_new_indices.get(idx, None) if new_idx is not None: new_indices.append(new_idx) if new_indices: new_basis.append((basis, new_indices)) op._basis = new_basis return op def commute_with(self, other): """Commutes with""" return check_commutativity(self, other) def anticommute_with(self, other): """Anti commutes with""" return check_commutativity(self, other, anti=True) def is_empty(self): """ Check Operator is empty or not. Returns: bool: True if empty, False otherwise """ if not self._paulis: return True elif not self._paulis[0]: return True else: return False @classmethod def from_file(cls, file_name, before_04=False): """ Load paulis in a file to construct an Operator. Args: file_name (str): path to the file, which contains a list of Paulis and coefficients. before_04 (bool): support the format before Aqua 0.4. Returns: WeightedPauliOperator: the loaded operator. """ with open(file_name, "r", encoding="UTF-8") as file: return cls.from_dict(json.load(file), before_04=before_04) def to_file(self, file_name): """ Save operator to a file in pauli representation. Args: file_name (str): path to the file """ with open(file_name, "w", encoding="UTF-8") as file: json.dump(self.to_dict(), file) @classmethod def from_dict(cls, dictionary, before_04=False): """ Load paulis from a dictionary to construct an Operator. The dictionary must comprise the key 'paulis' having a value which is an array of pauli dicts. Each dict in this array must be represented by label and coeff (real and imag) such as in the following example: .. code-block:: python {'paulis': [ {'label': 'IIII', 'coeff': {'real': -0.33562957575267038, 'imag': 0.0}}, {'label': 'ZIII', 'coeff': {'real': 0.28220597164664896, 'imag': 0.0}}, ... ] } Args: dictionary (dict): dictionary, which contains a list of Paulis and coefficients. before_04 (bool): support the format before Aqua 0.4. Returns: WeightedPauliOperator: the operator created from the input dictionary. Raises: AlgorithmError: Invalid dictionary """ if "paulis" not in dictionary: raise AlgorithmError('Dictionary missing "paulis" key') paulis = [] for op in dictionary["paulis"]: if "label" not in op: raise AlgorithmError('Dictionary missing "label" key') pauli_label = op["label"] if "coeff" not in op: raise AlgorithmError('Dictionary missing "coeff" key') pauli_coeff = op["coeff"] if "real" not in pauli_coeff: raise AlgorithmError('Dictionary missing "real" key') coeff = pauli_coeff["real"] if "imag" in pauli_coeff: coeff = complex(pauli_coeff["real"], pauli_coeff["imag"]) pauli_label = pauli_label[::-1] if before_04 else pauli_label paulis.append([coeff, Pauli(pauli_label)]) return cls(paulis=paulis) def to_dict(self): """ Save operator to a dict in pauli representation. Returns: dict: a dictionary contains an operator with pauli representation. """ ret_dict = {"paulis": []} for coeff, pauli in self._paulis: op = {"label": pauli.to_label()} if isinstance(coeff, complex): op["coeff"] = {"real": np.real(coeff), "imag": np.imag(coeff)} else: op["coeff"] = {"real": coeff} ret_dict["paulis"].append(op) return ret_dict # pylint: disable=arguments-differ def construct_evaluation_circuit( self, wave_function, statevector_mode, qr=None, cr=None, use_simulator_snapshot_mode=False, circuit_name_prefix="", ): r""" Construct the circuits for evaluation, which calculating the expectation <psi\|H\|psi>. At statevector mode: to simplify the computation, we do not build the whole circuit for <psi|H|psi>, instead of that we construct an individual circuit <psi\|, and a bundle circuit for H\|psi> Args: wave_function (QuantumCircuit): the quantum circuit. statevector_mode (bool): indicate which type of simulator are going to use. qr (QuantumRegister, optional): the quantum register associated with the input_circuit cr (ClassicalRegister, optional): the classical register associated with the input_circuit use_simulator_snapshot_mode (bool, optional): if aer_provider is used, we can do faster evaluation for pauli mode on statevector simulation circuit_name_prefix (str, optional): a prefix of circuit name Returns: list[QuantumCircuit]: a list of quantum circuits and each circuit with a unique name: circuit_name_prefix + Pauli string Raises: AlgorithmError: if Operator is empty AlgorithmError: if quantum register is not provided explicitly and cannot find quantum register with `q` as the name AlgorithmError: The provided qreg is not in the wave_function """ if self.is_empty(): raise AlgorithmError("Operator is empty, check the operator.") # pylint: disable=import-outside-toplevel from qiskit.utils.run_circuits import find_regs_by_name if qr is None: qr = find_regs_by_name(wave_function, "q") if qr is None: raise AlgorithmError( "Either provide the quantum register " "(qreg) explicitly or use `q` as the name " "of the quantum register in the input circuit." ) else: if not wave_function.has_register(qr): raise AlgorithmError( "The provided QuantumRegister (qreg) is not in the circuit." ) n_qubits = self.num_qubits instructions = self.evaluation_instruction( statevector_mode, use_simulator_snapshot_mode ) circuits = [] if use_simulator_snapshot_mode: circuit = wave_function.copy(name=circuit_name_prefix + "snapshot_mode") # Add expectation value snapshot instruction instr = instructions.get("expval_snapshot", None) if instr is not None: circuit.append(instr, qr) circuits.append(circuit) elif statevector_mode: circuits.append(wave_function.copy(name=circuit_name_prefix + "psi")) for _, pauli in self._paulis: inst = instructions.get(pauli.to_label(), None) if inst is not None: circuit = wave_function.copy( name=circuit_name_prefix + pauli.to_label() ) circuit.append(inst, qr) circuits.append(circuit) else: base_circuit = wave_function.copy() if cr is not None: if not base_circuit.has_register(cr): base_circuit.add_register(cr) else: cr = find_regs_by_name(base_circuit, "c", qreg=False) if cr is None: cr = ClassicalRegister(n_qubits, name="c") base_circuit.add_register(cr) for basis, _ in self._basis: circuit = base_circuit.copy(name=circuit_name_prefix + basis.to_label()) circuit.append(instructions[basis.to_label()], qargs=qr, cargs=cr) circuits.append(circuit) return circuits def evaluation_instruction( self, statevector_mode, use_simulator_snapshot_mode=False ): """ Args: statevector_mode (bool): will it be run on statevector simulator or not use_simulator_snapshot_mode (bool): will it use qiskit aer simulator operator mode Returns: dict: Pauli-instruction pair. Raises: AlgorithmError: if Operator is empty MissingOptionalLibraryError: qiskit-aer not installed """ if self.is_empty(): raise AlgorithmError("Operator is empty, check the operator.") instructions = {} qr = QuantumRegister(self.num_qubits) qc = QuantumCircuit(qr) if statevector_mode: for _, pauli in self._paulis: tmp_qc = qc.copy(name="Pauli " + pauli.to_label()) if np.all(np.logical_not(pauli.z)) and np.all( np.logical_not(pauli.x) ): # all I continue # This explicit barrier is needed for statevector simulator since Qiskit-terra # will remove global phase at default compilation level but the results here # rely on global phase. tmp_qc.barrier(list(range(self.num_qubits))) tmp_qc.append(pauli.to_instruction(), list(range(self.num_qubits))) instructions[pauli.to_label()] = tmp_qc.to_instruction() else: cr = ClassicalRegister(self.num_qubits) qc.add_register(cr) for basis, _ in self._basis: tmp_qc = qc.copy(name="Pauli " + basis.to_label()) tmp_qc = pauli_measurement(tmp_qc, basis, qr, cr, barrier=True) instructions[basis.to_label()] = tmp_qc.to_instruction() return instructions # pylint: disable=arguments-differ def evaluate_with_result( self, result, statevector_mode, use_simulator_snapshot_mode=False, circuit_name_prefix="", ): """ This method can be only used with the circuits generated by the :meth:`construct_evaluation_circuit` method with the same `circuit_name_prefix` name since the circuit names are tied to some meanings. Calculate the evaluated value with the measurement results. Args: result (qiskit.Result): the result from the backend. statevector_mode (bool): indicate which type of simulator are used. use_simulator_snapshot_mode (bool): if aer_provider is used, we can do faster evaluation for pauli mode on statevector simulation circuit_name_prefix (str): a prefix of circuit name Returns: float: the mean value float: the standard deviation Raises: AlgorithmError: if Operator is empty """ if self.is_empty(): raise AlgorithmError("Operator is empty, check the operator.") avg, std_dev, variance = 0.0, 0.0, 0.0 if use_simulator_snapshot_mode: snapshot_data = result.data(circuit_name_prefix + "snapshot_mode")[ "snapshots" ] avg = snapshot_data["expectation_value"]["expval"][0]["value"] if isinstance(avg, (list, tuple)): # Aer versions before 0.4 use a list snapshot format # which must be converted to a complex value. avg = avg[0] + 1j * avg[1] elif statevector_mode: quantum_state = np.asarray( result.get_statevector(circuit_name_prefix + "psi") ) for weight, pauli in self._paulis: # all I if np.all(np.logical_not(pauli.z)) and np.all(np.logical_not(pauli.x)): avg += weight else: quantum_state_i = result.get_statevector( circuit_name_prefix + pauli.to_label() ) avg += weight * (np.vdot(quantum_state, quantum_state_i)) else: if logger.isEnabledFor(logging.DEBUG): logger.debug("Computing the expectation from measurement results:") TextProgressBar(sys.stderr) # pick the first result to get the total number of shots num_shots = sum(list(result.get_counts(0).values())) results = parallel_map( WeightedPauliOperator._routine_compute_mean_and_var, [ ( [self._paulis[idx] for idx in indices], result.get_counts(circuit_name_prefix + basis.to_label()), ) for basis, indices in self._basis ], num_processes=algorithm_globals.num_processes, ) for res in results: avg += res[0] variance += res[1] std_dev = np.sqrt(variance / num_shots) return avg, std_dev @staticmethod def _routine_compute_mean_and_var(args): paulis, measured_results = args avg_paulis = [] avg = 0.0 variance = 0.0 for weight, pauli in paulis: observable = measure_pauli_z(measured_results, pauli) avg += weight * observable avg_paulis.append(observable) for idx_1, weighted_pauli_1 in enumerate(paulis): weight_1, pauli_1 = weighted_pauli_1 for idx_2, weighted_pauli_2 in enumerate(paulis): weight_2, pauli_2 = weighted_pauli_2 variance += ( weight_1 * weight_2 * covariance( measured_results, pauli_1, pauli_2, avg_paulis[idx_1], avg_paulis[idx_2], ) ) return avg, variance def reorder_paulis(self) -> List[List[Union[complex, Pauli]]]: """ Reorder the paulis based on the basis and return the reordered paulis. Returns: the ordered paulis based on the basis. """ # if each pauli belongs to its group, no reordering it needed. if len(self._basis) == len(self._paulis): return self._paulis paulis = [] new_basis = [] curr_count = 0 for basis, indices in self._basis: sub_paulis = [] for idx in indices: sub_paulis.append(self._paulis[idx]) new_basis.append((basis, range(curr_count, curr_count + len(sub_paulis)))) paulis.extend(sub_paulis) curr_count += len(sub_paulis) self._paulis = paulis self._basis = new_basis return self._paulis # pylint: disable=arguments-differ def evolve( self, state_in=None, evo_time=0, num_time_slices=1, quantum_registers=None, expansion_mode="trotter", expansion_order=1, ): """ Carry out the eoh evolution for the operator under supplied specifications. Args: state_in (QuantumCircuit): a circuit describes the input state evo_time (Union(complex, float, Parameter, ParameterExpression)): The evolution time num_time_slices (int): The number of time slices for the expansion quantum_registers (QuantumRegister): The QuantumRegister to build the QuantumCircuit off of expansion_mode (str): The mode under which the expansion is to be done. Currently support 'trotter', which follows the expansion as discussed in http://science.sciencemag.org/content/273/5278/1073, and 'suzuki', which corresponds to the discussion in https://arxiv.org/pdf/quant-ph/0508139.pdf expansion_order (int): The order for suzuki expansion Returns: QuantumCircuit: The constructed circuit. Raises: AlgorithmError: quantum_registers must be in the provided state_in circuit AlgorithmError: if operator is empty """ if self.is_empty(): raise AlgorithmError("Operator is empty, can not evolve.") if state_in is not None and quantum_registers is not None: if not state_in.has_register(quantum_registers): raise AlgorithmError( "quantum_registers must be in the provided state_in circuit." ) elif state_in is None and quantum_registers is None: quantum_registers = QuantumRegister(self.num_qubits) qc = QuantumCircuit(quantum_registers) elif state_in is not None and quantum_registers is None: # assuming the first register is for evolve quantum_registers = state_in.qregs[0] qc = QuantumCircuit() + state_in else: qc = QuantumCircuit(quantum_registers) instruction = self.evolve_instruction( evo_time, num_time_slices, expansion_mode, expansion_order ) qc.append(instruction, quantum_registers) return qc def evolve_instruction( self, evo_time=0, num_time_slices=1, expansion_mode="trotter", expansion_order=1 ): """ Carry out the eoh evolution for the operator under supplied specifications. Args: evo_time (Union(complex, float, Parameter, ParameterExpression)): The evolution time num_time_slices (int): The number of time slices for the expansion expansion_mode (str): The mode under which the expansion is to be done. Currently support 'trotter', which follows the expansion as discussed in http://science.sciencemag.org/content/273/5278/1073, and 'suzuki', which corresponds to the discussion in https://arxiv.org/pdf/quant-ph/0508139.pdf expansion_order (int): The order for suzuki expansion Returns: QuantumCircuit: The constructed QuantumCircuit. Raises: ValueError: Number of time slices should be a non-negative integer NotImplementedError: expansion mode not supported AlgorithmError: if operator is empty """ if self.is_empty(): raise AlgorithmError("Operator is empty, can not build evolve instruction.") # pylint: disable=no-member if num_time_slices <= 0 or not isinstance(num_time_slices, int): raise ValueError("Number of time slices should be a non-negative integer.") if expansion_mode not in ["trotter", "suzuki"]: raise NotImplementedError(f"Expansion mode {expansion_mode} not supported.") pauli_list = self.reorder_paulis() if len(pauli_list) == 1: slice_pauli_list = pauli_list else: if expansion_mode == "trotter": slice_pauli_list = pauli_list # suzuki expansion else: slice_pauli_list = suzuki_expansion_slice_pauli_list( pauli_list, 1, expansion_order ) instruction = evolution_instruction(slice_pauli_list, evo_time, num_time_slices) return instruction class Z2Symmetries: """Z2 Symmetries""" def __init__(self, symmetries, sq_paulis, sq_list, tapering_values=None): """ Args: symmetries (list[Pauli]): the list of Pauli objects representing the Z_2 symmetries sq_paulis (list[Pauli]): the list of single - qubit Pauli objects to construct the Clifford operators sq_list (list[int]): the list of support of the single-qubit Pauli objects used to build the Clifford operators tapering_values (list[int], optional): values determines the sector. Raises: AlgorithmError: Invalid paulis """ if len(symmetries) != len(sq_paulis): raise AlgorithmError( "Number of Z2 symmetries has to be the same as number " "of single-qubit pauli x." ) if len(sq_paulis) != len(sq_list): raise AlgorithmError( "Number of single-qubit pauli x has to be the same " "as length of single-qubit list." ) if tapering_values is not None: if len(sq_list) != len(tapering_values): raise AlgorithmError( "The length of single-qubit list has " "to be the same as length of tapering values." ) self._symmetries = symmetries self._sq_paulis = sq_paulis self._sq_list = sq_list self._tapering_values = tapering_values @property def symmetries(self): """return symmetries""" return self._symmetries @property def sq_paulis(self): """returns sq paulis""" return self._sq_paulis @property def cliffords(self): """ Get clifford operators, build based on symmetries and single-qubit X. Returns: list[WeightedPauliOperator]: a list of unitaries used to diagonalize the Hamiltonian. """ cliffords = [ WeightedPauliOperator( paulis=[[1 / np.sqrt(2), pauli_symm], [1 / np.sqrt(2), sq_pauli]] ) for pauli_symm, sq_pauli in zip(self._symmetries, self._sq_paulis) ] return cliffords @property def sq_list(self): """returns sq list""" return self._sq_list @property def tapering_values(self): """returns tapering values""" return self._tapering_values @tapering_values.setter def tapering_values(self, new_value): """set tapering values""" self._tapering_values = new_value def __str__(self): ret = ["Z2 symmetries:"] ret.append("Symmetries:") for symmetry in self._symmetries: ret.append(symmetry.to_label()) ret.append("Single-Qubit Pauli X:") for x in self._sq_paulis: ret.append(x.to_label()) ret.append("Cliffords:") for c in self.cliffords: ret.append(c.print_details()) ret.append("Qubit index:") ret.append(str(self._sq_list)) ret.append("Tapering values:") if self._tapering_values is None: possible_values = [ str(list(coeff)) for coeff in itertools.product([1, -1], repeat=len(self._sq_list)) ] possible_values = ", ".join(x for x in possible_values) ret.append(" - Possible values: " + possible_values) else: ret.append(str(self._tapering_values)) ret = "\n".join(ret) return ret def copy(self) -> "Z2Symmetries": """ Get a copy of self. Returns: copy """ return deepcopy(self) def is_empty(self): """ Check the z2_symmetries is empty or not. Returns: bool: empty """ if self._symmetries != [] and self._sq_paulis != [] and self._sq_list != []: return False else: return True def taper(self, operator, tapering_values=None): """ Taper an operator based on the z2_symmetries info and sector defined by `tapering_values`. The `tapering_values` will be stored into the resulted operator for a record. Args: operator (WeightedPauliOperator): the to-be-tapered operator. tapering_values (list[int], optional): if None, returns operators at each sector; otherwise, returns the operator located in that sector. Returns: list[WeightedPauliOperator] or WeightedPauliOperator: If tapering_values is None: [:class`WeightedPauliOperator`]; otherwise, :class:`WeightedPauliOperator` Raises: AlgorithmError: Z2 symmetries, single qubit pauli and single qubit list cannot be empty """ if not self._symmetries or not self._sq_paulis or not self._sq_list: raise AlgorithmError( "Z2 symmetries, single qubit pauli and " "single qubit list cannot be empty." ) if operator.is_empty(): logger.warning("The operator is empty, return the empty operator directly.") return operator for clifford in self.cliffords: operator = clifford * operator * clifford tapering_values = ( tapering_values if tapering_values is not None else self._tapering_values ) def _taper(op, curr_tapering_values): z2_symmetries = self.copy() z2_symmetries.tapering_values = curr_tapering_values operator_out = WeightedPauliOperator( paulis=[], z2_symmetries=z2_symmetries, name=operator.name ) for pauli_term in op.paulis: coeff_out = pauli_term[0] for idx, qubit_idx in enumerate(self._sq_list): if not ( not pauli_term[1].z[qubit_idx] and not pauli_term[1].x[qubit_idx] ): coeff_out = curr_tapering_values[idx] * coeff_out z_temp = np.delete(pauli_term[1].z.copy(), np.asarray(self._sq_list)) x_temp = np.delete(pauli_term[1].x.copy(), np.asarray(self._sq_list)) pauli_term_out = WeightedPauliOperator( paulis=[[coeff_out, Pauli((z_temp, x_temp))]] ) operator_out += pauli_term_out operator_out.chop(0.0) return operator_out if tapering_values is None: tapered_ops = [] for coeff in itertools.product([1, -1], repeat=len(self._sq_list)): tapered_ops.append(_taper(operator, list(coeff))) else: tapered_ops = _taper(operator, tapering_values) return tapered_ops @staticmethod def two_qubit_reduction(operator, num_particles): """ Eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions Chemistry specific method: It can be used to taper two qubits in parity and binary-tree mapped fermionic Hamiltonians when the spin orbitals are ordered in two spin sectors, (block spin order) according to the number of particles in the system. Args: operator (WeightedPauliOperator): the operator num_particles (Union(list, int)): number of particles, if it is a list, the first number is alpha and the second number if beta. Returns: WeightedPauliOperator: a new operator whose qubit number is reduced by 2. """ if operator.is_empty(): logger.info( "Operator is empty, can not do two qubit reduction. " "Return the empty operator back." ) return operator if isinstance(num_particles, (tuple, list)): num_alpha = num_particles[0] num_beta = num_particles[1] else: num_alpha = num_particles // 2 num_beta = num_particles // 2 par_1 = 1 if (num_alpha + num_beta) % 2 == 0 else -1 par_2 = 1 if num_alpha % 2 == 0 else -1 tapering_values = [par_2, par_1] num_qubits = operator.num_qubits last_idx = num_qubits - 1 mid_idx = num_qubits // 2 - 1 sq_list = [mid_idx, last_idx] # build symmetries, sq_paulis: symmetries, sq_paulis = [], [] for idx in sq_list: pauli_str = ["I"] * num_qubits pauli_str[idx] = "Z" z_sym = Pauli("".join(pauli_str)[::-1]) symmetries.append(z_sym) pauli_str[idx] = "X" sq_pauli = Pauli("".join(pauli_str)[::-1]) sq_paulis.append(sq_pauli) z2_symmetries = Z2Symmetries(symmetries, sq_paulis, sq_list, tapering_values) return z2_symmetries.taper(operator) def consistent_tapering(self, operator): """ Tapering the `operator` with the same manner of how this tapered operator is created. i.e., using the same Cliffords and tapering values. Args: operator (WeightedPauliOperator): the to-be-tapered operator Returns: TaperedWeightedPauliOperator: the tapered operator Raises: AlgorithmError: The given operator does not commute with the symmetry """ if operator.is_empty(): raise AlgorithmError("Can not taper an empty operator.") for symmetry in self._symmetries: if not operator.commute_with(symmetry): raise AlgorithmError( "The given operator does not commute with " "the symmetry, can not taper it." ) return self.taper(operator)
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# 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. """Integration tests for EntanglementForgedVQE module.""" # pylint: disable=wrong-import-position import unittest import os import numpy as np from qiskit import BasicAer from qiskit.circuit import Parameter, QuantumCircuit from qiskit.circuit.library import TwoLocal from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.algorithms.ground_state_solvers import ( GroundStateEigensolver, NumPyMinimumEigensolverFactory, ) from qiskit_nature.transformers.second_quantization.electronic.active_space_transformer import ( ActiveSpaceTransformer, ) from qiskit_nature import settings settings.dict_aux_operators = True from entanglement_forging import reduce_bitstrings from entanglement_forging import ( EntanglementForgedConfig, EntanglementForgedDriver, EntanglementForgedGroundStateSolver, ) class TestEntanglementForgedGroundStateEigensolver(unittest.TestCase): """EntanglementForgedGroundStateEigensolver tests.""" def setUp(self): np.random.seed(42) self.backend = BasicAer.get_backend("statevector_simulator") self.config = EntanglementForgedConfig( backend=self.backend, maxiter=0, initial_params=[0.0], optimizer_name="COBYLA", ) # TS self.mock_ts_ansatz = self.create_mock_ansatz(4) self.hcore_ts = np.load( os.path.join(os.path.dirname(__file__), "test_data", "TS_one_body.npy") ) self.eri_ts = np.load( os.path.join(os.path.dirname(__file__), "test_data", "TS_two_body.npy") ) self.energy_shift_ts = -264.7518219120776 # O2 self.mock_o2_ansatz = self.create_mock_ansatz(8) self.hcore_o2 = np.load( os.path.join(os.path.dirname(__file__), "test_data", "O2_one_body.npy") ) self.eri_o2 = np.load( os.path.join(os.path.dirname(__file__), "test_data", "O2_two_body.npy") ) self.energy_shift_o2 = -99.83894101027317 # CH3 self.mock_ch3_ansatz = self.create_mock_ansatz(6) self.hcore_ch3 = np.load( os.path.join(os.path.dirname(__file__), "test_data", "CH3_one_body.npy") ) self.eri_ch3 = np.load( os.path.join(os.path.dirname(__file__), "test_data", "CH3_two_body.npy") ) self.energy_shift_ch3 = -31.90914780401554 def create_mock_ansatz(self, num_qubits): n_theta = 1 theta = Parameter("θ") mock_gate = QuantumCircuit(1, name="mock gate") mock_gate.rz(theta, 0) theta_vec = [Parameter("θ%d" % i) for i in range(1)] ansatz = QuantumCircuit(num_qubits) ansatz.append(mock_gate.to_gate({theta: theta_vec[0]}), [0]) return ansatz def test_forged_vqe_H2(self): """Test of applying Entanglement Forged VQE to to compute the energy of a H2 molecule.""" # setup problem 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) problem = ElectronicStructureProblem(driver) problem.second_q_ops() # solution bitstrings = [[1, 0], [0, 1]] ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1) config = EntanglementForgedConfig( backend=self.backend, maxiter=0, initial_params=[0, 0.5 * np.pi] ) converter = QubitConverter(JordanWignerMapper()) forged_ground_state_solver = EntanglementForgedGroundStateSolver( converter, ansatz, bitstrings, config ) forged_result = forged_ground_state_solver.solve(problem) self.assertAlmostEqual(forged_result.ground_state_energy, -1.1219365445030705) def test_forged_vqe_H2O(self): # pylint: disable=too-many-locals """Test of applying Entanglement Forged VQE to to compute the energy of a H20 molecule.""" # setup problem radius_1 = 0.958 # position for the first H atom radius_2 = 0.958 # position for the second H atom thetas_in_deg = 104.478 # bond angles. h1_x = radius_1 h2_x = radius_2 * np.cos(np.pi / 180 * thetas_in_deg) h2_y = radius_2 * np.sin(np.pi / 180 * thetas_in_deg) molecule = Molecule( geometry=[ ("O", [0.0, 0.0, 0.0]), ("H", [h1_x, 0.0, 0.0]), ("H", [h2_x, h2_y, 0.0]), ], charge=0, multiplicity=1, ) driver = PySCFDriver.from_molecule(molecule, basis="sto6g") problem = ElectronicStructureProblem(driver) problem.second_q_ops() # solution orbitals_to_reduce = [0, 3] bitstrings = [ [1, 1, 1, 1, 1, 0, 0], [1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 1, 1, 0], ] reduced_bitstrings = reduce_bitstrings(bitstrings, orbitals_to_reduce) theta = Parameter("θ") theta_1, theta_2, theta_3, theta_4 = ( Parameter("θ1"), Parameter("θ2"), Parameter("θ3"), Parameter("θ4"), ) hop_gate = QuantumCircuit(2, name="Hop gate") hop_gate.h(0) hop_gate.cx(1, 0) hop_gate.cx(0, 1) hop_gate.ry(-theta, 0) hop_gate.ry(-theta, 1) hop_gate.cx(0, 1) hop_gate.h(0) ansatz = QuantumCircuit(5) ansatz.append(hop_gate.to_gate({theta: theta_1}), [0, 1]) ansatz.append(hop_gate.to_gate({theta: theta_2}), [3, 4]) ansatz.append(hop_gate.to_gate({theta: 0}), [1, 4]) ansatz.append(hop_gate.to_gate({theta: theta_3}), [0, 2]) ansatz.append(hop_gate.to_gate({theta: theta_4}), [3, 4]) config = EntanglementForgedConfig( backend=self.backend, maxiter=0, spsa_c0=20 * np.pi, initial_params=[0, 0, 0, 0], ) converter = QubitConverter(JordanWignerMapper()) solver = EntanglementForgedGroundStateSolver( converter, ansatz, reduced_bitstrings, config, orbitals_to_reduce=orbitals_to_reduce, ) forged_result = solver.solve(problem) self.assertAlmostEqual(forged_result.ground_state_energy, -75.68366174497027) def test_ef_driver(self): """Test for entanglement forging driver.""" hcore = np.array([[-1.12421758, -0.9652574], [-0.9652574, -1.12421758]]) mo_coeff = np.array([[0.54830202, 1.21832731], [0.54830202, -1.21832731]]) eri = np.array( [ [ [[0.77460594, 0.44744572], [0.44744572, 0.57187698]], [[0.44744572, 0.3009177], [0.3009177, 0.44744572]], ], [ [[0.44744572, 0.3009177], [0.3009177, 0.44744572]], [[0.57187698, 0.44744572], [0.44744572, 0.77460594]], ], ] ) driver = EntanglementForgedDriver( hcore=hcore, mo_coeff=mo_coeff, eri=eri, num_alpha=1, num_beta=1, nuclear_repulsion_energy=0.7199689944489797, ) problem = ElectronicStructureProblem(driver) problem.second_q_ops() bitstrings = [[1, 0], [0, 1]] ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1) config = EntanglementForgedConfig( backend=self.backend, maxiter=0, initial_params=[0, 0.5 * np.pi] ) converter = QubitConverter(JordanWignerMapper()) forged_ground_state_solver = EntanglementForgedGroundStateSolver( converter, ansatz, bitstrings, config ) forged_result = forged_ground_state_solver.solve(problem) self.assertAlmostEqual(forged_result.ground_state_energy, -1.1219365445030705) def test_ground_state_eigensolver_with_ef_driver(self): """Tests standard qiskit nature solver.""" hcore = np.array([[-1.12421758, -0.9652574], [-0.9652574, -1.12421758]]) mo_coeff = np.array([[0.54830202, 1.21832731], [0.54830202, -1.21832731]]) eri = np.array( [ [ [[0.77460594, 0.44744572], [0.44744572, 0.57187698]], [[0.44744572, 0.3009177], [0.3009177, 0.44744572]], ], [ [[0.44744572, 0.3009177], [0.3009177, 0.44744572]], [[0.57187698, 0.44744572], [0.44744572, 0.77460594]], ], ] ) repulsion_energy = 0.7199689944489797 driver = EntanglementForgedDriver( hcore=hcore, mo_coeff=mo_coeff, eri=eri, num_alpha=1, num_beta=1, nuclear_repulsion_energy=repulsion_energy, ) problem = ElectronicStructureProblem(driver) problem.second_q_ops() converter = QubitConverter(JordanWignerMapper()) solver = GroundStateEigensolver( converter, NumPyMinimumEigensolverFactory(use_default_filter_criterion=False), ) result = solver.solve(problem) self.assertAlmostEqual( -1.137306026563, np.real(result.eigenenergies[0]) + repulsion_energy ) def test_O2_1(self): driver = EntanglementForgedDriver( hcore=self.hcore_o2, mo_coeff=np.eye(8, 8), eri=self.eri_o2, num_alpha=6, num_beta=6, nuclear_repulsion_energy=self.energy_shift_o2, ) problem = ElectronicStructureProblem(driver) problem.second_q_ops() converter = QubitConverter(JordanWignerMapper()) bitstrings_u = [ [1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 0, 1, 0], [1, 1, 1, 1, 0, 1, 1, 0], [1, 1, 0, 1, 1, 1, 1, 0], ] bitstrings_v = [ [1, 1, 1, 1, 1, 0, 1, 0], [1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 0, 1, 1, 1, 1, 0], [1, 1, 1, 1, 0, 1, 1, 0], ] calc = EntanglementForgedGroundStateSolver( converter, self.mock_o2_ansatz, bitstrings_u=bitstrings_u, bitstrings_v=bitstrings_v, config=self.config, orbitals_to_reduce=[], ) res = calc.solve(problem) self.assertAlmostEqual(-147.63645235088566, res.ground_state_energy) def test_CH3(self): driver = EntanglementForgedDriver( hcore=self.hcore_ch3, mo_coeff=np.eye(6, 6), eri=self.eri_ch3, num_alpha=3, num_beta=2, nuclear_repulsion_energy=self.energy_shift_ch3, ) problem = ElectronicStructureProblem(driver) problem.second_q_ops() converter = QubitConverter(JordanWignerMapper()) bitstrings_u = [ [1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 0], [1, 0, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0], ] bitstrings_v = [ [1, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 0, 0], ] calc = EntanglementForgedGroundStateSolver( converter, self.mock_ch3_ansatz, bitstrings_u=bitstrings_u, bitstrings_v=bitstrings_v, config=self.config, orbitals_to_reduce=[], ) res = calc.solve(problem) self.assertAlmostEqual(-39.09031477502881, res.ground_state_energy)
https://github.com/JavaFXpert/quantum-circuit-pygame
JavaFXpert
# # Copyright 2019 the original author or authors. # # 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 numpy as np from qiskit import QuantumCircuit, QuantumRegister from model import circuit_node_types as node_types class CircuitGridModel(): """Grid-based model that is built when user interacts with circuit""" def __init__(self, max_wires, max_columns): self.max_wires = max_wires self.max_columns = max_columns self.nodes = np.empty((max_wires, max_columns), dtype = CircuitGridNode) def __str__(self): retval = '' for wire_num in range(self.max_wires): retval += '\n' for column_num in range(self.max_columns): # retval += str(self.nodes[wire_num][column_num]) + ', ' retval += str(self.get_node_gate_part(wire_num, column_num)) + ', ' return 'CircuitGridModel: ' + retval # def set_node(self, wire_num, column_num, node_type, radians=0, ctrl_a=-1, ctrl_b=-1, swap=-1): def set_node(self, wire_num, column_num, circuit_grid_node): self.nodes[wire_num][column_num] = \ CircuitGridNode(circuit_grid_node.node_type, circuit_grid_node.radians, circuit_grid_node.ctrl_a, circuit_grid_node.ctrl_b, circuit_grid_node.swap) # TODO: Decide whether to protect as shown below # if not self.nodes[wire_num][column_num]: # self.nodes[wire_num][column_num] = CircuitGridNode(node_type, radians) # else: # print('Node ', wire_num, column_num, ' not empty') def get_node(self, wire_num, column_num): return self.nodes[wire_num][column_num] def get_node_gate_part(self, wire_num, column_num): requested_node = self.nodes[wire_num][column_num] if requested_node and requested_node.node_type != node_types.EMPTY: # Node is occupied so return its gate return requested_node.node_type else: # Check for control nodes from gates in other nodes in this column nodes_in_column = self.nodes[:, column_num] for idx in range(self.max_wires): if idx != wire_num: other_node = nodes_in_column[idx] if other_node: if other_node.ctrl_a == wire_num or other_node.ctrl_b == wire_num: return node_types.CTRL elif other_node.swap == wire_num: return node_types.SWAP return node_types.EMPTY def get_gate_wire_for_control_node(self, control_wire_num, column_num): """Get wire for gate that belongs to a control node on the given wire""" gate_wire_num = -1 nodes_in_column = self.nodes[:, column_num] for wire_idx in range(self.max_wires): if wire_idx != control_wire_num: other_node = nodes_in_column[wire_idx] if other_node: if other_node.ctrl_a == control_wire_num or \ other_node.ctrl_b == control_wire_num: gate_wire_num = wire_idx print("Found gate: ", self.get_node_gate_part(gate_wire_num, column_num), " on wire: " , gate_wire_num) return gate_wire_num # def avail_gate_parts_for_node(self, wire_num, column_num): # retval = np.empty(0, dtype = np.int8) # node_gate_part = self.get_node_gate_part(wire_num, column_num) # if node_gate_part == node_types.EMPTY: # # No gate part in this node def compute_circuit(self): qr = QuantumRegister(self.max_wires, 'q') qc = QuantumCircuit(qr) for column_num in range(self.max_columns): for wire_num in range(self.max_wires): node = self.nodes[wire_num][column_num] if node: if node.node_type == node_types.IDEN: # Identity gate qc.iden(qr[wire_num]) elif node.node_type == node_types.X: if node.radians == 0: if node.ctrl_a != -1: if node.ctrl_b != -1: # Toffoli gate qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num]) else: # Controlled X gate qc.cx(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-X gate qc.x(qr[wire_num]) else: # Rotation around X axis qc.rx(node.radians, qr[wire_num]) elif node.node_type == node_types.Y: if node.radians == 0: if node.ctrl_a != -1: # Controlled Y gate qc.cy(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Y gate qc.y(qr[wire_num]) else: # Rotation around Y axis qc.ry(node.radians, qr[wire_num]) elif node.node_type == node_types.Z: if node.radians == 0: if node.ctrl_a != -1: # Controlled Z gate qc.cz(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Z gate qc.z(qr[wire_num]) else: if node.ctrl_a != -1: # Controlled rotation around the Z axis qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num]) else: # Rotation around Z axis qc.rz(node.radians, qr[wire_num]) elif node.node_type == node_types.S: # S gate qc.s(qr[wire_num]) elif node.node_type == node_types.SDG: # S dagger gate qc.sdg(qr[wire_num]) elif node.node_type == node_types.T: # T gate qc.t(qr[wire_num]) elif node.node_type == node_types.TDG: # T dagger gate qc.tdg(qr[wire_num]) elif node.node_type == node_types.H: if node.ctrl_a != -1: # Controlled Hadamard qc.ch(qr[node.ctrl_a], qr[wire_num]) else: # Hadamard gate qc.h(qr[wire_num]) elif node.node_type == node_types.SWAP: if node.ctrl_a != -1: # Controlled Swap qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap]) else: # Swap gate qc.swap(qr[wire_num], qr[node.swap]) return qc class CircuitGridNode(): """Represents a node in the circuit grid""" def __init__(self, node_type, radians=0.0, ctrl_a=-1, ctrl_b=-1, swap=-1): self.node_type = node_type self.radians = radians self.ctrl_a = ctrl_a self.ctrl_b = ctrl_b self.swap = swap def __str__(self): string = 'type: ' + str(self.node_type) string += ', radians: ' + str(self.radians) if self.radians != 0 else '' string += ', ctrl_a: ' + str(self.ctrl_a) if self.ctrl_a != -1 else '' string += ', ctrl_b: ' + str(self.ctrl_b) if self.ctrl_b != -1 else '' return string
https://github.com/JavaFXpert/quantum-circuit-pygame
JavaFXpert
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # 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 pygame from qiskit import BasicAer, QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram from utils import load_image DEFAULT_NUM_SHOTS = 100 class MeasurementsHistogram(pygame.sprite.Sprite): """Displays a histogram with measurements""" def __init__(self, circuit, num_shots=DEFAULT_NUM_SHOTS): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.set_circuit(circuit, num_shots) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit, num_shots=DEFAULT_NUM_SHOTS): backend_sim = BasicAer.get_backend('qasm_simulator') qr = QuantumRegister(circuit.width(), 'q') cr = ClassicalRegister(circuit.width(), 'c') meas_circ = QuantumCircuit(qr, cr) meas_circ.barrier(qr) meas_circ.measure(qr, cr) complete_circuit = circuit + meas_circ job_sim = execute(complete_circuit, backend_sim, shots=num_shots) result_sim = job_sim.result() counts = result_sim.get_counts(complete_circuit) print(counts) histogram = plot_histogram(counts) histogram.savefig("utils/data/bell_histogram.png") self.image, self.rect = load_image('bell_histogram.png', -1) self.image.convert()
https://github.com/JavaFXpert/quantum-circuit-pygame
JavaFXpert
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # 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 pygame from qiskit import BasicAer, execute from qiskit.tools.visualization import plot_state_qsphere from utils import load_image class QSphere(pygame.sprite.Sprite): """Displays a qsphere""" def __init__(self, circuit): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.set_circuit(circuit) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circuit, decimals=3) qsphere = plot_state_qsphere(quantum_state) qsphere.savefig("utils/data/bell_qsphere.png") self.image, self.rect = load_image('bell_qsphere.png', -1) self.rect.inflate_ip(-100, -100) self.image.convert()
https://github.com/JavaFXpert/quantum-circuit-pygame
JavaFXpert
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # 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 pygame from qiskit import BasicAer, execute, ClassicalRegister from utils.colors import * from utils.fonts import ARIAL_30 from utils.states import comp_basis_states from copy import deepcopy #from utils.paddle import * class StatevectorGrid(pygame.sprite.Sprite): """Displays a statevector grid""" def __init__(self, circuit, qubit_num, num_shots): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.basis_states = comp_basis_states(circuit.width()) self.set_circuit(circuit, qubit_num, num_shots) # def update(self): # # Nothing yet # a = 1ot def set_circuit(self, circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circuit, decimals=3) # This square represent the probability of state after measurement self.image = pygame.Surface([(circuit.width()+1) * 50, 500]) self.image.convert() self.image.fill(BLACK) self.rect = self.image.get_rect() block_size = int(round(500 / 2 ** qubit_num)) x_offset = 50 y_offset = 15 self.paddle = pygame.Surface([10, block_size]) self.paddle.convert() for y in range(len(quantum_state)): text_surface = ARIAL_30.render("|"+self.basis_states[y]+">", False, (255, 255, 255)) self.image.blit(text_surface,(120, y * block_size + y_offset)) if abs(quantum_state[y]) > 0: #pygame.draw.rect(self.image, WHITE, rect, 0) self.paddle.fill(WHITE) self.paddle.set_alpha(int(round(abs(quantum_state[y])*255))) self.image.blit(self.paddle,(80,y * block_size)) def set_circuit_measure(self, circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('qasm_simulator') cr = ClassicalRegister(qubit_num) circuit2 = deepcopy(circuit) circuit2.add_register(cr) circuit2.measure(circuit2.qregs[0],circuit2.cregs[0]) job_sim = execute(circuit2, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) print(counts) #quantum_state = result_sim.get_statevector(circuit, decimals=3) # This square represent the probability of state after measurement self.image = pygame.Surface([(circuit.width()+1) * 50, 500]) self.image.convert() self.image.fill(BLACK) self.rect = self.image.get_rect() block_size = int(round(500 / 2 ** qubit_num)) x_offset = 50 y_offset = 15 self.paddle = pygame.Surface([10, block_size]) self.paddle.convert() self.paddle.fill(WHITE) #for y in range(len(quantum_state)): # text_surface = ARIAL_30.render(self.basis_states[y], False, (0, 0, 0)) # self.image.blit(text_surface,(120, y * block_size + y_offset)) # if abs(quantum_state[y]) > 0: #pygame.draw.rect(self.image, WHITE, rect, 0) #self.paddle.fill(WHITE) # self.paddle.set_alpha(int(round(abs(quantum_state[y])*255))) print(counts.keys()) print(int(list(counts.keys())[0],2)) self.image.blit(self.paddle,(80,int(list(counts.keys())[0],2) * block_size)) #pygame.time.wait(100) return int(list(counts.keys())[0],2)
https://github.com/JavaFXpert/quantum-circuit-pygame
JavaFXpert
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # 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 pygame from qiskit import BasicAer, execute from utils.colors import * from utils.fonts import * from utils.states import comp_basis_states class UnitaryGrid(pygame.sprite.Sprite): """Displays a unitary matrix grid""" def __init__(self, circuit): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.basis_states = comp_basis_states(circuit.width()) self.set_circuit(circuit) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit): backend_unit_sim = BasicAer.get_backend('unitary_simulator') job_sim = execute(circuit, backend_unit_sim) result_sim = job_sim.result() unitary = result_sim.get_unitary(circuit, decimals=3) # print('unitary: ', unitary) self.image = pygame.Surface([100 + len(unitary) * 50, 100 + len(unitary) * 50]) self.image.convert() self.image.fill(WHITE) self.rect = self.image.get_rect() block_size = 30 x_offset = 50 y_offset = 50 for y in range(len(unitary)): text_surface = ARIAL_16.render(self.basis_states[y], False, (0, 0, 0)) self.image.blit(text_surface,(x_offset, (y + 1) * block_size + y_offset)) for x in range(len(unitary)): text_surface = ARIAL_16.render(self.basis_states[x], False, (0, 0, 0)) self.image.blit(text_surface, ((x + 1) * block_size + x_offset, y_offset)) rect = pygame.Rect((x + 1) * block_size + x_offset, (y + 1) * block_size + y_offset, abs(unitary[y][x]) * block_size, abs(unitary[y][x]) * block_size) if abs(unitary[y][x]) > 0: pygame.draw.rect(self.image, BLACK, rect, 1)
https://github.com/quantumofme/pavia-qiskit-tutorials
quantumofme
# Welcome to qiskit import qiskit as qk myvers = qk.__version__ print("You are using qiskit version", myvers) print("More details on qiskit components:",qk.__qiskit_version__) my_token = '' # Set up your credentials for the IBM Quantum Experience in one-time mode (easiest) ibmq_provider = qk.IBMQ.enable_account(my_token) # Check the available local backends qk.Aer.backends() # Check the available cloud-based backends ibmq_provider.backends() qr = qk.QuantumRegister(2,name='qreg') cr = qk.ClassicalRegister(2,name='creg') qc = qk.QuantumCircuit(qr,cr,name='test_circ') # A QuantumCircuit is composed of quantum and classical registers qc.x(qr[0]) for indx in range(2): qc.h(qr[indx]) qc.cx(qr[0],qr[1]) # The first entry is the control qubit, the second entry is the target qubit for the CNOT qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) qc.draw() qc.draw(output='mpl') backend1 = qk.Aer.get_backend('qasm_simulator') job1 = qk.execute(qc, backend1, shots=1024) # The shots are the number of times the circuit will be run. # More shots will mean better reconstruction of the measurement # statistics, but also longer execution times result1 = job1.result() counts1 = result1.get_counts(qc) print(counts1) from qiskit.tools.visualization import plot_histogram plot_histogram(counts1) backend2 = ibmq_provider.get_backend('ibmqx2') job2 = qk.execute(qc, backend=backend2, shots=1024) from qiskit.tools.monitor import job_monitor job_monitor(job2, interval=5) result2 = job2.result() counts2 = result2.get_counts(qc) print(counts2) plot_histogram(counts2) jobID = job2.job_id() print(jobID) job_get = backend2.retrieve_job(jobID) counts_get = job_get.result().get_counts() print(counts_get) plot_histogram([counts1,counts_get]) from qiskit.tools.visualization import plot_gate_map print('List of pairwise connection between qubits available for CNOT operations:\n', backend2.configuration().coupling_map) plot_gate_map(backend2) custom_layout = [3,4] # abstract qr[0] will be mapped in q[3] on the device # abstract qr[1] will be mapped in q[4] on the device compiled_qc = qk.transpile(qc,backend = backend2,initial_layout = custom_layout,optimization_level=0) compiled_qc.draw() from qiskit.tools.visualization import plot_circuit_layout plot_circuit_layout(compiled_qc,backend2) compiled_qobj = qk.assemble(compiled_qc,shots=1024) job3 = backend2.run(compiled_qobj) job4 = qk.execute(qc,backend=backend2,shots=1024,initial_layout=custom_layout,optimization_level=0) custom_layout_bad = [1,3] # There is no 1 -> 3 connection on the device compiled_qc_bad = qk.transpile(qc, backend = backend2, initial_layout = custom_layout_bad,optimization_level=0) compiled_qc_bad.draw(output='mpl') plot_circuit_layout(compiled_qc_bad,backend2) qr = qk.QuantumRegister(5,name='qreg') cr = qk.ClassicalRegister(5,name='creg') qc = qk.QuantumCircuit(qr,cr,name='exercise') qc.h(qr[0]) for i in range(1,5): qc.cx(qr[0],qr[i]) qc.draw(output='mpl')
https://github.com/quantumofme/pavia-qiskit-tutorials
quantumofme
import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) import qiskit as qk qr0 = qk.QuantumRegister(1,name='qb') # qb for "qubit", but the name is optional cr0 = qk.ClassicalRegister(1,name='b') # b for "bit", but the name is optional qc0 = qk.QuantumCircuit(qr0,cr0) qc0.draw(output='mpl') # this is to visualize the circuit. Remove the output option for a different style. from qiskit.tools.visualization import plot_bloch_vector import math theta = math.pi/2 # You can try to change the parameters theta and phi phi = math.pi/4 # to see how the vector moves on the sphere plot_bloch_vector([math.cos(phi)*math.sin(theta),math.sin(phi)*math.sin(theta),math.cos(theta)]) # Entries of the # input vector are # coordinates [x,y,z] qc0.measure(qr0[0],cr0[0]) qc0.draw(output='mpl') backend = qk.Aer.get_backend('qasm_simulator') job = qk.execute(qc0, backend, shots=1024) result = job.result() counts = result.get_counts() print(counts) qc1 = qk.QuantumCircuit(qr0,cr0) qc1.x(qr0[0]) # A X gate targeting the first (and only) qubit in register qr0 qc1.measure(qr0[0],cr0[0]) qc1.draw(output='mpl') backend = qk.Aer.get_backend('qasm_simulator') job1 = qk.execute(qc1, backend, shots=1024) result1 = job1.result() counts1 = result1.get_counts() print(counts1) from qiskit.tools.visualization import plot_bloch_multivector vec_backend = qk.Aer.get_backend('statevector_simulator') result_vec0 = qk.execute(qc0, vec_backend).result() result_vec1 = qk.execute(qc1, vec_backend).result() psi0 = result_vec0.get_statevector() psi1 = result_vec1.get_statevector() plot_bloch_multivector(psi0) plot_bloch_multivector(psi1) qc2 = qk.QuantumCircuit(qr0,cr0) qc2.h(qr0[0]) qc2.measure(qr0[0],cr0[0]) qc2.draw(output='mpl') job2 = qk.execute(qc2, backend, shots=1024) result2 = job2.result() counts2 = result2.get_counts() print(counts2) qc2_bis = qk.QuantumCircuit(qr0,cr0) qc2_bis.h(qr0[0]) result_vec2 = qk.execute(qc2_bis, vec_backend).result() psi2 = result_vec2.get_statevector() plot_bloch_multivector(psi2) qc3 = qk.QuantumCircuit(qr0,cr0) qc3.h(qr0[0]) qc3.s(qr0[0]) # Use sdg instead of s for the adjoint qc3.measure(qr0[0],cr0[0]) qc3.draw(output='mpl') job3 = qk.execute(qc3, backend, shots=1024) result3 = job3.result() counts3 = result3.get_counts() print(counts3) qc3_bis = qk.QuantumCircuit(qr0,cr0) qc3_bis.h(qr0[0]) qc3_bis.s(qr0[0]) result_vec3 = qk.execute(qc3_bis, vec_backend).result() psi3 = result_vec3.get_statevector() plot_bloch_multivector(psi3) qc4 = qk.QuantumCircuit(qr0,cr0) qc4.h(qr0[0]) qc4.t(qr0[0]) # Use tdg instead of t for the adjoint qc4.measure(qr0[0],cr0[0]) qc4.draw(output='mpl') job4 = qk.execute(qc4, backend, shots=1024) result4 = job4.result() counts4 = result4.get_counts() print(counts4) qc4_bis = qk.QuantumCircuit(qr0,cr0) qc4_bis.h(qr0[0]) qc4_bis.t(qr0[0]) result_vec4 = qk.execute(qc4_bis, vec_backend).result() psi4 = result_vec4.get_statevector() plot_bloch_multivector(psi4) lmbd = 1.2 # Change this value to rotate the output vector on the equator of the Bloch sphere qc5 = qk.QuantumCircuit(qr0,cr0) qc5.h(qr0[0]) qc5.u1(lmbd, qr0[0]) qc5.draw(output='mpl') result_vec5 = qk.execute(qc5, vec_backend).result() psi5 = result_vec5.get_statevector() plot_bloch_multivector(psi5) qc6 = qk.QuantumCircuit(qr0,cr0) qc6.u2(0,math.pi, qr0[0]) result_vec6 = qk.execute(qc6, vec_backend).result() psi6 = result_vec6.get_statevector() plot_bloch_multivector(psi6) theta = 0.5 phi = math.pi/4 lmb = math.pi/8 qc7 = qk.QuantumCircuit(qr0,cr0) qc7.u3(theta,phi, lmb, qr0[0]) result_vec7 = qk.execute(qc7, vec_backend).result() psi7 = result_vec7.get_statevector() plot_bloch_multivector(psi7) qr = qk.QuantumRegister(2,name='qr') # we need a 2-qubit register now cr = qk.ClassicalRegister(2,name='cr') cnot_example = qk.QuantumCircuit(qr,cr) cnot_example.x(qr[0]) cnot_example.cx(qr[0],qr[1]) # First entry is control, the second is the target cnot_example.measure(qr[0],cr[0]) cnot_example.measure(qr[1],cr[1]) cnot_example.draw(output='mpl') job_cnot = qk.execute(cnot_example, backend, shots=1024) result_cnot = job_cnot.result() counts_cnot = result_cnot.get_counts() print(counts_cnot) cnot_reversed = qk.QuantumCircuit(qr,cr) cnot_reversed.x(qr[0]) # This part uses cx(qr[1],qr[0]) but is equivalent to cx(qr[0],qr[1]) cnot_reversed.h(qr[0]) cnot_reversed.h(qr[1]) cnot_reversed.cx(qr[1],qr[0]) cnot_reversed.h(qr[0]) cnot_reversed.h(qr[1]) # cnot_reversed.measure(qr[0],cr[0]) cnot_reversed.measure(qr[1],cr[1]) cnot_reversed.draw(output='mpl') job_cnot_rev = qk.execute(cnot_reversed, backend, shots=1024) result_cnot_rev = job_cnot_rev.result() counts_cnot_rev = result_cnot_rev.get_counts() print(counts_cnot_rev) bell_phi_p = qk.QuantumCircuit(qr,cr) bell_phi_p.h(qr[0]) bell_phi_p.cx(qr[0],qr[1]) bell_phi_p.measure(qr[0],cr[0]) bell_phi_p.measure(qr[1],cr[1]) bell_phi_p.draw(output='mpl') job_bell_phi_p = qk.execute(bell_phi_p, backend, shots=1024) result_bell_phi_p = job_bell_phi_p.result() counts_bell_phi_p = result_bell_phi_p.get_counts() print(counts_bell_phi_p) cz_example = qk.QuantumCircuit(qr) cz_example.cz(qr[0],qr[1]) cz_example.draw(output='mpl') cz_from_cnot = qk.QuantumCircuit(qr) cz_from_cnot.h(qr[1]) cz_from_cnot.cx(qr[0],qr[1]) cz_from_cnot.h(qr[1]) cz_from_cnot.draw(output='mpl') delta = 0.5 cphase_test = qk.QuantumCircuit(qr) cphase_test.cu1(delta,qr[0],qr[1]) cphase_test.draw(output='mpl') delta = 0.5 cphase_from_cnot = qk.QuantumCircuit(qr) cphase_from_cnot.u1(delta/2,qr[1]) cphase_from_cnot.cx(qr[0],qr[1]) cphase_from_cnot.u1(-delta/2,qr[1]) cphase_from_cnot.cx(qr[0],qr[1]) cphase_from_cnot.u1(delta/2,qr[0]) cphase_from_cnot.draw(output='mpl') swap_test = qk.QuantumCircuit(qr) swap_test.swap(qr[0],qr[1]) swap_test.draw(output='mpl') swap_from_cnot = qk.QuantumCircuit(qr) swap_from_cnot.cx(qr[0],qr[1]) swap_from_cnot.cx(qr[1],qr[0]) swap_from_cnot.cx(qr[0],qr[1]) swap_from_cnot.draw(output='mpl') qr_many = qk.QuantumRegister(5) control_example = qk.QuantumCircuit(qr_many) control_example.cy(qr_many[0],qr_many[1]) control_example.ch(qr_many[1],qr_many[2]) control_example.crz(0.2,qr_many[2],qr_many[3]) control_example.cu3(0.5, 0, 0, qr_many[3],qr_many[4]) control_example.draw(output='mpl') qrthree = qk.QuantumRegister(3) toffoli_example = qk.QuantumCircuit(qrthree) toffoli_example.ccx(qrthree[0],qrthree[1],qrthree[2]) toffoli_example.draw(output='mpl') toffoli_from_cnot = qk.QuantumCircuit(qrthree) toffoli_from_cnot.h(qrthree[2]) toffoli_from_cnot.cx(qrthree[1],qrthree[2]) toffoli_from_cnot.tdg(qrthree[2]) toffoli_from_cnot.cx(qrthree[0],qrthree[2]) toffoli_from_cnot.t(qrthree[2]) toffoli_from_cnot.cx(qrthree[1],qrthree[2]) toffoli_from_cnot.tdg(qrthree[2]) toffoli_from_cnot.cx(qrthree[0],qrthree[2]) toffoli_from_cnot.tdg(qrthree[1]) toffoli_from_cnot.t(qrthree[2]) toffoli_from_cnot.h(qrthree[2]) toffoli_from_cnot.cx(qrthree[0],qrthree[1]) toffoli_from_cnot.tdg(qrthree[1]) toffoli_from_cnot.cx(qrthree[0],qrthree[1]) toffoli_from_cnot.s(qrthree[1]) toffoli_from_cnot.t(qrthree[0]) toffoli_from_cnot.draw(output='mpl') crsingle = qk.ClassicalRegister(1) deutsch = qk.QuantumCircuit(qr,crsingle) deutsch.x(qr[1]) deutsch.h(qr[1]) deutsch.draw(output='mpl') deutsch.h(qr[0]) deutsch.draw(output='mpl') deutsch.cx(qr[0],qr[1]) deutsch.h(qr[0]) deutsch.measure(qr[0],crsingle[0]) deutsch.draw(output='mpl') N = 4 qrQFT = qk.QuantumRegister(N,'qftr') QFT = qk.QuantumCircuit(qrQFT) for i in range(N): QFT.h(qrQFT[i]) for k in range(i+1,N): l = k-i+1 QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i]) QFT.draw(output='mpl')
https://github.com/quantumofme/pavia-qiskit-tutorials
quantumofme
import qiskit as qk import numpy as np from scipy.linalg import expm import matplotlib.pyplot as plt import math # Single qubit operators sx = np.array([[0.0, 1.0],[1.0, 0.0]]) sy = np.array([[0.0, -1.0*1j],[1.0*1j, 0.0]]) sz = np.array([[1.0, 0.0],[0.0, -1.0]]) idt = np.array([[1.0, 0.0],[0.0, 1.0]]) import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) psi0 = np.array([1.0, 0.0]) thetas = np.linspace(0,4*math.pi,200) avg_sx_tot = np.zeros(len(thetas)) for i in range(len(thetas)): psi_theta = expm(-1j*0.5*thetas[i]*(sx+sz)/math.sqrt(2)).dot(psi0) avg_sx_tot[i] = np.real(psi_theta.conjugate().transpose().dot(sx.dot(psi_theta))) plt.plot(thetas,avg_sx_tot) plt.xlabel(r'$\theta$') plt.ylabel(r'$\langle\sigma_x\rangle_\theta$') plt.show() avg_sx_zx = np.zeros(len(thetas)) avg_sx_xz = np.zeros(len(thetas)) for i in range(len(thetas)): psi_theta_zx = expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(psi0)) psi_theta_xz = expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(psi0)) avg_sx_zx[i] = np.real(psi_theta_zx.conjugate().transpose().dot(sx.dot(psi_theta_zx))) avg_sx_xz[i] = np.real(psi_theta_xz.conjugate().transpose().dot(sx.dot(psi_theta_xz))) plt.plot(thetas,avg_sx_tot) plt.plot(thetas,avg_sx_zx) plt.plot(thetas,avg_sx_xz) plt.xlabel(r'$\theta$') plt.ylabel(r'$\langle\sigma_x\rangle_\theta$') plt.legend(['Around x = z', 'x first', 'z first'],loc=1) plt.show() # Try this with e.g. ntrot = 1, 5, 10, 50. # You can also try to do sx and sz slices in the reverse order: both choices will become good approximations # for large n ntrot = 10 avg_sx_n = np.zeros(len(thetas)) for i in range(len(thetas)): rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2)))) for j in range(ntrot-1): rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2)))).dot(rot) psi_theta_n = rot.dot(psi0) avg_sx_n[i] = np.real(psi_theta_n.conjugate().transpose().dot(sx.dot(psi_theta_n))) plt.plot(thetas,avg_sx_tot) plt.plot(thetas,avg_sx_n,'--') plt.xlabel(r'$\theta$') plt.ylabel(r'$\langle\sigma_x\rangle_\theta$') plt.legend(['Exact', 'ntrot = ' + str(ntrot)],loc=1) plt.show() delta = 0.1 qr = qk.QuantumRegister(2,name='qr') zz_example = qk.QuantumCircuit(qr) zz_example.cx(qr[0],qr[1]) zz_example.u1(2*delta,qr[1]) zz_example.cx(qr[0],qr[1]) zz_example.draw(output='mpl') J = 1 c_times = np.linspace(0,0.5*math.pi/abs(J),1000) q_times = np.linspace(0,0.5*math.pi/abs(J),10) ### Classical simulation of the Heisenberg dimer model psi0 = np.kron( np.array([0,1]), np.array([1,0]) ) H = J * ( np.kron(sx,sx) + np.kron(sy,sy) + np.kron(sz,sz) ) sz1_t = np.zeros(len(c_times)) sz2_t = np.zeros(len(c_times)) sz1 = np.kron(sz,idt) sz2 = np.kron(idt,sz) for i in range(len(c_times)): t = c_times[i] psi_t = expm(-1j*H*t).dot(psi0) sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t))) sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t))) ### Digital quantum simulation of the Heisenberg dimer model using qiskit nshots = 1024 sz1q_t = np.zeros(len(q_times)) sz2q_t = np.zeros(len(q_times)) for k in range(len(q_times)): delta = J*q_times[k] qr = qk.QuantumRegister(2,name='qr') cr = qk.ClassicalRegister(2,name='cr') Heis2 = qk.QuantumCircuit(qr,cr) # Initial state preparation Heis2.x(qr[0]) # ZZ Heis2.cx(qr[0],qr[1]) Heis2.u1(-2*delta,qr[1]) Heis2.cx(qr[0],qr[1]) # YY Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0]) Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1]) Heis2.cx(qr[0],qr[1]) Heis2.u1(-2*delta,qr[1]) Heis2.cx(qr[0],qr[1]) Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0]) Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1]) # XX Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0]) Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1]) Heis2.cx(qr[0],qr[1]) Heis2.u1(-2*delta,qr[1]) Heis2.cx(qr[0],qr[1]) Heis2.u3(math.pi/2, 0.0, 0.0, qr[0]) Heis2.u3(math.pi/2, 0.0, 0.0, qr[1]) # measure Heis2.measure(qr,cr) # Run the quantum algorithm backend = qk.Aer.get_backend('qasm_simulator') job = qk.execute(Heis2, backend, shots=nshots) result = job.result() counts = result.get_counts() # Post processing of outcomes to get sz expectation values sz1q = 0 sz2q = 0 for key,value in counts.items(): if key == '00': sz1q += value sz2q += value elif key == '01': sz1q -= value sz2q += value elif key == '10': sz1q += value sz2q -= value elif key == '11': sz1q -= value sz2q -= value sz1q_t[k] = sz1q/nshots sz2q_t[k] = sz2q/nshots plt.plot(abs(J)*c_times,0.5*sz1_t,'b--') plt.plot(abs(J)*c_times,0.5*sz2_t,'c') plt.plot(abs(J)*q_times,0.5*sz1q_t,'rd') plt.plot(abs(J)*q_times,0.5*sz2q_t,'ko') plt.legend(['sz1','sz2','sz1q','sz2q']) plt.xlabel(r'$\delta = |J|t$') plt.show() # WARNING: this cell can take a few minutes to run! ntrotter = 5 J12 = 1 J23 = 1 c_times = np.linspace(0,math.pi/abs(J12),1000) q_times = np.linspace(0,math.pi/abs(J12),20) ### Classical simulation of the Heisenberg trimer model psi0 = np.kron( np.kron( np.array([0,1]), np.array([1,0]) ) , np.array([1,0]) ) sxsx12 = np.kron(sx, np.kron(sx,idt)) sysy12 = np.kron(sy, np.kron(sy,idt)) szsz12 = np.kron(sz, np.kron(sz,idt)) sxsx23 = np.kron(idt, np.kron(sx,sx)) sysy23 = np.kron(idt, np.kron(sy,sy)) szsz23 = np.kron(idt, np.kron(sz,sz)) H12 = J12 * ( sxsx12 + sysy12 + szsz12 ) H23 = J23 * ( sxsx23 + sysy23 + szsz23 ) H = H12 + H23 sz1_t = np.zeros(len(c_times)) sz2_t = np.zeros(len(c_times)) sz3_t = np.zeros(len(c_times)) sz1 = np.kron(sz, np.kron(idt,idt)) sz2 = np.kron(idt, np.kron(sz,idt)) sz3 = np.kron(idt, np.kron(idt,sz)) for i in range(len(c_times)): t = c_times[i] psi_t = expm(-1j*H*t).dot(psi0) sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t))) sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t))) sz3_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t))) ### Classical simulation of the Heisenberg trimer model WITH SUZUKI TROTTER DIGITALIZATION sz1st_t = np.zeros(len(c_times)) sz2st_t = np.zeros(len(c_times)) sz3st_t = np.zeros(len(c_times)) for i in range(len(c_times)): t = c_times[i] Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter)) for j in range(ntrotter-1): Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter)).dot(Ust) psi_t = Ust.dot(psi0) sz1st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t))) sz2st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t))) sz3st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t))) ### Digital quantum simulation of the Heisenberg model using qiskit nshots = 1024 sz1q_t = np.zeros(len(q_times)) sz2q_t = np.zeros(len(q_times)) sz3q_t = np.zeros(len(q_times)) for k in range(len(q_times)): delta12n = J12*q_times[k]/ntrotter delta23n = J23*q_times[k]/ntrotter qr = qk.QuantumRegister(3,name='qr') cr = qk.ClassicalRegister(3,name='cr') Heis3 = qk.QuantumCircuit(qr,cr) # Initial state preparation Heis3.x(qr[0]) for n in range(ntrotter): # 1-2 bond mapped on qubits 0 and 1 in the quantum register # ZZ Heis3.cx(qr[0],qr[1]) Heis3.u1(-2*delta12n,qr[1]) Heis3.cx(qr[0],qr[1]) # YY Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0]) Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1]) Heis3.cx(qr[0],qr[1]) Heis3.u1(-2*delta12n,qr[1]) Heis3.cx(qr[0],qr[1]) Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0]) Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1]) # XX Heis3.u3(-math.pi/2, 0.0, 0.0, qr[0]) Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1]) Heis3.cx(qr[0],qr[1]) Heis3.u1(-2*delta12n,qr[1]) Heis3.cx(qr[0],qr[1]) Heis3.u3(math.pi/2, 0.0, 0.0, qr[0]) Heis3.u3(math.pi/2, 0.0, 0.0, qr[1]) # 2-3 bond mapped on qubits 1 and 2 in the quantum register # ZZ Heis3.cx(qr[1],qr[2]) Heis3.u1(-2*delta12n,qr[2]) Heis3.cx(qr[1],qr[2]) # YY Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1]) Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[2]) Heis3.cx(qr[1],qr[2]) Heis3.u1(-2*delta12n,qr[2]) Heis3.cx(qr[1],qr[2]) Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1]) Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[2]) # XX Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1]) Heis3.u3(-math.pi/2, 0.0, 0.0, qr[2]) Heis3.cx(qr[1],qr[2]) Heis3.u1(-2*delta12n,qr[2]) Heis3.cx(qr[1],qr[2]) Heis3.u3(math.pi/2, 0.0, 0.0, qr[1]) Heis3.u3(math.pi/2, 0.0, 0.0, qr[2]) # measure Heis3.measure(qr,cr) # Run the quantum algorithm backend = qk.Aer.get_backend('qasm_simulator') job = qk.execute(Heis3, backend, shots=nshots) result = job.result() counts = result.get_counts() # Post processing of outcomes to get sz expectation values sz1q = 0 sz2q = 0 sz3q = 0 for key,value in counts.items(): if key == '000': sz1q += value sz2q += value sz3q += value elif key == '001': sz1q -= value sz2q += value sz3q += value elif key == '010': sz1q += value sz2q -= value sz3q += value elif key == '011': sz1q -= value sz2q -= value sz3q += value elif key == '100': sz1q += value sz2q += value sz3q -= value elif key == '101': sz1q -= value sz2q += value sz3q -= value elif key == '110': sz1q += value sz2q -= value sz3q -= value elif key == '111': sz1q -= value sz2q -= value sz3q -= value sz1q_t[k] = sz1q/nshots sz2q_t[k] = sz2q/nshots sz3q_t[k] = sz3q/nshots fig = plt.figure() ax = plt.subplot(111) ax.plot(abs(J12)*c_times,0.5*sz1_t,'b', label='sz1 full') ax.plot(abs(J12)*c_times,0.5*sz2_t,'r', label='sz2 full') ax.plot(abs(J12)*c_times,0.5*sz3_t,'g', label='sz3 full') ax.plot(abs(J12)*c_times,0.5*sz1st_t,'b--',label='sz1 n = ' + str(ntrotter) + ' (classical)') ax.plot(abs(J12)*c_times,0.5*sz2st_t,'r--', label='sz2 n = ' + str(ntrotter) + ' (classical)') ax.plot(abs(J12)*c_times,0.5*sz3st_t,'g--', label='sz3 n = ' + str(ntrotter) + ' (classical)') ax.plot(abs(J12)*q_times,0.5*sz1q_t,'b*',label='sz1 n = ' + str(ntrotter) + ' (quantum)') ax.plot(abs(J12)*q_times,0.5*sz2q_t,'ro', label='sz2 n = ' + str(ntrotter) + ' (quantum)') ax.plot(abs(J12)*q_times,0.5*sz3q_t,'gd', label='sz3 n = ' + str(ntrotter) + ' (quantum)') chartBox = ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height]) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1) plt.xlabel(r'$\delta_{12} = |J_{12}|t$') plt.show() qr = qk.QuantumRegister(1,name='qr') cr = qk.ClassicalRegister(1,name='cr') x_meas = qk.QuantumCircuit(qr,cr) # Here you can add any quantum circuit generating the quantum state # that you with to measure at the end e.g. # # x_meas.u3(a,b,c,qr[0]) # # Measurement in x direction x_meas.h(qr[0]) x_meas.measure(qr,cr) x_meas.draw(output='mpl') nshots = 8192 backend = qk.Aer.get_backend('qasm_simulator') job = qk.execute(x_meas, backend, shots=nshots) result = job.result() counts = result.get_counts() print(counts) average_sigma_x = 0 for key,value in counts.items(): if key == '0': average_sigma_x += value elif key == '1': average_sigma_x -= value average_sigma_x = average_sigma_x/nshots print('Average of sx = ', average_sigma_x) theta_a = np.linspace(0.0, 2*math.pi, 21) # Some angles for the a vector, with respect to the z axis theta_b = 0.0 # If the b vector is the z axis -> angle = 0 theta_c = math.pi/2 # If the vector c is the x axis -> angle = pi/2 with respect to z # Quantum version nshots = 1024 Pab = np.zeros(len(theta_a)) Pac = np.zeros(len(theta_a)) # Quantum circuit to measure Pbc qr = qk.QuantumRegister(2, name='qr') cr = qk.ClassicalRegister(2, name='cr') qc = qk.QuantumCircuit(qr, cr) ## Initialize Bell state qc.x(qr[0]) qc.x(qr[1]) qc.h(qr[0]) qc.cx(qr[0],qr[1]) ## Pre measurement unitaries to select the basis along a (for the first qubit) and b (for the second qubit) qc.u3(theta_b,0,0,qr[0]) qc.u3(theta_c,0,0,qr[1]) ## Measures qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) ## Running and saving result backend = qk.Aer.get_backend('qasm_simulator') job = qk.execute(qc, backend, shots=nshots) result = job.result() counts = result.get_counts() out = 0 for key,value in counts.items(): if (key == '00') or (key == '11'): out += value elif (key == '01') or (key == '10'): out -= value Pbc = out/nshots # Now we compute Pab and Pac for different a vectors for i in range(len(theta_a)): ta = theta_a[i] # Quantum circuit to measure Pab with the given a qr = qk.QuantumRegister(2, name='qr') cr = qk.ClassicalRegister(2, name='cr') qc = qk.QuantumCircuit(qr, cr) ## Initialize Bell state qc.x(qr[0]) qc.x(qr[1]) qc.h(qr[0]) qc.cx(qr[0],qr[1]) ## Pre measurement unitaries to select the basis along a (for the first qubit) and b (for the second qubit) qc.u3(ta,0,0,qr[0]) qc.u3(theta_b,0,0,qr[1]) ## Measures qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) ## Running and saving result backend = qk.Aer.get_backend('qasm_simulator') job = qk.execute(qc, backend, shots=nshots) result = job.result() counts = result.get_counts() out = 0 for key,value in counts.items(): if (key == '00') or (key == '11'): out += value elif (key == '01') or (key == '10'): out -= value Pab[i] = out/nshots # Quantum circuit to measure Pac with the given a qr = qk.QuantumRegister(2, name='qr') cr = qk.ClassicalRegister(2, name='cr') qc = qk.QuantumCircuit(qr, cr) ## Initialize Bell state qc.x(qr[0]) qc.x(qr[1]) qc.h(qr[0]) qc.cx(qr[0],qr[1]) ## Pre measurement unitaries to select the basis along a (for the first qubit) and c (for the second qubit) qc.u3(ta,0,0,qr[0]) qc.u3(theta_c,0,0,qr[1]) ## Measures qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) ## Running and saving result backend = qk.Aer.get_backend('qasm_simulator') job = qk.execute(qc, backend, shots=nshots) result = job.result() counts = result.get_counts() out = 0 for key,value in counts.items(): if (key == '00') or (key == '11'): out += value elif (key == '01') or (key == '10'): out -= value Pac[i] = out/nshots quantum_outs = Pab-Pac # Classical calculations thetas = np.linspace(0,2*math.pi,100) classical_outs = np.zeros(len(thetas)) b_vec = np.array([math.sin(theta_b),0.0,math.cos(theta_b)]) c_vec = np.array([math.sin(theta_c),0.0,math.cos(theta_c)]) Bell_limit = (1 - b_vec.dot(c_vec))*np.ones(len(thetas)) for k in range(len(thetas)): a_vec = np.array([math.sin(thetas[k]),0.0,math.cos(thetas[k])]) classical_outs[k] = -a_vec.dot(b_vec) + a_vec.dot(c_vec) fig = plt.figure() ax = plt.subplot(111) ax.plot(thetas,classical_outs,'b', label='classical computation') ax.plot(theta_a,quantum_outs,'r*', label='quantum algorithm') ax.plot(thetas,Bell_limit,'--k', label='Bell bound') # If the data go beyond these boundaries, ax.plot(thetas,-Bell_limit,'--k', label='Bell bound') # the inequality is violated ax.plot(thetas,(1+Pbc)*np.ones(len(thetas)),'--c', label='Bell bound (quantum)') ax.plot(thetas,-(1+Pbc)*np.ones(len(thetas)),'--c', label='Bell bound (quantum)') chartBox = ax.get_position() ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height]) ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1) plt.xlabel(r'$\theta_a$') plt.show() from qiskit.tools.monitor import job_monitor my_token = '' ibmq_provider = qk.IBMQ.enable_account(my_token) delta = 0.5*math.pi qr = qk.QuantumRegister(2,name='qr') cr = qk.ClassicalRegister(2,name='cr') Heis2 = qk.QuantumCircuit(qr,cr) # Initial state preparation Heis2.x(qr[0]) # ZZ Heis2.cx(qr[0],qr[1]) Heis2.u1(-2*delta,qr[1]) Heis2.cx(qr[0],qr[1]) # YY Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0]) Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1]) Heis2.cx(qr[0],qr[1]) Heis2.u1(-2*delta,qr[1]) Heis2.cx(qr[0],qr[1]) Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0]) Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1]) # XX Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0]) Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1]) Heis2.cx(qr[0],qr[1]) Heis2.u1(-2*delta,qr[1]) Heis2.cx(qr[0],qr[1]) Heis2.u3(math.pi/2, 0.0, 0.0, qr[0]) Heis2.u3(math.pi/2, 0.0, 0.0, qr[1]) # measure Heis2.measure(qr,cr) my_backend = ibmq_provider.get_backend('ibmqx2') job = qk.execute(Heis2, backend=my_backend, shots=1024) job_monitor(job, interval=5) result = job.result() counts = result.get_counts() print(counts) plot_histogram(counts) my_backend.configuration().coupling_map # In the output, the first entry in a pair [a,b] is a control, second is the # corresponding target for a CNOT
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate,Initialize from qiskit.quantum_info import Statevector from qiskit.tools.visualization import plot_bloch_vector from qiskit.tools.visualization import plot_histogram,plot_bloch_multivector import numpy as np import os from time import sleep import sys sys.path.append("..") from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline os.makedirs(name = "Plots/1-qubit/",exist_ok=True) from Modules.vanilla_qpe import QPE from Modules.iterative_qpe import IQPE from Modules.normal_SPEA import SPEA from Modules.kitaev_qpe import KQPE # x gate u1 = QuantumCircuit(1) u1.x(0) u1.draw('mpl') # x gate u2 = QuantumCircuit(1) u2.p(2*np.pi*(1/6),0) u2.draw('mpl') backend = Aer.get_backend('qasm_simulator') os.makedirs(name = "Plots/1-qubit/x_gate/",exist_ok=True) x_path = "Plots/1-qubit/x_gate/" estimates = [] for precision in range(1,9): qpe = QPE(precision=precision,unitary = u1) qpe_circ = qpe.get_QPE(show = False) qc = QuantumCircuit(precision+1,precision) qc.x(precision) qc.h(precision) qc.append(qpe_circ, qargs = list(range(precision+1))) qc.measure(list(range(precision)),list(range(precision))) # display(qc.draw('mpl')) counts = execute(qc,backend=backend,shots = 2**10).result().get_counts() m = -1 for i,j in counts.items(): if j > m: m = j phase = i factor = 0.5 ans = 0.0 for i in range(precision): ans+= int(phase[i])*factor factor/=2 estimates.append(ans) plt.title("Phase by basic QPE for the unitary X",fontsize = 16) plt.plot([i for i in range(1,9)],estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(x_path+"basic_qpe.JPG",dpi = 200) estimates = [] for precision in range(1,9): qpe = IQPE(precision=precision,unitary = u1,unknown=True) qc = QuantumCircuit(precision+1,precision) qc.x(1) qc.h(1) phase = qpe.get_circuit_phase(qc, qubits = [1], ancilla = 0,clbits = list(range(precision)),show = False) # display(qc.draw('mpl')) estimates.append(phase[1]) plt.title("Phase by iterative QPE for the unitary X",fontsize = 16) plt.plot([i for i in range(1,9)],estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(x_path+"iqpe.JPG",dpi = 200) estimates = [] for resolution in range(10,40,5): qpe = SPEA(resolution = resolution,unitary = u1, error =3) result = qpe.get_eigen_pair(backend = backend) # display(qc.draw('mpl')) print("Result : ",result) estimates.append(result['theta']) plt.title("Phase by SQPE for the unitary X",fontsize = 16) plt.plot([i for i in range(10,40,5)],estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([5,50],[0.5,0.5],color = 'black') plt.plot([5,50],[0,0],color = 'black') plt.plot([5,50],[1,1],color = 'black',label = 'Correct') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(x_path+"stat_qpe.JPG",dpi = 200) estimates = [] for precision in range(5,16): kqpe = KQPE(precision=precision,unitary = u1) kqpe_circ = kqpe.get_circuit() qc = QuantumCircuit(2+1,2) qc.x(2) qc.h(2) qc.append(kqpe_circ,qargs = [0,1,2]) phase = kqpe.get_phase(qc,backend = backend, ancilla = [0,1],clbits = [0,1],show = False) print("Precision :",precision) print("Phase:",phase) estimates.append(phase[0]) plt.title("Phase by Kitaev's Algorithm for the X gate",fontsize = 16) plt.plot([i for i in range(5,16)],estimates,color = 'magenta',alpha = 0.6,linewidth = 2,marker = 's',label = 'Estimates') plt.plot([5,17],[0.5,0.5],color = 'black') plt.plot([5,17],[-0.5,-0.5],color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(x_path+"kitaev_qpe.JPG",dpi = 200) os.makedirs(name = "Plots/1-qubit/phase_gate/",exist_ok=True) phase_path = "Plots/1-qubit/phase_gate/" estimates = [] for precision in range(1,9): qpe = QPE(precision=precision,unitary = u2) qpe_circ = qpe.get_QPE(show = False) qc = QuantumCircuit(precision+1,precision) qc.x(precision) qc.append(qpe_circ, qargs = list(range(precision+1))) qc.measure(list(range(precision)),list(range(precision))) # display(qc.draw('mpl')) counts = execute(qc,backend=backend,shots = 2**10).result().get_counts() m = -1 for i,j in counts.items(): if j > m: m = j phase = i factor = 0.5 ans = 0.0 for i in range(precision): ans+= int(phase[i])*factor factor/=2 estimates.append(ans) plt.title("Phase by basic QPE for the unitary with phase(1/6)",fontsize = 16) plt.plot([i for i in range(1,9)],estimates,color = 'red',alpha = 0.8, linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([0,10],[0.1667,0.1667], color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(phase_path+"basic_qpe.JPG",dpi = 200) estimates = [] for precision in range(1,9): qpe = IQPE(precision=precision,unitary = u2,unknown=True) qc = QuantumCircuit(1+1,precision) qc.x(1) phase = qpe.get_circuit_phase(qc, qubits = [1], ancilla = 0,clbits = list(range(precision)),show = False) # display(qc.draw('mpl')) estimates.append(phase[1]) plt.title("Phase by iterative QPE for the unitary with phase(1/6)",fontsize = 16) plt.plot([i for i in range(1,9)],estimates,color = 'orange',alpha = 0.7,linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([0,10],[0.1667,0.1667], color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(phase_path+"iqpe.JPG",dpi = 200) estimates = [] for resolution in range(10,40,5): qpe = SPEA(resolution = resolution,unitary = u2, error =4) result = qpe.get_eigen_pair(backend = backend) print("Result : ",result) estimates.append(result['theta']) plt.title("Phase by SQPE for the unitary with phase(1/6)",fontsize = 16) plt.plot([i for i in range(10,40,5)],estimates,color = 'g',alpha = 0.7,linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([5,50],[0.1667,0.1667],color = 'black') plt.plot([5,50],[0,0],color = 'black') plt.plot([5,50],[1,1],color = 'black',label = 'Correct') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(phase_path+"stat_qpe.JPG",dpi = 200) estimates = [] for precision in range(5,16): kqpe = KQPE(precision=precision,unitary = u2) kqpe_circ = kqpe.get_circuit() qc = QuantumCircuit(2+1,2) qc.x(2) qc.append(kqpe_circ,qargs = [0,1,2]) phase = kqpe.get_phase(qc,backend = backend, ancilla = [0,1],clbits = [0,1],show = False) # display(qc.draw('mpl')) print("Precision :",precision) print("Phase:",phase) estimates.append(phase[0]) plt.title("Phase by Kitaev's Algorithm for the unitary with phase(1/6)",fontsize = 16) plt.plot([i for i in range(5,16)],estimates,color = 'magenta',alpha = 0.6,linewidth = 2,marker = 's',label = 'Estimates') plt.plot([5,17],[0.1667,0.1667],color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(phase_path+"kitaev_qpe.JPG",dpi = 200)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate,Initialize from qiskit.quantum_info import Statevector from qiskit.tools.visualization import plot_bloch_vector from qiskit.tools.visualization import plot_histogram,plot_bloch_multivector import numpy as np from time import sleep import sys sys.path.append("..") import os from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline os.makedirs(name = "Plots/2-qubit/",exist_ok=True) from Modules.vanilla_qpe import QPE from Modules.iterative_qpe import IQPE from Modules.normal_SPEA import SPEA from Modules.kitaev_qpe import KQPE # x gate u1 = QuantumCircuit(2) u1.cp(2*np.pi*(1/7),0,1) u1.draw('mpl') # x gate u2 = QuantumCircuit(2) u2.z(0) u2.x(1) u2.draw('mpl') os.makedirs(name = "Plots/2-qubit/phase_gate/",exist_ok=True) phase_path = "Plots/2-qubit/phase_gate/" backend = Aer.get_backend('qasm_simulator') estimates = [] for precision in range(1,9): qpe = QPE(precision=precision,unitary = u1) qpe_circ = qpe.get_QPE(show = False) qc = QuantumCircuit(precision+2,precision) qc.x(precision) qc.x(precision+1) qc.append(qpe_circ, qargs = list(range(precision+2))) qc.measure(list(range(precision)),list(range(precision))) # display(qc.draw('mpl')) counts = execute(qc,backend=backend,shots = 2**10).result().get_counts() m = -1 for i,j in counts.items(): if j > m: m = j phase = i factor = 0.5 ans = 0.0 for i in range(precision): ans+= int(phase[i])*factor factor/=2 estimates.append(ans) plt.title("Phase by basic QPE for the unitary CP(1/7)",fontsize = 16) plt.plot([i for i in range(1,9)],estimates,alpha = 0.5,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([0,8],[0.1428,0.1428],color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(phase_path+"basic_qpe.JPG",dpi = 200) estimates = [] for precision in range(1,9): qpe = IQPE(precision=precision,unitary = u1,unknown=True) qc = QuantumCircuit(1+2,precision) qc.x(1) qc.x(2) phase = qpe.get_circuit_phase(qc, qubits = [1,2], ancilla = 0,clbits = list(range(precision)),show = False) # display(qc.draw('mpl')) estimates.append(phase[1]) plt.title("Phase by iterative QPE for the unitary CP(1/7)",fontsize = 16) plt.plot([i for i in range(1,9)],estimates,color = 'b',alpha = 0.5,linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([0,8],[0.1428,0.1428],color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(phase_path+"iqpe.JPG",dpi = 200) backend = Aer.get_backend('qasm_simulator') estimates = [] for _ in range(100): qpe = SPEA(resolution = 30,unitary = u1, error =4,max_iters=12) result = qpe.get_eigen_pair(progress = False, backend = backend) print("Result : ",result) estimates.append(result['theta']) plt.figure(figsize = (12,11)) plt.title("Phase by SQPE for the unitary CP(1/7)",fontsize = 16) plt.plot(range(100),estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([1,100],[0.1428,0.1428],color = 'black') plt.plot([1,100],[0,0],color = 'black') plt.plot([1,100],[1,1],color = 'black',label = 'Correct') plt.xlabel('Experiment') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(phase_path+"stat_qpe.JPG",dpi = 200) estimates = [] for precision in range(5,16): kqpe = KQPE(precision=precision,unitary = u1) kqpe_circ = kqpe.get_circuit() qc = QuantumCircuit(2+2,2) qc.x(2) qc.x(3) qc.append(kqpe_circ,qargs = [0,1,2,3]) phase = kqpe.get_phase(qc,backend = backend, ancilla = [0,1],clbits = [0,1],show = False) print("Precision :",precision) print("Phase:",phase) estimates.append(phase[0]) plt.title("Phase by Kitaev's Algorithm for the phase gate(1/7)",fontsize = 16) plt.plot([i for i in range(5,16)],estimates,color = 'cyan',alpha = 0.6,linewidth = 2,marker = 's',label = 'Estimates') plt.plot([5,17],[0.1428,0.1428],color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(phase_path+"kitaev_qpe.JPG",dpi = 200) os.makedirs(name = "Plots/2-qubit/zx_gate/",exist_ok=True) zx_path = "Plots/2-qubit/zx_gate/" estimates = [] for precision in range(1,9): # qpe = QPE(precision=precision,unitary = u2) qpe_circ = qpe.get_QPE(show = False) # Quantum Circuit qc = QuantumCircuit(precision+2,precision) # make the eigenvector qc.x(precision+1) qc.h(precision+1) qc.append(qpe_circ, qargs = list(range(precision+2))) qc.measure(list(range(precision)),list(range(precision))) counts = execute(qc,backend=backend,shots = 2**10).result().get_counts() m = -1 for i,j in counts.items(): if j > m: m = j phase = i factor = 0.5 ans = 0.0 for i in range(precision): ans+= int(phase[i])*factor factor/=2 estimates.append(ans) plt.title("Phase by basic QPE for the unitary ZX",fontsize = 16) plt.plot([i for i in range(1,9)],estimates,alpha = 0.5,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([0,8],[0.5,0.5],color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(zx_path+"basic_qpe.JPG",dpi = 200) estimates = [] for precision in range(1,9): qpe = IQPE(precision=precision,unitary = u2,unknown=True) qc = QuantumCircuit(1+2,precision) # making the eigenvector qc.x(2) qc.h(2) phase = qpe.get_circuit_phase(qc, qubits = [1,2], ancilla = 0,clbits = list(range(precision)),show = False) # display(qc.draw('mpl')) estimates.append(phase[1]) plt.title("Phase by iterative QPE for the unitary ZX",fontsize = 16) plt.plot([i for i in range(1,9)],estimates,color = 'b',alpha = 0.5,linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([0,8],[0.5,0.5],color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(zx_path+"iqpe.JPG",dpi = 200) estimates = [] for resolution in range(10,40,5): qpe = SPEA(resolution = resolution,unitary = u2, error =4,max_iters=12) result = qpe.get_eigen_pair(progress = True, backend = backend) print("Result : ",result) estimates.append(result['theta']) plt.title("Phase by SQPE for the unitary ZX",fontsize = 16) plt.plot([i for i in range(10,40,5)],estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates') plt.plot([5,50],[0.5,0.5],color = 'black') plt.plot([5,50],[0,0],color = 'black') plt.plot([5,50],[1,1],color = 'black',label = 'Correct') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(zx_path+"stat_qpe.JPG",dpi = 200) estimates = [] for precision in range(5,16): kqpe = KQPE(precision=precision,unitary = u2) kqpe_circ = kqpe.get_circuit() qc = QuantumCircuit(2+2,2) qc.x(3) qc.h(3) qc.append(kqpe_circ,qargs = [0,1,2,3]) phase = kqpe.get_phase(qc,backend = backend, ancilla = [0,1],clbits = [0,1],show = False) # display(qc.draw('mpl')) print("Precision :",precision) print("Phase:",phase) estimates.append(phase[0]) plt.title("Phase by Kitaev's Algorithm for the zx gate",fontsize = 16) plt.plot([i for i in range(5,16)],estimates,color = 'orange',alpha = 0.6,linewidth = 2,marker = 's',label = 'Estimates') plt.plot([5,17],[0.5,0.5],color = 'black') plt.plot([5,17],[-0.5,-0.5],color = 'black') plt.xlabel('Precision') plt.ylabel('Estimates') plt.grid() plt.legend() plt.savefig(zx_path+"kitaev_qpe.JPG",dpi = 200)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import * import matplotlib.pyplot as plt from qiskit.extensions import UnitaryGate from qiskit.circuit import add_control from qiskit.tools.visualization import plot_bloch_multivector,plot_histogram import numpy as np import sys sys.path.append("..") from Modules.vanilla_qpe import QPE U= UnitaryGate(data = np.array([[1,0], [0,np.exp(2*np.pi*1j*(1/5))]])) qpe_circ1 = QPE(precision=4,unitary=U).get_QPE(show=True,save = False) q = QuantumCircuit(5,4) q.x(4) q.barrier() q = q.compose(qpe_circ1,qubits = [0,1,2,3,4]) q.draw('mpl') q.measure([0,1,2,3],[0,1,2,3]) q.draw('mpl') count = execute(q,backend=Aer.get_backend('qasm_simulator')).result().get_counts() fig = plot_histogram(count,title = "Phase estimates for $\\theta = 1/5$") fig.savefig("Phase 0.2 estimate.JPG",dpi = 200) fig q = QuantumCircuit(3,name = 'Unitary') q.cp(2*np.pi*(1/5),1,2) q.draw('mpl') qpe_circ2 = QPE(precision=4,unitary=q).get_QPE(show=True,save=True) q = QuantumCircuit(7,4) q.x([5,6]) q.barrier() q.append(qpe_circ2, qargs = [0,1,2,3,4,5,6]) q.measure([0,1,2,3],[0,1,2,3]) q.draw('mpl') count = execute(q,backend=Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(count) q = QuantumCircuit(7,5) q.x(4) q.compose(qpe_circ1,qubits = [0,1,2,3,4], inplace = True) # q = q.compose(qpe_circ,qubits = [0,1,2,3,4]) q.draw('mpl') q.measure([0,1,2,3],[0,1,2,3]) q.draw('mpl') count = execute(q,backend=Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(count)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import * import matplotlib.pyplot as plt from qiskit.extensions import UnitaryGate from qiskit.circuit import add_control from IPython.display import display from qiskit.tools.visualization import plot_histogram import numpy as np import sys sys.path.append("..") from Modules.faster_basic_qpe import fast_QPE U = np.array([[1, 0], [0, np.exp(2*np.pi*1j*(1/5))]]) qpe_circ = fast_QPE(precision=4, unitary=U).get_QPE(show=True) q = QuantumCircuit(5, 4) q.x(4) q.append(qpe_circ, qargs=[0, 1, 2, 3, 4]) # q = q.compose(qpe_circ,qubits = [0,1,2,3,4]) q.draw('mpl') q.measure([0, 1, 2, 3], [0, 1, 2, 3]) q.draw('mpl') count = execute(q, backend=Aer.get_backend( 'qasm_simulator')).result().get_counts() plot_histogram(count) q = QuantumCircuit(3,name = 'Unitary') q.cp(2*np.pi*(1/7),1,2) display(q.draw('mpl')) # u = execute(q,backend = Aer.get_backend('unitary_simulator')).result().get_unitary() qpe_circ = fast_QPE(precision=4,unitary=q).get_QPE(show=True,save = True) q = QuantumCircuit(7,4) q.x([5,6]) q.barrier() q.append(qpe_circ, qargs = [0,1,2,3,4,5,6]) q.measure([0,1,2,3],[0,1,2,3]) q.draw('mpl') count = execute(q,backend=Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(count) q = QuantumCircuit(7, 4) q.x([5,6]) q.append(qpe_circ, qargs=range(7)) # q = q.compose(qpe_circ,qubits = [0,1,2,3,4]) q.draw('mpl') q.measure([0, 1, 2, 3], [0, 1, 2, 3]) q.draw('mpl') count = execute(q, backend=Aer.get_backend( 'qasm_simulator')).result().get_counts() plot_histogram(count)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import * from qiskit import transpile import numpy as np import matplotlib.pyplot as plt from qiskit.extensions import UnitaryGate from qiskit import IBMQ import sys sys.path.append("..") %matplotlib inline qiskit.__qiskit_version__ from Modules.iterative_qpe import IQPE U = UnitaryGate(data=np.array([[1, 0], [0, np.exp(2*np.pi*1j*(1/5))]])) iqpe = IQPE(precision=4,unitary=U,unknown=True) q = QuantumCircuit(2, 4) q.x(1) phase = iqpe.get_circuit_phase( QC=q, clbits=[0, 1, 2, 3], qubits=[1],ancilla=0, show=True, save_circ = True) phase U = QuantumCircuit(2,name='U') U.cp(2*np.pi*1/6,0,1) U.draw('mpl') #.control(num_ctrl_qcubits= 1, label = 'CCu', ctrl_state = '1') iqpe = IQPE(precision=4,unitary=U,unknown=True) q = QuantumCircuit(3, 4) q.x(1) q.x(2) phase = iqpe.get_circuit_phase( QC=q, clbits=[0, 1, 2, 3], qubits=[1,2],ancilla=0, show=True,save_circ = True,circ_name = "IQPE_circ.JPG") print("Phase of the circuit in binary:", phase) u2 = QuantumCircuit(3) u2.cp(2*np.pi*(1/6),1,2) u2.draw('mpl') estimates = [] for prec in range(2, 9): q = QuantumCircuit(4, prec) # making eigenvector q.x(2) q.x(3) iqpe = IQPE(precision=prec, unitary=u2,unknown=True) phase = iqpe.get_circuit_phase( QC=q, clbits=[i for i in range(prec)], qubits=[1,2,3], ancilla=0) # print(phase[0]) estimates.append(phase[1]) plt.figure(figsize=(9, 7)) plt.plot(list(range(2, 9)), estimates, marker='o', label='Estimates', linestyle='dotted',linewidth = 2,color = 'cyan') plt.plot([0, 10], [0.16667, 0.16667], color='black', label='Actual phase') plt.title("IQPE estimates for $\\theta = 1/6$", fontsize=16) plt.xlabel("Number of iterations ", fontsize=14) plt.ylabel("Estimate of phase", fontsize=14) plt.legend() from Modules.iterative_qpe import get_estimate_plot_phase IBMQ.load_account() ## provider = IBMQ.get_provider('''ENTER YOUR PROVIDER''') casb = provider.get_backend('ibmq_casablanca') get_estimate_plot_phase(theta=0.524, iters = 9,unknown= True, save=True, experiments=5,backend=casb) get_estimate_plot_phase(0.111, iters= 8, unknown=True, save=True,experiments=3)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import * import numpy as np import sys sys.path.append("..") qiskit.__qiskit_version__ from Modules.kitaev_qpe import KQPE U = np.array([[1, 0], [0, np.exp(2*np.pi*1j*(1/3))]]) kqpe = KQPE(unitary=U, precision=16) kq_circ = kqpe.get_circuit(show=True, save_circ=True, circ_name="KQPE_circ_1qubit.JPG") q = QuantumCircuit(5, 6) q.x(3) q.append(kq_circ, qargs=[1, 2, 3]) q.draw('mpl') phase = kqpe.get_phase(backend=Aer.get_backend( 'qasm_simulator'), QC=q, ancilla=[1, 2], clbits=[0, 1], show=True) print("Phase of the unitary is :", phase) q = QuantumCircuit(2, name='Unitary') q.cp(2*np.pi*(1/7), 0, 1) q.draw('mpl') unitary = q kqpe = KQPE(unitary, precision=12) kq_circ = kqpe.get_circuit(show=True) q = QuantumCircuit(5, 2) q.x([2, 3]) q.append(kq_circ, qargs=[0, 1, 2, 3]) q.draw('mpl') sim = Aer.get_backend('qasm_simulator') phase = kqpe.get_phase(backend=sim, QC=q, ancilla=[ 0, 1], clbits=[0, 1], show=True) print("Phase returned is :", phase) q = QuantumCircuit(2, name='Phase Unitary') q.cp(2*np.pi*(1/7), 0, 1) display(q.draw('mpl')) unitary = q precision = [i for i in range(8, 18)] precision estimates, errors = [], [] for prec in precision: kqpe = KQPE(unitary, precision=prec) kq_circ = kqpe.get_circuit(show=False) # making circuit q = QuantumCircuit(5, 2) q.x([2, 3]) q.append(kq_circ, qargs=[0, 1, 2, 3]) # getting the phase phase = kqpe.get_phase(backend=sim, QC=q, ancilla=[ 0, 1], clbits=[0, 1], show=False) estimates.append(phase[0]) errors.append(abs(1/7-phase[0])) import matplotlib.pyplot as plt plt.title("Phase Estimation for $ \phi $ = 1/7", fontsize=16) plt.xlabel("Precision for estimation") plt.ylabel("Estimates for Error and Phase") plt.plot([7, 18], [1/7, 1/7], color='black', label='Actual', linewidth=2) plt.plot(precision, estimates, marker='o', color='magenta', alpha=0.6, label='Phase Estimate') plt.plot(precision, errors, marker='s', color='cyan', alpha=0.6, label="Error estimate") plt.grid() plt.legend() plt.savefig("Kitaev Multiqubit Estimation Plot.JPG", dpi=200)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate, Initialize import numpy as np from qiskit.providers.ibmq.managed import IBMQJobManager from sys import stdout from scipy.stats import unitary_group class bundled_SPEA_alternate: def __init__(self, unitary, resolution=100, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError("Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001" ) self.resolution = resolution # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix" ) # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2 ** (U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)" ) if error <= 0: raise ValueError("The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError("Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def get_basis_vectors(self, randomize=True): # get the d dimensional basis for the unitary provided if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def get_unitary_circuit(self, backend): """Return the pretranspiled circuit""" if backend is None: backend = Aer.get_backend("qasm_simulator") qc = QuantumCircuit(1 + int(np.log2(self.dims))) # make the circuit qc.h(0) qc = qc.compose(self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims)))) qc.barrier() qc = transpile(qc, backend=backend, optimization_level=3) return qc def get_circuit(self, state, backend, shots, angle=None): """Given an initial state , return the circuit that is generated with inverse rotation as 0.""" # all theta values are iterated over for the same state phi = Initialize(state) shots = 512 qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc1 = qc1.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1))) qc1 = transpile(qc1, backend=backend) # get the circuit2 qc2 = self.unitary_circuit qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) if angle is not None: # add inverse rotation on the first qubit qc3.p(-2 * np.pi * angle, 0) # add hadamard qc3.h(0) qc3 = transpile(qc3, backend=backend) # make final circuit qc = qc1 + qc2 + qc3 # qc = assemble(qc,shots = shots) # measure qc.measure([0], [0]) return qc def get_optimal_angle(self, p0, p1, angles): """Return the theta value which minimizes the S metric""" min_s = 1e5 best_theta = -1 for theta in angles: c0 = (np.cos(np.pi * theta)) ** 2 c1 = (np.sin(np.pi * theta)) ** 2 # generate the metric ... s = (p0 - c0) ** 2 + (p1 - c1) ** 2 if s < min_s: s = min_s best_theta = theta return best_theta def execute_job(self, progress, iteration, backend, shots, circuits): """Send a job to the backend using IBMQ Job Manager""" # define IBMQManager instance manager = IBMQJobManager() # first run the generated circuits if progress: print("Transpiling circuits...") # get the job runner instance job_set = manager.run( circuits, backend=backend, name="Job_set " + str(iteration), shots=shots ) if progress: print("Transpilation Done!\nJob sent...") # send and get job job_result = job_set.results() if progress: print("Job has returned") # return result return job_result def get_eigen_pair( self, backend, theta_left=0, theta_right=1, progress=False, randomize=True, basis=None, basis_ind=None, target_cost=None, shots=512, ): """Finding the eigenstate pair for the unitary""" self.unitary_circuit = self.get_unitary_circuit(backend) if theta_left > theta_right: raise ValueError( "Left bound for theta should be smaller than the right bound" ) elif (theta_left < 0) or (theta_right > 1): raise ValueError("Bounds of theta are [0,1].") if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") results = dict() # first initialize the state phi if basis is None: self.basis = self.get_basis_vectors(randomize) else: self.basis = basis # choose a random index if basis_ind is None: ind = np.random.choice(self.dims) else: ind = basis_ind phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision precision = 1 / 10 ** self.error samples = self.resolution # initialization of range left, right = theta_left, theta_right # generate the angles angles = np.linspace(left, right, samples) # First execution can be done without JobManager also... circ = self.get_circuit(phi, backend=backend, shots=shots) job = execute(circ, backend=backend, shots=shots) counts = job.result().get_counts() if "0" in counts: p0 = counts["0"] else: p0 = 0 if "1" in counts: p1 = counts["1"] else: p1 = 0 # experimental probabilities p0, p1 = p0 / shots, p1 / shots # get initial angle estimate theta_max = self.get_optimal_angle(p0, p1, angles) # get intial cost circ = self.get_circuit(phi, backend=backend, shots=shots, angle=theta_max) job = execute(circ, backend=backend, shots=shots) counts = job.result().get_counts() if "0" in counts: cost = counts["0"] / shots else: cost = 0 # update best phi best_phi = phi # the range upto which theta extends iin each iteration angle_range = (right - left) / 2 # a parameter a = 1 # start algorithm iters = 0 found = True while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(theta_right, theta_max + angle_range / 2) left = max(theta_left, theta_max - angle_range / 2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters + 1, "...") # generate a cost dict for each of the iterations # final result lists costs, states = [], [] # circuit list circuits = [] # 1. Circuit generation loop for i in range((2 * self.dims)): # everyone is supplied with the same range of theta in one iteration # define z if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) states.append(curr_phi) # bundle the circuits together ... circuits.append( self.get_circuit(curr_phi, backend=backend, shots=shots) ) job_result = self.execute_job(progress, iters, backend, shots, circuits) # define lists again thetas, circuits = [], [] # 3. Classical work for i in range((2 * self.dims)): # we have that many circuits only counts = job_result.get_counts(i) # get the experimental counts for this state try: exp_p0 = counts["0"] except: exp_p0 = 0 try: exp_p1 = counts["1"] except: exp_p1 = 0 # normalize exp_p0 = exp_p0 / shots exp_p1 = exp_p1 / shots theta_val = self.get_optimal_angle(exp_p0, exp_p1, angles) # generate the circuit and append circuits.append( self.get_circuit( states[i], backend=backend, shots=shots, angle=theta_val ) ) thetas.append(theta_val) # again execute these circuits job_result = self.execute_job(progress, iters, backend, shots, circuits) # 5. Result generation loop for i in range((2 * self.dims)): # cost generation after execution ... counts = job_result.get_counts(i) if "0" in counts: curr_cost = counts["0"] / (shots) else: curr_cost = 0 if ( curr_cost > cost ): # then only add this cost in the cost and states list cost = curr_cost best_phi = states[i] theta_max = thetas[i] found = True if progress: stdout.write("\r") stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims))) stdout.flush() if found == False: # phi was not updated , change a a = a / 2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only print if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm..." ) break # add cost, eigenvector and theta to the dict results["cost"] = cost results["theta"] = theta_max results["state"] = best_phi return results
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate, Initialize from qiskit.providers.ibmq.managed import IBMQJobManager import numpy as np from sys import stdout from scipy.stats import unitary_group class bundled_changed_SPEA: def __init__(self, unitary, resolution=100, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError("Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001" ) self.resolution = resolution # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix" ) # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2 ** (U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)" ) if error <= 0: raise ValueError("The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError("Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def get_basis_vectors(self, randomize=True): # get the d dimensional basis for the unitary provided if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def get_circuits(self, angles, state): """Given an initial state and a set of angles, return the circuits that are generated with those angles""" result = {"cost": -1, "theta": -1} # all theta values are iterated over for the same state phi = Initialize(state) shots = 512 circuits = [] for theta in angles: qc = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc = qc.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1))) # add hadamard qc.h(0) # add unitary which produces a phase kickback on control qubit qc = qc.compose( self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims))) ) # add the inv rotation qc.p(-2 * np.pi * theta, 0) # add hadamard qc.h(0) # measure qc.measure([0], [0]) # generate all the circuits... circuits.append(qc) return circuits def get_cost(self, angles, counts, shots): """Generate the best cost and theta pair for the particular state""" result = {"cost": -1, "theta": -1} # get the cost for this theta for k, theta in zip(counts, angles): # for all experiments you ran try: C_val = (k["0"]) / shots except: C_val = 0 if C_val > result["cost"]: # means this is a better theta value result["theta"] = theta result["cost"] = C_val return result def get_eigen_pair(self, backend, progress=False, randomize=True): """Finding the eigenstate pair for the unitary""" if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") results = dict() # first initialize the state phi self.basis = self.get_basis_vectors(randomize) # choose a random index ind = np.random.choice(self.dims) phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision precision = 1 / 10 ** self.error samples = self.resolution # initialization of range left, right = 0, 1 shots = 512 # generate the angles angles = np.linspace(left, right, samples) # First execution can be done without JobManager also... circs = self.get_circuits(angles, phi) job = execute(circs, backend=backend, shots=shots) counts = job.result().get_counts() result = self.get_cost(angles, counts, shots) # get initial estimates cost = result["cost"] theta_max = result["theta"] best_phi = phi # the range upto which theta extends iin each iteration angle_range = 0.5 # a parameter a = 1 # start algorithm iters = 0 found = True plus = (1 / np.sqrt(2)) * np.array([1, 1]) minus = (1 / np.sqrt(2)) * np.array([1, -1]) # define IBMQManager instance manager = IBMQJobManager() while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(1, theta_max + angle_range / 2) left = max(0, theta_max - angle_range / 2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters + 1, "...") # generate a cost dict for each of the iterations # final result lists thetas, costs, states = [], [], [] # circuit list circuits = [] # list to store intermediate states phis = [] # 1. Circuit generation loop for i in range((2 * self.dims)): # everyone is supplied with the same range of theta in one iteration # define z # make a list of the circuits if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) phis.append(curr_phi) # bundle the circuits together ... circs = self.get_circuits(angles, curr_phi) circuits = circuits + circs # now each iteration would see the same state as the best phi # is updated once at the end of the iteration # also, the cost is also updated only once at the end of the iteration # 2. run the generated circuits if progress: print("Transpiling circuits...") circuits = transpile(circuits=circuits, backend=backend) job_set = manager.run( circuits, backend=backend, name="Job_set" + str(iters), shots=shots ) if progress: print("Transpilation Done!\nJob sent...") job_result = job_set.results() # now get the circuits in chunks of resolution each if progress: print("Job has returned") # 3. Result generation loop for i in range((2 * self.dims)): # get the results of this basis state # it will have resolution number of circuits... counts = [] for j in range(i * self.resolution, (i + 1) * self.resolution): # in this you'll get the counts counts.append(job_result.get_counts(j)) result = self.get_cost(counts, angles, shots) # get the estimates for this basis curr_theta = result["theta"] curr_cost = result["cost"] curr_phi = phis[i] # the result was generated pertaining to this phi if ( curr_cost > cost ): # then only add this cost in the cost and states list thetas.append(float(curr_theta)) costs.append(float(curr_cost)) states.append(curr_phi) found = True if progress: stdout.write("\r") stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims))) stdout.flush() if found == False: # phi was not updated , change a a = a / 2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only update # O(n) , would update this though index = np.argmax(costs) # update the parameters of the model cost = costs[index] theta_max = thetas[index] best_phi = states[index] if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm..." ) break # add cost, eigenvector and theta to the dict results["cost"] = cost results["theta"] = theta_max results["state"] = best_phi return results
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate, Initialize from qiskit.providers.ibmq.managed import IBMQJobManager import numpy as np from sys import stdout from scipy.stats import unitary_group class global_max_SPEA: """ This is a class which implements the Statistical Phase Estimation algorithm. The global max SPEA looks to update the cost returned at the end of one itertation as compared to the original normal SPEA. This allows an advantage of the bundling up of circuits and thus helps to speed up the quantum execution time. paper1 - https://arxiv.org/pdf/2104.10285.pdf paper2 - https://arxiv.org/pdf/1906.11401.pdf(discussion) Attributes : resolution(int) : the number of intervals the angle range has to be divided into dims(int) : dimensions of the passed unitary matrix c_unitary_gate(Unitary Gate) : the controlled unitary gate in our algorithm error(int) : the number of places after decimal, upto which the cost of the algorithm would be estimated itrations(int) : the maximum iterations after which the algorithm ends the computation basis(list of np.ndarray) : the basis generated at the start of the algorithm unitary_circuit(QuantumCircuit): a pre-transpiled QuantumCircuit which is applied during the algorithm Methods : __get_basis_vectors(randomize) : Get the d dimensional basis for the initializtion of the algorithm __get_unitary_circuit(backend) : Get the pre-transpiled circuit for the unitary matrix __get_alternate_cost(angle,state,backend,shots) : Get the cost through the alternate method specified in the algorithm __get_standard_cost(angle,state,backend,shots) : Get the cost through the standard method specified in the algorithm __get_circuit(state,angle,backend,shots) : Get the completed circuit used inside the algorithm to estimate the phase get_eigen_pair(backend, algo='alternate', theta_left,theta_right,progress, randomize, target_cost, basis, basis_ind,shots) : Get the eigenstate and eigenphase phase pair for the unitary matrix """ def __init__(self, unitary, resolution=100, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError("Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001" ) self.resolution = resolution # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix" ) # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2 ** (U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)" ) if error <= 0: raise ValueError("The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError("Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def __get_basis_vectors(self, randomize=True): """Get the d dimensional basis for the unitary provided Args : randomize (bool) : whether to pick a random basis or not Returns: a list of np.ndarrays which are used as the basis vectors""" if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def __get_unitary_circuit(self, backend): """Return the pretranspiled circuit Args: backend : the IBMQBackend on which we want to transpile. If None, Default : 'qasm_simulator' Returns: QuantumCircuit containing the transpiled circuit for the controlled unitary """ if backend is None: backend = Aer.get_backend("qasm_simulator") qc = QuantumCircuit(1 + int(np.log2(self.dims))) # make the circuit qc.h(0) qc = qc.compose(self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims)))) qc.barrier() qc = transpile(qc, backend=backend, optimization_level=3) return qc def __get_circuit(self, state, backend, shots, angle=None): """Given an initial state , return the assembled and transpiled circuit that is generated with inverse rotation Args: state(np.ndarray) : The eigenvector guess state for the initialization backend(IBMQBackend) : the backend on which this circuit is going to be executed shots(int) : the number of shots in our experiments angle(float) : whether the returned circuit contains an inverse rotation gate or not. If angle is None, no rotation gate attached Else, cp(angle) is attached on control qubit 0 Returns: QuantumCircuit which is pre-transpiled according to the backend provided """ # all theta values are iterated over for the same state phi = Initialize(state) qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc1 = qc1.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1))) qc1.barrier() qc1 = transpile(qc1, backend=backend, optimization_level=1) # get the circuit2 qc2 = self.unitary_circuit qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) if angle is not None: # add inverse rotation on the first qubit qc3.p(-2 * np.pi * angle, 0) # add hadamard qc3.h(0) qc3 = transpile(qc3, backend=backend, optimization_level=1) # make final circuit qc = qc1 + qc2 + qc3 # measure qc.measure([0], [0]) # qc = assemble(qc,shots = shots) return qc def __get_standard_cost(self, angles, state, backend, shots): """Given an initial state and a set of angles, return the best cost and the associated angle. Implements the standard method as specified in the paper. Args : angles(np.ndarray) : the set of angles on which we execute the circuits state(np.ndarray) : the initialization state provided backend(IBMQBackend): the backend on which this circuit needs to be executed shots(int) : the number of shots used to execute this circuit Returns : result(dict) : {result : (float), theta : (float)} result - the best cost given this set of angles theta - the best theta value amongst this set of angles""" result = {"cost": -1, "theta": -1} # all theta values are iterated over for the same state circuits = [] for theta in angles: qc = self.__get_circuit(state, backend, shots, theta) circuits.append(qc) # execute only once... counts = backend.run(circuits, shots=shots).result().get_counts() # get the cost for this theta for k, theta in zip(counts, angles): # for all experiments you ran try: C_val = (k["0"]) / shots except: C_val = 0 if C_val > result["cost"]: # means this is a better theta value result["theta"] = theta result["cost"] = C_val return result def __get_alternate_cost(self, angles, state, backend, shots): """Given an initial state and a set of angles, return the best cost and the associated angle. Implements the alternate method as specified in the paper1 and discussion of paper2. Args : angles(np.ndarray) : the set of angles on which we execute the circuits state(np.ndarray) : the initialization state provided backend(IBMQBackend): the backend on which this circuit needs to be executed shots(int) : the number of shots used to execute this circuit Returns : result(dict) : {result : (float), theta : (float)} result - the best cost given this set of angles theta - the best theta value amongst this set of angles""" result = {"cost": -1, "theta": -1} # all theta values are iterated over for the same state # run the circuit once qc = self.__get_circuit(state, backend, shots) # execute only once... counts = backend.run(qc, shots=shots).result().get_counts() # generate experimental probabilities try: p0 = counts["0"] / shots except: p0 = 0 try: p1 = counts["1"] / shots except: p1 = 0 # now, find the best theta as specified by the # alternate method classically min_s = 1e5 for theta in angles: # generate theoretical probabilities c0 = (np.cos(np.pi * theta)) ** 2 c1 = (np.sin(np.pi * theta)) ** 2 # generate s value s = (p0 - c0) ** 2 + (p1 - c1) ** 2 if s < min_s: result["theta"] = theta min_s = s # now , we have the best theta stored in phi # run circuit once again to get the value of C* qc = self.__get_circuit(state, backend, shots, result["theta"]) counts = backend.run(qc, shots=shots).result().get_counts() try: result["cost"] = counts["0"] / shots except: result["cost"] = 0 # no 0 counts present # return the result return result def __validate_params( self, algorithm, progress, randomize, target_cost, bounds ) -> None: # validate algorithm if not isinstance(algorithm, str): raise TypeError( "Algorithm must be mentioned as a string from the values {alternate,standard}" ) elif algorithm not in ["alternate", "standard"]: raise ValueError( "Algorithm must be specified as 'alternate' or 'standard' " ) # validate progress if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") # validate target_cost if target_cost is not None: if not isinstance(target_cost, float): raise TypeError("Target cost must be a float") if target_cost <= 0 or target_cost >= 1: raise ValueError("Target cost must be a float value between 0 and 1") # validate bounds theta_left, theta_right = bounds[0], bounds[1] if theta_left > theta_right: raise ValueError( "Left bound for theta should be smaller than the right bound" ) elif (theta_left < 0) or (theta_right > 1): raise ValueError("Bounds of theta are [0,1].") def get_eigen_pair( self, backend, algo="alternate", theta_left=0, theta_right=1, progress=False, basis=None, basis_ind=None, randomize=True, target_cost=None, shots=512, ): """Finding the eigenstate pair for the unitary Args : backend(IBMQBackend) : the backend on which the circuit needs to be executed algo(str) : ['alternate','standard'] the algorithm to use as specified in the paper1 section 3. theta_left(float): the left bound for the search of eigenvalue. Default : 0 theta_right(float): the right bound for the search of eigenvalue. Default : 1 progress(bool) : Whether to show the progress as the algorithm runs randomize(bool): Whether to choose random initialization of basis states or not If False, computational basis is chosen. target_cost(float) : the min cost required to be achieved by the algorithm basis(list of np.ndarray) : The basis to be used in the algorithm. Note, if basis is specified, randomize value is ignored basis_ind(int) : the index of the basis vector to be used as the initial state vector Returns : result(dict) : {cost :(float), theta :(float), state : (np.ndarray) cost - the cost with which the algorithm terminates theta - the eigenvalue estimated by SPEA state - the eigenvector estimated by SPEA Example Usage found in notebook Statistical QPE-Changed Algorithm.ipynb""" self.unitary_circuit = self.__get_unitary_circuit(backend) self.__validate_params( algo, progress, randomize, target_cost, [theta_left, theta_right] ) results = dict() # first initialize the state phi if basis is None: self.basis = self.__get_basis_vectors(randomize) else: # is basis is specified, given as array of vectors... self.basis = basis # choose a random index if basis_ind is None: ind = np.random.choice(self.dims) else: # choose the index given in that basis ind = basis_ind phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision if target_cost == None: precision = 1 / 10 ** self.error else: precision = 1 - target_cost samples = self.resolution # initialization of range left, right = theta_left, theta_right # generate the angles angles = np.linspace(left, right, samples) # iterate once if algo == "alternate": result = self.__get_alternate_cost(angles, phi, backend, shots) else: result = self.__get_standard_cost(angles, phi, backend, shots) # get initial estimates cost = result["cost"] theta_max = result["theta"] best_phi = phi # the range upto which theta extends iin each iteration angle_range = (right - left) / 2 # a parameter a = 1 # start algorithm iters = 0 found = True while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(theta_right, theta_max + angle_range / 2) left = max(theta_left, theta_max - angle_range / 2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters + 1, "...") # generate a cost dict for each of the iterations thetas, costs, states = [], [], [] for i in range((2 * self.dims)): # everyone is supplied with the same range of theta in one iteration # define z if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) # iterate (angles would be same until theta is changed) if algo == "alternate": res = self.__get_alternate_cost(angles, curr_phi, backend, shots) else: res = self.__get_standard_cost(angles, curr_phi, backend, shots) curr_cost = res["cost"] curr_theta = res["theta"] # append these parameters # bundle the circuits together ... if ( curr_cost > cost ): # then only add this cost in the cost and states list thetas.append(float(curr_theta)) costs.append(float(curr_cost)) states.append(curr_phi) found = True # now each iteration would see the same state as the best phi # is updated once at the end of the iteration # also, the cost is also updated only once at the end of the iteration if progress: stdout.write("\r") stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims))) stdout.flush() # 1 iteration completes if found == False: # phi was not updated , change a a = a / 2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only update # O(n) , would update this though index = np.argmax(costs) # update the parameters of the model cost = costs[index] theta_max = thetas[index] best_phi = states[index] if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm..." ) break # add cost, eigenvector and theta to the dict results["cost"] = cost results["theta"] = theta_max results["state"] = best_phi return results class bundled_SPEA_alternate: def __init__(self, unitary, resolution=100, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError("Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001" ) self.resolution = resolution # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix" ) # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2 ** (U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)" ) if error <= 0: raise ValueError("The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError("Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def get_basis_vectors(self, randomize=True): # get the d dimensional basis for the unitary provided if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def get_unitary_circuit(self, backend): """Return the pretranspiled circuit""" if backend is None: backend = Aer.get_backend("qasm_simulator") qc = QuantumCircuit(1 + int(np.log2(self.dims))) # make the circuit qc.h(0) qc = qc.compose(self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims)))) qc.barrier() qc = transpile(qc, backend=backend, optimization_level=3) return qc def get_circuit(self, state, backend, shots, angle=None): """Given an initial state , return the circuit that is generated with inverse rotation as 0.""" # all theta values are iterated over for the same state phi = Initialize(state) shots = 512 qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc1 = qc1.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1))) qc1 = transpile(qc1, backend=backend) # get the circuit2 qc2 = self.unitary_circuit qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) if angle is not None: # add inverse rotation on the first qubit qc3.p(-2 * np.pi * angle, 0) # add hadamard qc3.h(0) qc3 = transpile(qc3, backend=backend) # make final circuit qc = qc1 + qc2 + qc3 # qc = assemble(qc,shots = shots) # measure qc.measure([0], [0]) return qc def get_optimal_angle(self, p0, p1, angles): """Return the theta value which minimizes the S metric""" min_s = 1e5 best_theta = -1 for theta in angles: c0 = (np.cos(np.pi * theta)) ** 2 c1 = (np.sin(np.pi * theta)) ** 2 # generate the metric ... s = (p0 - c0) ** 2 + (p1 - c1) ** 2 if s < min_s: s = min_s best_theta = theta return best_theta def execute_job(self, progress, iteration, backend, shots, circuits): """Send a job to the backend using IBMQ Job Manager""" # define IBMQManager instance manager = IBMQJobManager() # first run the generated circuits if progress: print("Transpiling circuits...") # get the job runner instance job_set = manager.run( circuits, backend=backend, name="Job_set " + str(iteration), shots=shots ) if progress: print("Transpilation Done!\nJob sent...") # send and get job job_result = job_set.results() if progress: print("Job has returned") # return result return job_result def get_eigen_pair( self, backend, theta_left=0, theta_right=1, progress=False, randomize=True, basis=None, basis_ind=None, target_cost=None, shots=512, ): """Finding the eigenstate pair for the unitary""" self.unitary_circuit = self.get_unitary_circuit(backend) if theta_left > theta_right: raise ValueError( "Left bound for theta should be smaller than the right bound" ) elif (theta_left < 0) or (theta_right > 1): raise ValueError("Bounds of theta are [0,1].") if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") results = dict() # first initialize the state phi if basis is None: self.basis = self.get_basis_vectors(randomize) else: self.basis = basis # choose a random index if basis_ind is None: ind = np.random.choice(self.dims) else: ind = basis_ind phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision precision = 1 / 10 ** self.error samples = self.resolution # initialization of range left, right = theta_left, theta_right # generate the angles angles = np.linspace(left, right, samples) # First execution can be done without JobManager also... circ = self.get_circuit(phi, backend=backend, shots=shots) job = execute(circ, backend=backend, shots=shots) counts = job.result().get_counts() if "0" in counts: p0 = counts["0"] else: p0 = 0 if "1" in counts: p1 = counts["1"] else: p1 = 0 # experimental probabilities p0, p1 = p0 / shots, p1 / shots # get initial angle estimate theta_max = self.get_optimal_angle(p0, p1, angles) # get intial cost circ = self.get_circuit(phi, backend=backend, shots=shots, angle=theta_max) job = execute(circ, backend=backend, shots=shots) counts = job.result().get_counts() if "0" in counts: cost = counts["0"] / shots else: cost = 0 # update best phi best_phi = phi # the range upto which theta extends iin each iteration angle_range = (right - left) / 2 # a parameter a = 1 # start algorithm iters = 0 found = True while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(theta_right, theta_max + angle_range / 2) left = max(theta_left, theta_max - angle_range / 2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters + 1, "...") # generate a cost dict for each of the iterations # final result lists costs, states = [], [] # circuit list circuits = [] # 1. Circuit generation loop for i in range((2 * self.dims)): # everyone is supplied with the same range of theta in one iteration # define z if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) states.append(curr_phi) # bundle the circuits together ... circuits.append( self.get_circuit(curr_phi, backend=backend, shots=shots) ) job_result = self.execute_job(progress, iters, backend, shots, circuits) # define lists again thetas, circuits = [], [] # 3. Classical work for i in range((2 * self.dims)): # we have that many circuits only counts = job_result.get_counts(i) # get the experimental counts for this state try: exp_p0 = counts["0"] except: exp_p0 = 0 try: exp_p1 = counts["1"] except: exp_p1 = 0 # normalize exp_p0 = exp_p0 / shots exp_p1 = exp_p1 / shots theta_val = self.get_optimal_angle(exp_p0, exp_p1, angles) # generate the circuit and append circuits.append( self.get_circuit( states[i], backend=backend, shots=shots, angle=theta_val ) ) thetas.append(theta_val) # again execute these circuits job_result = self.execute_job(progress, iters, backend, shots, circuits) # 5. Result generation loop for i in range((2 * self.dims)): # cost generation after execution ... counts = job_result.get_counts(i) if "0" in counts: curr_cost = counts["0"] / (shots) else: curr_cost = 0 if ( curr_cost > cost ): # then only add this cost in the cost and states list cost = curr_cost best_phi = states[i] theta_max = thetas[i] found = True if progress: stdout.write("\r") stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims))) stdout.flush() if found == False: # phi was not updated , change a a = a / 2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only print if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm..." ) break # add cost, eigenvector and theta to the dict results["cost"] = cost results["theta"] = theta_max results["state"] = best_phi return results class bundled_changed_SPEA: def __init__(self, unitary, resolution=100, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError("Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001" ) self.resolution = resolution # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix" ) # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2 ** (U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)" ) if error <= 0: raise ValueError("The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError("Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def get_basis_vectors(self, randomize=True): # get the d dimensional basis for the unitary provided if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def get_circuits(self, angles, state): """Given an initial state and a set of angles, return the circuits that are generated with those angles""" result = {"cost": -1, "theta": -1} # all theta values are iterated over for the same state phi = Initialize(state) shots = 512 circuits = [] for theta in angles: qc = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc = qc.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1))) # add hadamard qc.h(0) # add unitary which produces a phase kickback on control qubit qc = qc.compose( self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims))) ) # add the inv rotation qc.p(-2 * np.pi * theta, 0) # add hadamard qc.h(0) # measure qc.measure([0], [0]) # generate all the circuits... circuits.append(qc) return circuits def get_cost(self, angles, counts, shots): """Generate the best cost and theta pair for the particular state""" result = {"cost": -1, "theta": -1} # get the cost for this theta for k, theta in zip(counts, angles): # for all experiments you ran try: C_val = (k["0"]) / shots except: C_val = 0 if C_val > result["cost"]: # means this is a better theta value result["theta"] = theta result["cost"] = C_val return result def get_eigen_pair(self, backend, progress=False, randomize=True): """Finding the eigenstate pair for the unitary""" if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") results = dict() # first initialize the state phi self.basis = self.get_basis_vectors(randomize) # choose a random index ind = np.random.choice(self.dims) phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision precision = 1 / 10 ** self.error samples = self.resolution # initialization of range left, right = 0, 1 shots = 512 # generate the angles angles = np.linspace(left, right, samples) # First execution can be done without JobManager also... circs = self.get_circuits(angles, phi) job = execute(circs, backend=backend, shots=shots) counts = job.result().get_counts() result = self.get_cost(angles, counts, shots) # get initial estimates cost = result["cost"] theta_max = result["theta"] best_phi = phi # the range upto which theta extends iin each iteration angle_range = 0.5 # a parameter a = 1 # start algorithm iters = 0 found = True plus = (1 / np.sqrt(2)) * np.array([1, 1]) minus = (1 / np.sqrt(2)) * np.array([1, -1]) # define IBMQManager instance manager = IBMQJobManager() while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(1, theta_max + angle_range / 2) left = max(0, theta_max - angle_range / 2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters + 1, "...") # generate a cost dict for each of the iterations # final result lists thetas, costs, states = [], [], [] # circuit list circuits = [] # list to store intermediate states phis = [] # 1. Circuit generation loop for i in range((2 * self.dims)): # everyone is supplied with the same range of theta in one iteration # define z # make a list of the circuits if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) phis.append(curr_phi) # bundle the circuits together ... circs = self.get_circuits(angles, curr_phi) circuits = circuits + circs # now each iteration would see the same state as the best phi # is updated once at the end of the iteration # also, the cost is also updated only once at the end of the iteration # 2. run the generated circuits if progress: print("Transpiling circuits...") circuits = transpile(circuits=circuits, backend=backend) job_set = manager.run( circuits, backend=backend, name="Job_set" + str(iters), shots=shots ) if progress: print("Transpilation Done!\nJob sent...") job_result = job_set.results() # now get the circuits in chunks of resolution each if progress: print("Job has returned") # 3. Result generation loop for i in range((2 * self.dims)): # get the results of this basis state # it will have resolution number of circuits... counts = [] for j in range(i * self.resolution, (i + 1) * self.resolution): # in this you'll get the counts counts.append(job_result.get_counts(j)) result = self.get_cost(counts, angles, shots) # get the estimates for this basis curr_theta = result["theta"] curr_cost = result["cost"] curr_phi = phis[i] # the result was generated pertaining to this phi if ( curr_cost > cost ): # then only add this cost in the cost and states list thetas.append(float(curr_theta)) costs.append(float(curr_cost)) states.append(curr_phi) found = True if progress: stdout.write("\r") stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims))) stdout.flush() if found == False: # phi was not updated , change a a = a / 2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only update # O(n) , would update this though index = np.argmax(costs) # update the parameters of the model cost = costs[index] theta_max = thetas[index] best_phi = states[index] if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm..." ) break # add cost, eigenvector and theta to the dict results["cost"] = cost results["theta"] = theta_max results["state"] = best_phi return results