repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit from qiskit import execute, Aer import numpy as np import matplotlib.pyplot as plt from IPython.display import display from qiskit.tools.monitor import job_monitor from qiskit.extensions import UnitaryGate from qiskit.circuit import Gate class IQPE: """Implements the iterative QPE algorithm upto n bit precision specified by user Attributes: precision : int([1,...]): precision of the phase estimation ( also equal to number of qubits in scratch register) unitary(np.ndarray or QuantumCircuit or UnitaryGate): unitary operator for which QPE is being applied. unknown(bool) : a boolean variable used to specify whether exponentiation of unitary needs to be done or not (True : no exponentiation done) powers(dict): contains the powers of the unitary matrix key : exponent, value : U^(exponent) controls(dict): contains equivalent controlled U gates to be applied key : iteration number, value : controlled U gate Methods : get_powers(unitary,n) : generates powers of U from U^1 -> U^(2^(n-1)) and stores power in dict get_controls() : generates the U^(2^j) control gates for faster simulation of the QPE algorithm """ def __init__(self, precision, unitary, unknown=False): # write docs """ Args : precision(int) : The precision upto which the phase needs to be estimated. Interpreted as 2^(-precision). eg. precision = 4 means the phase is going to be precise upto 2^(-4). unitary(np.ndarray or UnitaryGate or QuantumCircuit): The unitary for which we want to determine the phase. Currently this class supports 2 x 2 matrices or single qubit gates. Shall be extended for higher order matrices. unknown(bool) : Whether exponentiation is to be done or not Raises : TypeError : if precision or unitary are not of a valid type ValueError : if precision is not valid Exception : if unitary is of larger size than 2 x 2 Examples : from iter_QPE import IQPE # passing as ndarray theta = 1/5 U1 = np.ndarray([[1,0], [0, np.exp(2*np.pi*1j*(theta))]]) qpe1 = IQPE(precision = 4, unitary = U1,unknown = True) # passing as QuantumCircuit U2 = QuantumCircuit(1) U2.rz(np.pi/7,0) qpe2 = IQPE(precision = 5,unitary = U2,unknown = True) """ # handle precision if type(precision) != int: raise TypeError("Precision needs to be an integer") elif precision < 0 or precision == 0: raise ValueError("Precision needs to be atleast 1") self.precision = precision # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) and not isinstance(unitary, Gate) ): raise TypeError( "A numpy array, Quantum Circuit or Gate needs to be passed as the unitary matrix" ) if unknown == False: # means matrix rep needed if not isinstance(unitary, np.ndarray) and not isinstance( unitary, UnitaryGate ): raise TypeError( """Unitary needs to be of type ndarray or Unitary Gate if optimization needs to be done""" ) if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: U = unitary # already an array else: # if it is numpy type array if isinstance(unitary, np.ndarray): U = UnitaryGate(data=unitary) else: U = unitary # here we can directly use the .control method in our circuit. # the unitary is an ndarray if unknown is False and # the unitary is not ndarray is unknown is true self.unitary = U self.unknown = unknown self.powers = {} # optimization can only be performed when we know the # matrix representation if unknown == False: self.controls = self.get_controls() def get_powers(self, unitary, n): """This function returns the matrix U^(n) and saves other smaller powers Arguments: unitary(np.ndarray): The Unitary matrix which needs to be exponentitated n(int): integer specifying the exponent Raises: ValueError : when n is < 0 Returns: a dictionary containing the relevant powers of the matrix U""" if n < 0: raise ValueError("Power should be atleast 0") if n == 1: self.powers[1] = unitary return unitary if n % 2 == 1: if n - 1 not in self.powers: self.powers[n - 1] = self.get_powers(unitary, n - 1) self.powers[n] = unitary @ self.powers[n - 1] return self.powers[n] else: if n / 2 not in self.powers: self.powers[n / 2] = self.get_powers(unitary, n / 2) self.powers[n] = self.powers[n / 2] @ self.powers[n / 2] return self.powers[n] # get the controls, if using optimization def get_controls(self): """Get the control gates for the circuit While computing exponent, we also compute the smaller powers Returns: controls(dict) : dictionary containing the relevant controlled unitary gates key : iteration number, value : controlled U gate """ n_iters = self.precision exp = 2 ** (n_iters - 1) self.get_powers(self.unitary, exp) # got the powers controls = {} # note that iteration 0 has the highest powered matrix and # then it goes on to get lesser and lesser iterations = self.precision for it in range(iterations): mat = self.powers[exp] u_gate = UnitaryGate(data=mat) cu = u_gate.control(num_ctrl_qubits=1, label="CU", ctrl_state="1") controls[it] = cu exp /= 2 return controls def get_circuit_phase( self, QC, clbits, qubits, ancilla, show=False, backend=None, save_circ=False, circ_name="IQPE_circ.JPG", ): # QC must be atleast size 2 """Add the experiments pararmeters .., and the shots parameter""" """ Returns the circuit phase as a 2-tuple phase : (binary phase,decimal phase) Arguments: QC(QuantumCircuit) : the circuit containing the eigenvector of the unitary matrix clbits(list-like) : the list of the classical bits in which the phase would be saved qubits(list-like) : the indices of the qubits containing the eigenvector of unitary ancilla(int) : the ancilliary qubit which would be used as the control qubit show(bool) : boolean to specify if circuit should be drawn or not save(bool) : boolean to specify if circuit should be saved or not (saved as IQPE_circuit.JPG, if true) backend(IBMQBackend) : backend for running the circuit NOTE : IBMQ provider must be enabled for execution of circuits on real backends Raises: ValueError : if clbits are not equal to precision or non-unique bits specified or if elements of clbits/qubits are not integer type or ancilla qubit is same as one of the eigenvector qubits TypeError : if qubit indices are not integral Exception : if unitary has less than 2 qubits Returns : A 2-tuple specifying the phase of unitary matrix : (binary phase,decimal phase) Usage Notes : NOTE : The phase is assumed to be a binary fraction as 0.x1x2x2...xn where n is the precision specified by the user. The least significant bit , xn, is saved in the qubit with index precision-1 and the most significant bit, x1, is saved in the qubit with index 0 in the phase[0] of tuple. For example :- theta = 1/5 # binary representation upto 4 bits : 0.0011 unitary = np.ndarray([[1,0], [0, np.exp(2*np.pi*1j*(theta))]]) q = QuantumCircuit(6,4) q.x(4) # the eigenvector qubit qpe = get_circuit_phase(precision = 4,unitary = unitary,unknown = True) athens = provider.get_backend('ibmq_athens') phase = iqpe.get_circuit_phase( QC=q, clbits=[0, 1, 2, 3], qubits=[4], ancilla=3, show=True,backend = athens) # phase[0] would contain a 4-bit phase representation # phase[1] would contain the decimal representation of the phase """ # handle qubits in circuit if len(QC.qubits) < 2: raise Exception("Quantum Circuit needs to have atleast size 2") # handle classical bits if len(clbits) != self.precision: raise ValueError( "Exactly", self.precision, "classical bits needed for measurement" ) elif len(set(clbits)) != len(clbits): raise ValueError("Non-unique classical bits given for measurement") elif not all(isinstance(i, int) for i in clbits): raise ValueError("All classical indices must be integer type") # qubit and ancilla need to be integers if type(ancilla) is not int: raise TypeError("Ancilla indix need to be specified as integer") elif not all(isinstance(i, int) for i in qubits): raise TypeError( "The indices containing the eigenvector must be integer type " ) elif len(set(qubits)) != len(qubits): raise ValueError("Non-unique qubits given for the eigenvector") elif ancilla in qubits: raise Exception("Ancilla can not be equal to a qubit index ") res = [] # start with the iteration phase = -2 * np.pi factor = 0 iterations = self.precision # generate the qubit list on which the Unitary is applied qargs = [ancilla] for q in qubits: qargs.append(q) if self.unknown == True: # no matrix repr is available -> means .control method can be applied easily exponent = 2 ** (iterations - 1) CU = self.unitary.control(num_ctrl_qubits=1, label="CU", ctrl_state=1) for it in range(iterations): # start QC.reset(ancilla) QC.h(ancilla) # add the inverse rotation inv_phase = phase * factor QC.p(inv_phase, ancilla) # add the controlled Unitary of iteration it if self.unknown == False: QC = QC.compose(self.controls[it], qubits=qargs) else: # need to add exponential amount of matrices for _ in range(int(exponent)): QC = QC.compose(CU, qubits=qargs) exponent /= 2 # add H gate QC.h(ancilla) QC.measure(ancilla, clbits[it]) # or, iterate in reverse manner , no of steps -> # clbits[it] as it is the absolute # classical register index if backend == None: # simulating counts = ( execute(QC, backend=Aer.get_backend("qasm_simulator"), shots=1) .result() .get_counts() ) else: job = execute( QC, shots=1, backend=backend, job_name="Iter " + str(it + 1), optimization_level=3, ) display(job_monitor(job)) counts = job.result().get_counts() # we will have only one single key in the dict key = list(counts.keys())[0][::-1] # try adding x based on clasical curr_bit = key[clbits[it]] res.append(int(curr_bit)) # if bit measured is 1 if curr_bit == "1": factor += 1 / 2 # add the phase factor factor = factor / 2 # shift each towards one weight right if it + 1 == iterations: if show == True: if save_circ == False: display(QC.draw("mpl")) else: display(QC.draw(output="mpl", filename=circ_name, scale=0.8)) # phase has now been stored in the clbits # returning its binary representation # need to reverse as LSB is stored at the zeroth index and # not the last res = res[::-1] # find decimal phase dec = 0 weight = 1 / 2 for k in res: dec += (weight) * k weight /= 2 return (res, dec) def get_estimate_plot_phase( theta=None, unitary=None, unknown=True, experiments=1, iters=9, show_circ=False, save=False, backend=None, ): """ Displays an estimate plot of the phase that is found through the IQPE algorithm for SINGLE qubit phase unitaries theta(float) : contains the actual theta (if some theoretical assumption is known) unitary(ndarray / QuantumCircuit / UnitaryGate) : the unitary for which phase needs to be determined unknown(bool) : boolean variable to specify whether the optimization in unitary application is to be used experiments(int) : the number of experiments for which each iteration is to be run iters(int) : the max number of iterations to be run ( circuit is run from precision 2 -> iters) show_circ(bool) : boolean variable to specify whether circuit needs to be drawn or not save(bool) : boolean variable specifying whether plot needs to be saved or not (saved as IQPE Plots/Estimate_plot_theta.jpg) backend(IBMBackend) : ibmq backend on which the circuit should be run (if None, qasm_simulator is used) Example :- provider = IBMQ.get_provider('ibm-q') casb = provider.get_backend('ibmq-casablanca) U = np.array([[1,0], [0, np.exp(2*np.pi*1j(0.524))]]) get_estimate_plot(unitary = U, iters = 10,unknown= True, save=True,backend = casb) """ import os if theta is None and unitary is None: raise Exception("Atleast one of theta or unitary is needed.") if theta > 1 or theta < 0: raise ValueError("Theta must be specified as a float val between 0 and 1") if unitary is None: unitary = np.array([[1, 0], [0, np.exp(2 * np.pi * 1j * (theta))]]) estimates, errors = [], [] avg_phase, avg_error = {}, {} for prec in range(2, iters): print("\n\nITERATION NUMBER", prec - 1, "...\n\n") iqpe = IQPE(precision=prec, unitary=unitary, unknown=unknown) dec_phase, abs_errors = [], [] for exp in range(experiments): # single qubit rotation matrices q = QuantumCircuit(2, prec) q.x(1) # simulate the matrix on a circuit phase = iqpe.get_circuit_phase( QC=q, clbits=[i for i in range(prec)], qubits=[1], ancilla=0, show=show_circ, backend=backend, ) # add the phase and the error ... dec_phase.append(phase[1]) print("Binary Phase in experiment", exp, phase[0]) if theta is not None: ae = np.round(abs(phase[1] - theta), 5) abs_errors.append(ae) # run experiments number of times AND get the avg phase avg_phase[prec] = sum(dec_phase) / len(dec_phase) avg_error[prec] = sum(abs_errors) / len(abs_errors) print("Decimal Phase :", avg_phase[prec]) print("Absolute Error :", avg_error[prec]) if theta is not None: print("Percentage error :", avg_error[prec] * 100 / theta, "%") # append to graph estimates.append(avg_phase[prec]) errors.append(avg_error[prec]) # choose color colors = ["r", "g", "c", "m", "y"] c1 = np.random.choice(colors)[0] c2 = np.random.choice(colors)[0] while c2 == c1: c2 = np.random.choice(colors)[0] plt.figure(figsize=(9, 7)) plt.grid(True) # plot plt.plot( [i for i in range(2, iters)], estimates, alpha=0.6, marker="o", color=c1, label="Estimates", linestyle="dashed", linewidth=2, ) plt.plot( [i for i in range(2, iters)], errors, alpha=0.6, marker="s", color=c2, label="Absoulte error", linestyle="dotted", linewidth=2, ) if theta != None: plt.plot([0, iters], [theta, theta], color="black", label="Actual phase") plt.title("IQPE estimates for $\\theta =" + str(theta) + "$", fontsize=16) plt.xlabel("Number of iterations ", fontsize=14) plt.ylabel("Estimates by IQPE", fontsize=14) plt.legend() if save: os.makedirs("IQPE Plots", exist_ok=True) plt.savefig("IQPE Plots/Estimate_plot_" + str(theta) + ".jpg", dpi=200)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram from qiskit.extensions import UnitaryGate import numpy as np from IPython.display import display class KQPE: """ Implements the Kitaev's phase estimation algorithm where a single circuit is used to estimate the phase of a unitary but the measurements are exponential. Attributes : precision : (int)the precision upto which the phase needs to be estimated NOTE : precision is estimated as 2^(-precision) unitary (np.ndarray or QuantumCircuit or UnitaryGate) : the unitary matrix for which we want to find the phase, given its eigenvector qubits (int) : the number of qubits on which the unitary matrix acts Methods : get_phase(QC,ancilla,clbits,backend, show) : generate the resultant phase associated with the given Unitary and the given eigenvector get_circuit(show,save_circ, circ_name ) : generate a Kitaev phase estimation circuit which can be attached to the parent quantum circuit containing eigenvector of the unitary matrix """ def __init__(self, unitary, precision=10): """ Args : precision(int) : The precision upto which the phase is estimated. Interpreted as 2^(-precision). eg. precision = 4 means the phase is going to be precise upto 2^(-4). unitary(np.ndarray or UnitaryGate or QuantumCircuit): The unitary for which we want to determine the phase. Raises : TypeError : if precision or unitary are not of a valid type ValueError : if precision is not valid Examples : # passing as array theta = 1/6 U1 = np.ndarray([[1,0], [0, np.exp(2*np.pi*1j*(theta))]]) kqpe1 = KQPE(precision = 8, unitary = U1) # passing as QuantumCircuit U2 = QuantumCircuit(1) U2.rz(np.pi/7,0) kqpe2 = KQPE(precision = 8,unitary = U2) """ # handle precision if not isinstance(precision, int): raise TypeError("Precision needs to be an integer") elif precision <= 0: raise ValueError("Precision needs to be >=0") self.precision = 1 / (2 ** precision) # handle unitary if unitary is None: raise Exception( "Unitary needs to be specified for the Kitaev QPE algorithm" ) elif ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array, QuantumCircuit or UnitaryGate needs to be passed as the unitary matrix" ) self.unitary = unitary # get the number of qubits in the unitary if isinstance(unitary, np.ndarray): self.qubits = int(np.log2(unitary.shape[0])) else: self.qubits = int(unitary.num_qubits) def get_phase(self, QC, ancilla, clbits, backend, show=False): """This function is used to determine the final measured phase from the circuit with the specified precision. Args : QC (QuantumCircuit) : the quantum circuit on which we have attached the kitaev's estimation circuit. Must contain atleast 2 classical bits for correct running of the algorithm ancilla(list-like) : the ancilla qubits to be used in the kitaev phase estimation clbits(list-like) : the classical bits in which the measurement results of the given ancilla qubits is stored backend(ibmq_backend or 'qasm_simulator') : the backend on which the circuit is executed on show(bool) : boolean to specify whether the progress and the circuit need to be shown Raises : Exception : If a QuantumCircuit with less than 2 classical bits or less than 3 qubits is passed, if the ancilla or the clbits are not unique, if more than 2 of classical or ancilla bits are provided Returns : phase(tuple) : (phase_dec, phase_binary) : A 2-tuple representing the calculated phase in decimal and binary upto the given precision NOTE : for details of the math please refer to section2A of https://arxiv.org/pdf/1910.11696.pdf. Examples : 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") # defining parent quantum circuit q = QuantumCircuit(5, 6) #eigenvector of unitary q.x(3) #kitaev circuit is attached on the eigenvector and # two additional ancilla qubits q.append(kq_circ, qargs=[1, 2, 3]) q.draw('mpl') # result phase = kqpe.get_phase(backend=Aer.get_backend( 'qasm_simulator'), QC=q, ancilla=[1, 2], clbits=[0, 1], show=True) """ # handle circuit if not isinstance(QC, QuantumCircuit): raise TypeError( "A QuantumCircuit must be provided for generating the phase" ) if len(QC.clbits) < 2: raise Exception("Atleast 2 classical bits needed for measurement") elif len(QC.qubits) < 3: raise Exception("Quantum Circuit needs to have atleast 3 qubits") # handle bits elif len(ancilla) != 2 or ancilla is None: raise Exception("Exactly two ancilla bits need to be specified") elif len(clbits) != 2 or clbits is None: raise Exception( "Exactly two classical bits need to be specified for measurement" ) elif len(set(clbits)) != len(clbits) or len(set(ancilla)) != len(ancilla): raise Exception("Duplicate bits provided in lists") # find number of shots -> atleast Big-O(1/precision shots) shots = 10 * int(1 / self.precision) if show == True: print("Shots :", shots) # measure into the given bits QC.measure([ancilla[0], ancilla[1]], [clbits[0], clbits[1]]) if show == True: display(QC.draw("mpl")) # execute the circuit result = execute( QC, backend=backend, shots=shots, optimization_level=3 ).result() counts = result.get_counts() if show: print("Measurement results :", counts) if show: display(plot_histogram(counts)) # now get the results C0, C1, S0, S1 = 0, 0, 0, 0 first = clbits[0] second = clbits[1] for i, j in zip(list(counts.keys()), list(counts.values())): # get bits l = len(i) one = i[l - first - 1] two = i[l - second - 1] # First qubit 0 - C (0,theta) if one == "0": C0 += j # First qubit 1 - C (1,theta) else: C1 += j # Second qubit 0 - S (0,theta) if two == "0": S0 += j # Second qubit 1 - S (1,theta) else: S1 += j # normalize C0, C1, S0, S1 = C0 / shots, C1 / shots, S0 / shots, S1 / shots # determine theta_0 tan_1 = np.arctan2([(1 - 2 * S0)], [(2 * C0 - 1)])[0] theta_0 = (1 / (2 * np.pi)) * tan_1 # determine theta_1 tan_2 = np.arctan2([(2 * S1 - 1)], [(1 - 2 * C1)])[0] theta_1 = (1 / (2 * np.pi)) * tan_2 phase_dec = np.average([theta_0, theta_1]) phase_binary = [] phase = phase_dec # generate the binary representation for i in range(int(np.log2((1 / self.precision)))): phase *= 2 if phase < 1: phase_binary.append(0) else: phase -= 1 phase_binary.append(1) return (phase_dec, phase_binary) def get_circuit(self, show=False, save_circ=False, circ_name="KQPE_circ.JPG"): """Returns a kitaev phase estimation circuit with the unitary provided Args: show(bool) : whether to draw the circuit or not Default - False save_circ(bool) : whether to save the circuit in an image or not. Default - False circ_name(str) : filename with which the circuit is stored. Default - KQPE_circ.JPG Returns : A QuantumCircuit with the controlled unitary matrix and relevant gates attached to the circuit. Size of the circuit is (2 + the number of qubits in unitary) Examples: theta = 1/5 unitary = UnitaryGate(np.ndarray([[1,0], [0, np.exp(2*np.pi*1j*(theta))]])) kqpe = KQPE(unitary,precision = 10) kq_circ = kqpe.get_circuit(show = True,save_circ = True, circ_name= "KQPE_circ_1qubit.JPG") # attaching the circuit q = QuantumCircuit(5, 6) q.x(3) q.append(kq_circ, qargs=[1, 2, 3]) q.draw('mpl') """ qc = QuantumCircuit(2 + self.qubits, name="KQPE") qubits = [i for i in range(2, 2 + self.qubits)] # make the unitary if isinstance(self.unitary, np.ndarray): U = UnitaryGate(data=self.unitary) C_U = U.control(num_ctrl_qubits=1, label="CU", ctrl_state="1") else: C_U = self.unitary.control(num_ctrl_qubits=1, label="CU", ctrl_state="1") # qubit 0 is for the H estimation qc.h(0) qc = qc.compose(C_U, qubits=[0] + qubits) qc.h(0) qc.barrier() # qubit 1 is for the H + S estimation qc.h(1) qc.s(1) qc = qc.compose(C_U, qubits=[1] + qubits) qc.h(1) qc.barrier() if show == True: if save_circ: display(qc.draw("mpl", filename=circ_name)) else: display(qc.draw("mpl")) return qc
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate,Initialize from qiskit.tools.visualization import plot_histogram from qiskit.compiler import assemble import numpy as np from time import sleep from qiskit.tools.monitor import job_monitor from qiskit.extensions import UnitaryGate from qiskit.quantum_info import Statevector import sys from scipy.stats import unitary_group import matplotlib.pyplot as plt class SPEA(): ''' This is a class which implements the Statistical Phase Estimation algorithm 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 for the unitary matrix ''' def __init__(self, unitary, resolution=50, 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() # RANDOMNESS 1 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() # RANDOMNESS 2 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]) 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) # RANDOMNESS 3 # 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 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 = 1 - c0 # 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* # RANDOMNESS 4 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 get_eigen_pair(self, backend, algo='alternate', theta_left = 0,theta_right = 1,progress=False, randomize=True, target_cost=None, basis = None, basis_ind = 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 ''' # handle algorithm... 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(algo, str): raise TypeError( "Algorithm must be mentioned as a string from the values {alternate,standard}") elif algo not in ['alternate', 'standard']: raise ValueError( "Algorithm must be specified as 'alternate' or 'standard' ") 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") 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") 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 = min(1,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, "...") 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'] # at this point I have the best Cost for the state PHI and the if curr_cost > cost: theta_max = float(curr_theta) cost = min(1.0,float(curr_cost)) best_phi = curr_phi found = True if progress: sys.stdout.write('\r') sys.stdout.write("%f %%completed" % (100*(i+1)/(2*self.dims))) sys.stdout.flush() # iteration completes if found == False: # phi was not updated , change a a = a/2 if progress: print("\nNo change, updating a...") else: angle_range /= 2 # updated phi and thus theta too -> refine theta range 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 the warning that iters maxed out # 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.providers.ibmq.managed import IBMQJobManager from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-education') from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate, Initialize from qiskit.quantum_info import Statevector from qiskit.compiler import assemble 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("..") from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline from Modules.changed_SPEA import bundled_SPEA_alternate q = QuantumCircuit(2) q.cp(2*np.pi*(1/4), 0, 1) q.draw('mpl') spe = bundled_SPEA_alternate(q, resolution=30, error=3, max_iters=10) jakarta = provider.get_backend('ibmq_jakarta') bogota = provider.get_backend('ibmq_bogota') thetas = [] for k in range(5): result = spe.get_eigen_pair( backend=jakarta, progress=True, randomize=True) print("Result is :", result) thetas.append(result['theta']) thetas plt.title("Plot for returned Eigenvalues", fontsize=16) plt.xlabel("Experiment number") plt.ylabel("Eigenvalues") plt.plot([0, 6], [0, 0], color='black') plt.plot([0, 6], [1, 1], color='black') plt.plot([0, 6], [0.25, 0.25], color='black') plt.plot(list(range(5)), thetas, label='Estimates', color='cyan', linewidth=2, marker='s') plt.legend() plt.grid()
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit.providers.ibmq.managed import IBMQJobManager from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-education') 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("..") from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline from Modules.changed_SPEA import bundled_changed_SPEA q = QuantumCircuit(2) q.cp(2*np.pi*(1/9),0,1) q.draw('mpl') spe = bundled_changed_SPEA(q,resolution=20,error = 3,max_iters=10) jakarta = provider.get_backend('ibmq_jakarta') thetas = [] for k in range(5): result = spe.get_eigen_pair(backend=jakarta,progress=True) print("Result is :",result) thetas.append(result['theta']) thetas plt.title("Plot for returned Eigenvalues",fontsize = 16) plt.xlabel("Experiment number") plt.ylabel("Eigenvalues") plt.plot([0,6],[0,0],color = 'black') plt.plot([0,6],[1,1],color = 'black') plt.plot([0,6],[0.111,0.111],color = 'black') plt.plot(list(range(5)), thetas, label = 'Estimates', color = 'cyan', linewidth = 2, marker = 's') plt.legend() plt.grid()
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("..") from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline from Modules.normal_SPEA import SPEA from Modules.changed_SPEA import global_max_SPEA def generate_random_estimation(unitaries,SPE_type,resolution = 40,save = True): backend = Aer.get_backend('qasm_simulator') best_costs, errors_in_phases = [] , [] for i,u_rand in enumerate(unitaries): print("FOR UNITARY ",i+1) # generate the phases and vectors eigen_phases, eigen_vectors = np.linalg.eig(u_rand) eigen_phases = np.angle(eigen_phases) ep = [] # doing this as phase maybe be negative for k in eigen_phases: if k < 0: ep.append((k + 2*np.pi)/(2*np.pi)) else: ep.append(k/(2*np.pi)) eigen_phases = ep ev1 , ev2 = eigen_vectors[0] , eigen_vectors[1] ev1 = ev1 / np.linalg.norm(ev1) ev2 = ev2 / np.linalg.norm(ev2) # generate their corresponding init statevectors sv1 = Initialize(ev1) sv2 = Initialize(ev2) print("Eigenvectors",ev1,ev2) print("Eigenphases",eigen_phases) # run the algorithm if SPE_type == 'original': spea = SPEA(resolution = resolution, max_iters = 10, unitary = u_rand,error = 4) else: spea = global_max_SPEA(resolution = resolution, max_iters = 10, unitary = u_rand,error = 4) result = spea.get_eigen_pair(backend = backend, progress = False, randomize = True) # get the results res_state = result['state'] res_theta = result['theta'] sv_res = Initialize(res_state) print("Result",result) print("Phase returned :",res_theta) # get the dot products d1 = np.linalg.norm(np.dot(ev1, res_state.conjugate().T))**2 d2 = np.linalg.norm(np.dot(ev2, res_state.conjugate().T))**2 # make a bloch sphere qc = QuantumCircuit(2) qc = qc.compose(sv_res,qubits = [0]) if d1 > d2: print("Best overlap :",d1) # it is closer to the first qc = qc.compose(sv1,qubits = [1]) best_costs.append(result['cost']) errors_in_phases.append(abs(res_theta - eigen_phases[0])) else: # it is closer to the second print("Best overlap :",d2) qc = qc.compose(sv2,qubits = [1]) best_costs.append(result['cost']) errors_in_phases.append(abs(res_theta - eigen_phases[1])) print("Bloch Sphere for the states...") s = Statevector.from_instruction(qc) display(plot_bloch_multivector(s)) if SPE_type == 'original': plt.title("Experiments over Random Matrices for original SPEA",fontsize= 16) else: plt.title("Experiments over Random Matrices for modified SPEA",fontsize= 16) plt.xlabel("Experiment Number") plt.ylabel("Metric value") plt.plot([i for i in range(len(unitaries))], best_costs, label = 'Best Costs', alpha = 0.5, color = 'r',marker='o',linewidth = 2) plt.plot([i for i in range(len(unitaries))], errors_in_phases, label = 'Corresponding Error in Phase',linewidth = 2, alpha = 0.5, color = 'b',marker='s') plt.legend() plt.grid() if save: if SPE_type == 'original': plt.savefig("Random Estimation for Original SPE.jpg",dpi = 200) else: plt.savefig("Random Estimation for Modified SPE.jpg",dpi = 200) unitaries = [] for i in range(6): u = unitary_group.rvs(2) unitaries.append(u) print("Unitaries :",unitaries) generate_random_estimation(unitaries,'original',resolution=15) generate_random_estimation(unitaries,'modified',resolution=15)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, Aer from qiskit.extensions import UnitaryGate,Initialize from qiskit.quantum_info import Statevector from qiskit.tools.visualization import plot_bloch_multivector import numpy as np import sys from scipy.stats import unitary_group import matplotlib.pyplot as plt from qiskit import IBMQ %matplotlib inline sys.path.append("..") from Modules.changed_SPEA import global_max_SPEA # IBMQ.load_account() # provider = IBMQ.get_provider(hub='??replace_with_your_hub_name??') sim = Aer.get_backend('qasm_simulator') U1 = UnitaryGate(data=np.array([[0,1], [1,0]])) spe = global_max_SPEA(U1,resolution= 30,error = 4,max_iters=12) result = spe.get_eigen_pair(progress = False,backend=sim) result t = [] for resolution in range(10,50,5): spe = global_max_SPEA(U1,resolution= resolution,error = 4,max_iters=10) res = spe.get_eigen_pair(backend = sim) theta = res['theta'] t.append(theta) plt.figure(figsize = (8,9)) plt.title("Eigenphase estimation for X gate, modified algo",fontsize = 15) plt.grid() plt.plot(list(range(10,50,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7) plt.plot([10,50],[0.5,0.5],color='black',label = "True") plt.plot([10,50],[0,0],color='black') plt.plot([10,50],[1,1],color='black') plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Estimates") plt.savefig("Plots/SPE_PLOT1_global_max.jpg",dpi = 200) u2 = UnitaryGate(data=np.array([[1,0], [0, np.exp(2*np.pi*1j*(1/5))]])) t = [] for resolution in range(10,50,5): spe = global_max_SPEA(u2,resolution= resolution,error = 4,max_iters=10) res = spe.get_eigen_pair(backend = sim) theta = res['theta'] t.append(theta) plt.figure(figsize = (9,9)) plt.title("Eigenphase estimation for theta = 1/5, 0, 1, modified algo",fontsize = 15) plt.grid() plt.plot(list(range(10,50,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7) plt.plot([10,50],[0.2,0.2],color='black',label = "True") plt.plot([10,50],[0,0],color='black') plt.plot([10,50],[1,1],color='black') plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Estimates") plt.savefig("Plots/SPE_PLOT2_global_max.jpg",dpi = 200) unitary_group.rvs() u_rand = unitary_group.rvs(2) print("Random Unitary :",u_rand) eigen_phases, eigen_vectors = np.linalg.eig(u_rand) print("Eigen states of Unitary :",eigen_vectors) eigen_phases = np.angle(eigen_phases) ep = [] for k in eigen_phases: if k < 0: ep.append(k + 2*np.pi) else: ep.append(k) eigen_phases = ep print("Eigen phases of unitary :",eigen_phases) ev1 , ev2 = eigen_vectors[0] , eigen_vectors[1] ev1 = ev1 / np.linalg.norm(ev1) ev2 = ev2 / np.linalg.norm(ev2) qc1 = QuantumCircuit(1) qc2 = QuantumCircuit(1) sv1 = Initialize(ev1) sv2 = Initialize(ev2) qc1 = qc1.compose(sv1,qubits = [0]) qc2 = qc2.compose(sv2,qubits = [0]) qc1.draw('mpl') sv = Statevector.from_instruction(qc1) plot_bloch_multivector(sv) sv = Statevector.from_instruction(qc2) plot_bloch_multivector(sv) spea = global_max_SPEA(resolution = 50, max_iters = 10, unitary = u_rand,error = 4) result = spea.get_eigen_pair(progress = False, randomize = True) print("Result of our estimation :",result) res_state = result['state'] res_state = res_state/ np.linalg.norm(res_state) qc_res = QuantumCircuit(1) sv_init = Initialize(res_state) qc_res = qc_res.compose(sv_init, qubits = [0]) qc_res.draw('mpl') statevector_res = Statevector.from_instruction(qc_res) plot_bloch_multivector(statevector_res) def generate_random_estimation(experiments=5,resolution = 40): sim = Aer.get_backend('qasm_simulator') best_costs, errors_in_phases = [] , [] for exp in range(experiments): u_rand = unitary_group.rvs(2) # generate the phases and vectors eigen_phases, eigen_vectors = np.linalg.eig(u_rand) eigen_phases = np.angle(eigen_phases) ep = [] # doing this as phase maybe be negative for k in eigen_phases: if k < 0: ep.append((k + 2*np.pi)/(2*np.pi)) else: ep.append(k/(2*np.pi)) eigen_phases = ep ev1 , ev2 = eigen_vectors[0] , eigen_vectors[1] ev1 = ev1 / np.linalg.norm(ev1) ev2 = ev2 / np.linalg.norm(ev2) # generate their corresponding init statevectors sv1 = Initialize(ev1) sv2 = Initialize(ev2) print("Eigenvectors",ev1,ev2) print("Eigenphases",eigen_phases) # run the algorithm spea = global_max_SPEA(resolution = resolution, max_iters = 10, unitary = u_rand,error = 4) result = spea.get_eigen_pair(backend = sim, progress = False, randomize = True) # get the results res_state = result['state'] res_theta = result['theta'] sv_res = Initialize(res_state) print("Result",result) print("Phase returned(0-> 2*pi) :",res_theta) # get the dot products d1 = np.linalg.norm(np.dot(ev1, res_state.conjugate().T))**2 d2 = np.linalg.norm(np.dot(ev2, res_state.conjugate().T))**2 # make a bloch sphere qc = QuantumCircuit(2) qc = qc.compose(sv_res,qubits = [0]) if d1 > d2: print(" Best overlap :",d1) # it is closer to the first qc = qc.compose(sv1,qubits = [1]) best_costs.append(result['cost']) errors_in_phases.append(abs(res_theta - eigen_phases[0])) else: # it is closer to the second print(" Best overlap :",d2) qc = qc.compose(sv2,qubits = [1]) best_costs.append(result['cost']) errors_in_phases.append(abs(res_theta - eigen_phases[1])) print("Bloch Sphere for the states...") s = Statevector.from_instruction(qc) display(plot_bloch_multivector(s)) plt.title("Experiments for Random Matrices",fontsize= 16) plt.xlabel("Experiment Number") plt.ylabel("Metric value") plt.plot([i for i in range(experiments)], best_costs, label = 'Best Costs', alpha = 0.5, color = 'g',marker='o') plt.plot([i for i in range(experiments)], errors_in_phases, label = 'Corresponding Error in Phase', alpha = 0.5, color = 'b',marker='s') plt.legend() plt.grid() return generate_random_estimation()
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate import numpy as np import os from qiskit.extensions import UnitaryGate import sys import matplotlib.pyplot as plt %matplotlib inline os.makedirs(name = 'Plots',exist_ok=True) sys.path.append("..") from Modules.normal_SPEA import SPEA # uncomment & RUN to use actual backends # from qiskit import IBMQ # IBMQ.load_account() # provider = IBMQ.get_provider(hub='??your_provider??') # santiago = provider.get_backend('ibmq_santiago') # casablanca = provider.get_backend('ibmq_casablanca') sim = Aer.get_backend('qasm_simulator') U1 = QuantumCircuit(1) U1.x(0) U1.draw('mpl') spe = SPEA(U1,resolution= 10,error = 4,max_iters=12) result = spe.get_eigen_pair(progress = False,algo = 'alternate',backend = Aer.get_backend('qasm_simulator')) result # original theta = 0.2 t = [] for resolution in range(10,50,5): spe = SPEA(U1,resolution= resolution,max_iters=10) res = spe.get_eigen_pair(backend = sim,algo = 'alternate',target_cost = 0.9) theta = res['theta'] t.append(theta) plt.figure(dpi = 100,figsize=(8,6)) plt.title("Eigenphase estimation for X gate",fontsize = 15) plt.grid() plt.plot(list(range(10,50,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7) plt.plot([10,50],[0.5,0.5],color='black',label = "True") plt.plot([10,50],[0,0],color='black') plt.plot([10,50],[1,1],color='black') plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Estimates") plt.savefig("Plots/SPE_PLOT1.jpg",dpi = 200) u2 = UnitaryGate(data=np.array([[1,0], [0, np.exp(2*np.pi*1j*(1/5))]])) # original theta = 0.2 t = [] for resolution in range(20,80,5): spe = SPEA(u2,resolution= resolution,max_iters=10) res = spe.get_eigen_pair(backend = sim,algo = 'alternate',target_cost = 0.94) theta = res['theta'] t.append(theta) plt.figure(dpi = 100,figsize = (8,6)) plt.title("Eigenphase estimation for theta = 1/5, 0",fontsize = 15) plt.grid() plt.plot(list(range(20,80,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7) plt.plot([10,80],[0.2,0.2],color='black',label = "True") plt.plot([10,80],[0,0],color='black') plt.plot([10,80],[1,1],color='black') plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Estimates") plt.savefig("Plots/SPE_PLOT2.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.compiler import assemble 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 import os from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-education') simulator = Aer.get_backend('qasm_simulator') athens = provider.get_backend('ibmq_athens') class global_max_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_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, angle=None): '''Given an initial state , return the circuit that is generated with inverse rotation ''' # 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,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]) 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 state is a normalized state in ndarray form''' result = {'cost': -1, 'theta': -1} # all theta values are iterated over for the same state phi = Initialize(state) circuits = [] for theta in angles: qc = self.get_circuit(state,backend,theta) circuits.append(qc) circuits = assemble(circuits) # 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 state is a normalized state in ndarray form''' result = {'cost': -1, 'theta': -1} # all theta values are iterated over for the same state phi = Initialize(state) qc = self.get_circuit(state,backend) qc = assemble(qc) # 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, result['theta']) qc = assemble(qc) counts = backend.run(qc, shots=shots).result().get_counts() try: result['cost'] = counts['0']/shots except: result['cost'] = 0 # no 0 counts presenta # return the result return result def get_eigen_pair(self,backend,algo = 'alternate',progress = False,randomize = True, basis=None,basis_ind = None, shots=512): '''Finding the eigenstate pair for the unitary''' #handle algorithm... self.unitary_circuit = self.get_unitary_circuit(backend) if not isinstance(algo,str): raise TypeError("Algorithm must be mentioned as a string from the values {alternate,standard}") elif algo not in ['alternate','standard']: raise ValueError("Algorithm must be specified as 'alternate' or 'standard' ") # handle 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") 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 precision = 1/10**self.error samples = self.resolution # initialization of range left,right = 0,1 # 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 = 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]) 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 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: sys.stdout.write('\r') sys.stdout.write("%f %%completed" % (100*(i+1)/(2*self.dims))) sys.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 simulator = Aer.get_backend('qasm_simulator') U = QuantumCircuit(2) U.cp(2*np.pi*(1/3),0,1) U.draw('mpl') spe = global_max_SPEA(U,resolution= 40,error = 3,max_iters=15) # O(max_iters*(shots+resolution)*|Bm|) result = spe.get_eigen_pair(progress = False,algo = 'alternate',backend=simulator,shots=512) result U = QuantumCircuit(3) U.cp(2*np.pi*(1/3),1,2) U.draw('mpl') errors = [] eigvals = np.array([0.0,1/3,1.0]) for resolution in range(10,80,10): spe = global_max_SPEA(U,resolution= resolution,error = 4,max_iters=15) res = spe.get_eigen_pair(backend = simulator) theta = res['theta'] min_error = 1e5 # get percentage error for e in eigvals: error = abs(e-theta) if error < min_error: min_error = error if e != 0: perc_error = (error/e)*100 else: perc_error = error*100 errors.append(perc_error) plt.title("Eigenphase estimation for theta = 1/3, 0, 1 (3-qubit unitary)",fontsize = 15) plt.grid() plt.plot(list(range(10,80,10)),errors,marker = 'o',color='g',label = 'Estimates',alpha=0.7) # plt.plot([10,80],[0.25,0.25],color='black',label = "True") # plt.plot([10,80],[0,0],color='black',label = "True") # plt.plot([10,80],[1,1],color='black',label = "True") plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Errors from closest eigvals") plt.savefig("Alternate_SPE_PLOT_1.jpg",dpi = 200) U = QuantumCircuit(2) U.cp(2*np.pi*(1/2),0,1) U.draw('mpl') eigvals = np.array([0.0,1/2,1.0]) errors = [] for resolution in range(10,80,10): spe = global_max_SPEA(U,resolution= resolution,error = 3,max_iters=12) #run 5 experiments of this p_errors = [] for exp in range(4): res = spe.get_eigen_pair(progress = False,backend = simulator) theta = res['theta'] min_error = 1e5 min_val = -1 # get min error for e in eigvals: error = abs(e-theta) if error < min_error: min_error = error min_val = e # percent error in this experiment if min_val!=0: p_errors.append((min_error/min_val)*100) else: p_errors.append((min_error)*100) print("Percentage Errors in current iteration:",p_errors) errors.append(np.average(p_errors)) print("Errors :",errors) plt.title("Eigenphase estimation for theta = 1/2, 0.0, 1.0 (2-qubit unitary)",fontsize = 15) plt.grid() plt.plot(list(range(10,80,10)),errors,marker = 'o',color='orange',label = 'Estimates',alpha=0.7) # plt.plot([10,80],[0.25,0.25],color='black',label = "True") # plt.plot([10,80],[0,0],color='black',label = "True") # plt.plot([10,80],[1,1],color='black',label = "True") plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Errors from closest eigvals") plt.savefig("Alternate_SPE_PLOT_2(simulator).jpg",dpi = 200)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import IBMQ from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate, Initialize from qiskit.quantum_info import Statevector from qiskit.compiler import assemble from qiskit.circuit.random import random_circuit 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 import os from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-education') simulator = Aer.get_backend('qasm_simulator') athens = provider.get_backend('ibmq_athens') class SPEA(): def __init__(self, unitary, resolution=50, 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, angle=None): '''Given an initial state , return the circuit that is generated with inverse rotation ''' # 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,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]) 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 state is a normalized state in ndarray form''' result = {'cost': -1, 'theta': -1} # all theta values are iterated over for the same state phi = Initialize(state) circuits = [] for theta in angles: qc = self.get_circuit(state,backend,theta) circuits.append(qc) circuits = assemble(circuits) # 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 state is a normalized state in ndarray form''' result = {'cost': -1, 'theta': -1} # all theta values are iterated over for the same state phi = Initialize(state) qc = self.get_circuit(state,backend) qc = assemble(qc) # 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, result['theta']) qc = assemble(qc) counts = backend.run(qc, shots=shots).result().get_counts() try: result['cost'] = counts['0']/shots except: result['cost'] = 0 # no 0 counts presenta # return the result return result def get_eigen_pair(self, backend, algo='alternate', progress=False, randomize=True, target_cost=None , basis = None, basis_ind = None,shots=512): '''Finding the eigenstate pair for the unitary''' # handle algorithm... self.unitary_circuit = self.get_unitary_circuit(backend) if not isinstance(algo, str): raise TypeError( "Algorithm must be mentioned as a string from the values {alternate,standard}") elif algo not in ['alternate', 'standard']: raise ValueError( "Algorithm must be specified as 'alternate' or 'standard' ") 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") 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") 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 = 0, 1 # 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'] # the range upto which theta extends iin each iteration angle_range = 0.5 # a parameter a = 1 # start algorithm iters = 0 best_phi = phi 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(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, "...") 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'] # at this point I have the best Cost for the state PHI and the # # print(curr_phi) if curr_cost > cost: theta_max = float(curr_theta) cost = float(curr_cost) best_phi = curr_phi found = True if progress: sys.stdout.write('\r') sys.stdout.write("%f %%completed" % (100*(i+1)/(2*self.dims))) sys.stdout.flush() sleep(0.2) # iteration completes if found == False: # phi was not updated , change a a = a/2 if progress: print("\nNo change, updating a...") else: angle_range /= 2 # updated phi and thus theta too -> refine theta range 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 the warning that iters maxed out # add cost, eigenvector and theta to the dict results['cost'] = cost results['theta'] = theta_max results['state'] = best_phi return results simulator = Aer.get_backend('qasm_simulator') U = random_circuit(num_qubits=4,depth=1) U.draw('mpl') spe = SPEA(U, resolution=40, error=3, max_iters=13) result = spe.get_eigen_pair( progress=False, algo='alternate', backend=athens,shots=512) result U = QuantumCircuit(4) U.cp(2*np.pi*(1/2), 1, 2) display(U.draw('mpl')) errors = [] eigvals = np.array([0.0, 0.5, 1.0]) for resolution in range(10, 80, 10): spe = SPEA(U, resolution=resolution, error=4, max_iters=15) res = spe.get_eigen_pair(backend=simulator, algo='alternate') theta = res['theta'] min_error = 1e5 # get percentage error for e in eigvals: error = abs(e-theta) if error < min_error: min_error = error if e != 0: perc_error = (error/e)*100 else: perc_error = error*100 errors.append(perc_error) plt.title( "Eigenphase estimation for theta = 1/2, 0, 1 (4-qubit unitary)", fontsize=15) plt.grid() plt.plot(list(range(10, 80, 10)), errors, marker='o', color='brown', label='Estimates', alpha=0.7) # plt.plot([10,80],[0.25,0.25],color='black',label = "True") # plt.plot([10,80],[0,0],color='black',label = "True") # plt.plot([10,80],[1,1],color='black',label = "True") plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Percentage errors from closest eigenvalues") plt.savefig("Alternate_SPE_PLOT_original_algo.jpg", dpi=200) U = QuantumCircuit(2) U.cp(2*np.pi*(1/6), 0, 1) U.draw('mpl') eigvals = np.array([0.0, 1/6, 1.0]) errors = [] for resolution in range(10, 80, 10): spe = SPEA(U, resolution=resolution, error=3, max_iters=12) # run 5 experiments of this p_errors = [] for exp in range(4): res = spe.get_eigen_pair( progress=False, algo='alternate', backend=simulator) theta = res['theta'] min_error = 1e5 min_val = -1 # get min error for e in eigvals: error = abs(e-theta) if error < min_error: min_error = error min_val = e # percent error in this experiment if min_val != 0: p_errors.append((min_error/min_val)*100) else: p_errors.append((min_error)*100) print("Percentage Errors in current iteration:", p_errors) errors.append(np.average(p_errors)) print("Errors :", errors) plt.title( "Eigenphase estimation for theta = 1/6, 0, 1 (2-qubit unitary)", fontsize=15) plt.grid() plt.plot(list(range(10, 80, 10)), errors, marker='o', color='magenta', label='Estimates', alpha=0.6) # plt.plot([10,80],[0.25,0.25],color='black',label = "True") # plt.plot([10,80],[0,0],color='black',label = "True") # plt.plot([10,80],[1,1],color='black',label = "True") plt.legend() plt.xlabel("Resolution of theta ") plt.ylabel("Percentage Errors from closest eigenvalues") plt.savefig("Alternate_SPE_PLOT_2_original_algo.jpg", dpi=200)
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
resolutions = [i for i in range(10, 55, 5)] resolutions from qiskit import IBMQ 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 # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-education') # santiago = provider.get_backend('ibmq_santiago') # casablanca = provider.get_backend('ibmq_casablanca') # bogota = provider.get_backend('ibmq_bogota') sim = Aer.get_backend('qasm_simulator') # athens = provider.get_backend('ibmq_athens') from Modules.normal_SPEA import SPEA from Modules.changed_SPEA import global_max_SPEA def generate_plots(unitary_size, costs, errors, overlaps, algorithm): import random colors = ['red', 'brown', 'cyan', 'green', 'grey', 'blue', 'purple', 'black', 'orange'] c1, c2, c3 = random.sample(colors, 3) # plot os.makedirs("Experiment_1/"+str(unitary_size) + "_qubit(random)/", exist_ok=True) # plot 1 fig = plt.figure(figsize=(13, 6)) ax1 = fig.add_subplot(1, 2, 1) ax1.set_title(str(unitary_size)+" qubit "+algorithm + " Cost v/s Max iters", fontsize=16) ax1.set_xlabel("Number of Resolutions ", fontsize=15) ax1.set_ylabel("Metrics Returned for unitary ", fontsize=15) ax1.plot(resolutions, costs, label='Costs of Unitary', marker='o', color=c1, alpha=0.7) ax1.plot(resolutions, overlaps, label='Average overlap from nearest eigenvector', marker='s', color=c2, alpha=0.6) ax1.legend(loc='best') ax1.grid() # plot 2 ax2 = fig.add_subplot(1, 2, 2) ax2.set_title(str(unitary_size)+" qubit "+algorithm + " % error v/s Max iters", fontsize=16) ax2.set_xlabel("Number of resolutions ", fontsize=15) ax2.set_ylabel("% error for nearest eigenvalue", fontsize=15) ax2.plot(resolutions, errors, label='Average error from nearest eigenvalue', marker='o', color=c3, alpha=0.6) ax2.legend(loc='best') ax2.grid() # save axure fig.savefig("Experiment_1/"+str(unitary_size)+"_qubit(random)/" + algorithm+" Algorithm (alternate).JPG", dpi=200) def get_results(eig_vals, eig_vect, bases, basis_indices, unitary, algorithm, experiments): '''Return the results of running the algorithm for this particular unitary matrix''' costs_g = [] errors_g = [] max_overlaps_g = [] # find how the cost converges with increasing iterations for reso in resolutions: costs = [] errors = [] overlaps = [] i = 0 # run the experiments ... while len(costs) < experiments: if algorithm == 'original': spea = SPEA(unitary, resolution=reso, error=3, max_iters=10) else: spea = global_max_SPEA( unitary, resolution=reso, error=3, max_iters=10) result = spea.get_eigen_pair( progress=False, backend=sim, algo='alternate', basis=bases[i], basis_ind=basis_indices[i], randomize=False,shots = 2**12) # if result['cost'] < 0.65: # continue # increment the basis index i+=1 # in exp 1 -> basis[0], in exp 2 -> basis[1] and so on.... # find the costs costs.append(result['cost']) theta = result['theta'] res_state = result['state'] # find the abs difference in this theta with the closest eigenvalue # and append that to the errors ... min_error = 1e5 for e in eig_vals: error = abs(e - theta) if error < min_error: min_error = error perc_error = ((error)/e)*100 errors.append(perc_error) # find overlaps max_overlap = -1 for k in eig_vect: dot = np.linalg.norm(np.dot(k, res_state.conjugate().T))**2 max_overlap = max(max_overlap, dot) overlaps.append(max_overlap) print("Result with", reso, " resolutions :") print("AVG. COST :", np.average(costs), "AVG. ERROR :", np.average(errors)) # append the average result of your algorithm ... costs_g.append(np.average(costs)) errors_g.append(np.average(errors)) max_overlaps_g.append(np.average(overlaps)) return costs_g, errors_g, max_overlaps_g unit_2 = unitary_group.rvs(4) unit_2 eig_vals2, eig_vect2 = np.linalg.eig(unit_2) eig_vals2 = np.angle(eig_vals2) e = [] for k in eig_vals2: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals2 = np.array(e) print("Eigenstates :", eig_vect2) print("Eigenvalues :", eig_vals2) bases2 , basis_indices2 = [], [] for _ in range(4): sample = unitary_group.rvs(4) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(4)) bases2.append(basis) basis_indices2.append(ind) print("Basis set :",bases2) print("Basis indices :",basis_indices2) costs_2qubit_b, errors_eig_2qubit_b, max_overlaps_2qubit_b = get_results( eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, 'original', 4) generate_plots(2, costs_2qubit_b, errors_eig_2qubit_b, max_overlaps_2qubit_b, "Original") costs_2qubit_c, errors_eig_2qubit_c, max_overlaps_2qubit_c = get_results( eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, 'modified', 4) generate_plots(2, costs_2qubit_c, errors_eig_2qubit_c, max_overlaps_2qubit_c, "Modified") unit_3 = unitary_group.rvs(8) unit_3 eig_vals3, eig_vect3 = np.linalg.eig(unit_3) eig_vals3 = np.angle(eig_vals3) e = [] for k in eig_vals3: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals3 = np.array(e) print("Eigenstates :", eig_vect3) print("Eigenvalues :", eig_vals3) bases3 , basis_indices3 = [], [] for _ in range(4): sample = unitary_group.rvs(8) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(8)) bases3.append(basis) basis_indices3.append(ind) print("Basis indices :",basis_indices3) costs_3qubit_b, errors_eig_3qubit_b, max_overlaps_3qubit_b = get_results( eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, 'original', 4) generate_plots(3, costs_3qubit_b, errors_eig_3qubit_b, max_overlaps_3qubit_b, "Original") costs_3qubit_c, errors_eig_3qubit_c, max_overlaps_3qubit_c = get_results( eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, 'modified', 4) generate_plots(3, costs_3qubit_c, errors_eig_3qubit_c, max_overlaps_3qubit_c, "Modified") unit_4 = unitary_group.rvs(16) # unit_4 eig_vals4, eig_vect4 = np.linalg.eig(unit_4) eig_vals4 = np.angle(eig_vals4) e = [] for k in eig_vals4: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals4 = np.array(e) print("Eigenstates :", eig_vect4) print("Eigenvalues :", eig_vals4) bases4 , basis_indices4 = [], [] for _ in range(4): sample = unitary_group.rvs(16) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(16)) bases4.append(basis) basis_indices4.append(ind) print("Basis indices :",basis_indices4) costs_4qubit_b, errors_eig_4qubit_b, max_overlaps_4qubit_b = get_results( eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'original', 4) generate_plots(4, costs_4qubit_b, errors_eig_4qubit_b, max_overlaps_4qubit_b, "Original") costs_4qubit_c, errors_eig_4qubit_c, max_overlaps_4qubit_c = get_results( eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'modified', 4) generate_plots(4, costs_4qubit_c, errors_eig_4qubit_c,max_overlaps_4qubit_c, "Modified")
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
iterations = [i for i in range(5, 20, 2)] iterations from qiskit import IBMQ import random 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 # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-education') # santiago = provider.get_backend('ibmq_santiago') # casablanca = provider.get_backend('ibmq_casablanca') # bogota = provider.get_backend('ibmq_bogota') sim = Aer.get_backend('qasm_simulator') # athens = provider.get_backend('ibmq_athens') from Modules.normal_SPEA import SPEA from Modules.changed_SPEA import global_max_SPEA def generate_plots(unitary_size, costs, errors, overlaps, algorithm): colors = ['red', 'brown', 'cyan', 'green', 'grey', 'blue', 'purple', 'black', 'orange'] c1, c2, c3 = random.sample(colors, 3) # plot os.makedirs("Experiment_2/"+str(unitary_size) + "_qubit(random)/", exist_ok=True) # plot 1 fig = plt.figure(figsize=(13, 6)) ax1 = fig.add_subplot(1, 2, 1) ax1.set_title(str(unitary_size)+" qubit "+algorithm + " Cost v/s Max iters", fontsize=16) ax1.set_xlabel("Maximum iterations ", fontsize=15) ax1.set_ylabel("Metrics Returned for unitary ", fontsize=15) ax1.plot(iterations, costs, label='Costs of Unitary', marker='o', color=c1, alpha=0.7) ax1.plot(iterations, overlaps, label='Average overlap from nearest eigenvector', marker='s', color=c2, alpha=0.6) ax1.legend(loc='best') ax1.grid() # plot 2 ax2 = fig.add_subplot(1, 2, 2) ax2.set_title(str(unitary_size)+" qubit "+algorithm + " % error v/s Max iters", fontsize=16) ax2.set_xlabel("Maximum iterations ", fontsize=15) ax2.set_ylabel("% error for nearest eigenvalue", fontsize=15) ax2.plot(iterations, errors, label='Average error from nearest eigenvalue', marker='o', color=c3, alpha=0.6) ax2.legend(loc='best') ax2.grid() # save axure fig.savefig("Experiment_2/"+str(unitary_size)+"_qubit(random)/" + algorithm+" Algorithm (alternate).JPG", dpi=200) def get_results(eig_vals, eig_vect, bases, basis_indices, unitary, algorithm, experiments): '''Return the results of running the algorithm for this particular unitary matrix''' costs_g = [] errors_g = [] max_overlaps_g = [] # find how the cost converges with increasing iterations for iters in iterations: costs = [] errors = [] overlaps = [] i = 0 # run the experiments ... while len(costs) < experiments: if algorithm == 'original': spea = SPEA(unitary, resolution=30, error=3, max_iters=iters) else: spea = global_max_SPEA( unitary, resolution=30, error=3, max_iters=iters) result = spea.get_eigen_pair( progress=False, backend=sim, basis=bases[i], basis_ind=basis_indices[i], algo='alternate', randomize=False,shots = 256) if result['cost'] < 0.65: continue i+=1 # find the costs costs.append(result['cost']) theta = result['theta'] res_state = result['state'] # find the abs difference in this theta with the closest eigenvalue # and append that to the errors ... min_error = 1e5 for e in eig_vals: error = abs(e - theta) if error < min_error: min_error = error perc_error = ((error)/e)*100 errors.append(perc_error) # find overlaps max_overlap = -1 for k in eig_vect: dot = np.linalg.norm(np.dot(k, res_state.conjugate().T))**2 max_overlap = max(max_overlap, dot) overlaps.append(max_overlap) print("Result with", iters, " iterations :") print("AVG. COST :", np.average(costs), "AVG. ERROR :", np.average(errors)) # append the average result of your algorithm ... costs_g.append(np.average(costs)) errors_g.append(np.average(errors)) max_overlaps_g.append(np.average(overlaps)) return costs_g, errors_g, max_overlaps_g unit_2 = unitary_group.rvs(4) unit_2 eig_vals2, eig_vect2 = np.linalg.eig(unit_2) eig_vals2 = np.angle(eig_vals2) e = [] for k in eig_vals2: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals2 = np.array(e) print("Eigenstates :", eig_vect2) print("Eigenvalues :", eig_vals2) bases2 , basis_indices2 = [], [] for _ in range(4): sample = unitary_group.rvs(4) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) # print("2 qubit basis :", basis2) ind = np.random.choice(range(4)) # print(ind) bases2.append(basis) basis_indices2.append(ind) # print("Basis set :",bases2) print("Basis indices :",basis_indices2) costs_2qubit_b, errors_2qubit_b, max_overlaps_2qubit_b = get_results(eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, "original", 4) generate_plots(2, costs_2qubit_b, errors_2qubit_b, max_overlaps_2qubit_b, "Original") costs_2qubit_c, errors_2qubit_c, max_overlaps_2qubit_c = get_results( eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, "modified", 4) generate_plots(2, costs_2qubit_c, errors_2qubit_c, max_overlaps_2qubit_c, "Modified") unit_3 = unitary_group.rvs(8) unit_3 eig_vals3, eig_vect3 = np.linalg.eig(unit_3) eig_vals3 = np.angle(eig_vals3) e = [] for k in eig_vals3: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals3 = np.array(e) print("Eigenstates :", eig_vect3) print("Eigenvalues :", eig_vals3) bases3 , basis_indices3 = [], [] for _ in range(4): sample = unitary_group.rvs(8) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) # print("3 qubit basis :", basis3) ind = np.random.choice(range(8)) # print(ind) bases3.append(basis) basis_indices3.append(ind) # print("Basis set :",bases3) print("Basis indices :",basis_indices3) costs_3qubit_b, errors_3qubit_b, max_overlaps_3qubit_b = get_results( eig_vals3, eig_vect3,bases3, basis_indices3, unit_3, "original", 4) generate_plots(3, costs_3qubit_b, errors_3qubit_b, max_overlaps_3qubit_b, "Original") costs_3qubit_c, errors_3qubit_c, max_overlaps_3qubit_c = get_results( eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, "modified", 4) generate_plots(3, costs_3qubit_c, errors_3qubit_c, max_overlaps_3qubit_c, "Modified") unit_4 = unitary_group.rvs(16) # unit_4 eig_vals4, eig_vect4 = np.linalg.eig(unit_4) eig_vals4 = np.angle(eig_vals4) e = [] for k in eig_vals4: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals4 = np.array(e) print("Eigenstates :", eig_vect4) print("Eigenvalues :", eig_vals4) bases4 , basis_indices4 = [], [] for _ in range(4): sample = unitary_group.rvs(16) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(16)) bases4.append(basis) basis_indices4.append(ind) print("Basis indices :",basis_indices4) costs_4qubit_b, errors_eig_4qubit_b, max_overlaps_4qubit_b = get_results( eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'original', 4) generate_plots(4, costs_4qubit_b, errors_eig_4qubit_b, max_overlaps_4qubit_b, "Original") costs_4qubit_c, errors_eig_4qubit_c, max_overlaps_4qubit_c = get_results( eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'modified', 4) generate_plots(4, costs_4qubit_c, errors_eig_4qubit_c, max_overlaps_4qubit_c, "Modified")
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
error = 0.002 thresholds, targets = [], [] while error < 0.4: thresholds.append(error) targets.append(round(1-error, 3)) error *= 2 print("Threshold :", thresholds) print("Target costs :", targets) from qiskit import IBMQ 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 IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-education') # santiago = provider.get_backend('ibmq_santiago') # casablanca = provider.get_backend('ibmq_casablanca') # bogota = provider.get_backend('ibmq_bogota') sim = Aer.get_backend('qasm_simulator') # athens = provider.get_backend('ibmq_athens') from Modules.normal_SPEA import SPEA from Modules.changed_SPEA import global_max_SPEA def generate_plots(unitary_size, costs, overlaps, errors_eigen, errors_cost, algorithm): import random colors = ['red', 'brown', 'cyan', 'green', 'grey', 'blue', 'purple', 'black', 'orange'] c1, c2, c3, c4 = random.sample(colors, 4) # plot os.makedirs("Experiment_3/"+str(unitary_size) + "_qubit(random)/", exist_ok=True) # plot 1 fig = plt.figure(figsize=(13, 6)) ax1 = fig.add_subplot(1, 2, 1) ax1.set_title(str(unitary_size)+" qubit "+algorithm + " Cost vs Error threshold", fontsize=16) ax1.set_xlabel("Target costs ", fontsize=15) ax1.set_ylabel("Metrics Returned for unitary ", fontsize=15) # plot metrics ax1.plot(targets, costs, label='Costs of Unitary', marker='o', color=c1, alpha=0.7) ax1.plot(targets, overlaps, label='Average overlap from nearest eigenvector', marker='s', color=c2, alpha=0.6) ax1.plot() ax1.legend(loc='best') ax1.grid() # plot 2 ax2 = fig.add_subplot(1, 2, 2) ax2.set_title(str(unitary_size)+" qubit "+algorithm + " % Errors v/s thresholds", fontsize=16) ax2.set_xlabel("Target Costs", fontsize=15) ax2.set_ylabel("% errors", fontsize=15) # plot errors ax2.plot(targets, errors_eigen, label='Average error from nearest eigenvalue', marker='o', color=c3, alpha=0.6) ax2.plot(targets, errors_cost, label='Average deviation from desired cost', marker='s', color=c4, alpha=0.7) ax2.legend(loc='best') ax2.grid() # save axure fig.savefig("Experiment_3/"+str(unitary_size)+"_qubit(random)/" + algorithm+" Algorithm (alternate).JPG", dpi=200) def get_results(eig_vals, eig_vect, bases, basis_indices, unitary, algorithm, experiments): '''Return the results of running the algorithm for this particular unitary matrix''' costs_g = [] errors_eig_g = [] max_overlaps_g = [] errors_costs_g = [] # find how the cost converges with increasing iterations for error, target in zip(thresholds, targets): costs = [] errors_eig = [] errors_costs = [] overlaps = [] i = 0 # run the experiments ... while len(costs) < experiments: if algorithm == 'original': spea = SPEA(unitary, resolution=30, max_iters=10) else: spea = global_max_SPEA(unitary, resolution=30, max_iters=10) result = spea.get_eigen_pair( progress=False, backend=sim, target_cost=target, basis=bases[i], basis_ind=basis_indices[i], algo='alternate', randomize=False,shots=256) # results theta = result['theta'] res_state = result['state'] # get the results if result['cost'] < 0.75: continue i+=1 # find the abs difference in this theta with the closest eigenvalue # and append that to the errors ... min_error = 1e5 for e in eig_vals: error = abs(e - theta) if error < min_error: min_error = error perc_error = ((error)/e)*100 # get costs costs.append(result['cost']) # get eigenvalue error errors_eig.append(perc_error) # append the perc error from original target cost if target >= result['cost']: deviation = abs(target - result['cost'])/(target) else: # if we have stopped with a better cost, no sense of deviation deviation = 0 errors_costs.append(deviation*100) # find overlaps max_overlap = -1 for k in eig_vect: dot = np.linalg.norm(np.dot(k, res_state.conjugate().T))**2 max_overlap = max(max_overlap, dot) overlaps.append(max_overlap) print(costs, errors_costs) print("Result with", target, " target cost :") print("AVG. COST :", np.average(costs)) print("AVG. EIGENVALUE ERROR :", np.average(errors_eig)) print("AVG. DEVIATION FROM TARGET COST", np.average(errors_costs)) # append the average result of your algorithm ... costs_g.append(np.average(costs)) errors_eig_g.append(np.average(errors_eig)) errors_costs_g.append(np.average(errors_costs)) max_overlaps_g.append(np.average(overlaps)) return costs_g, errors_eig_g, errors_costs_g, max_overlaps_g unit_2 = unitary_group.rvs(4) unit_2 eig_vals2, eig_vect2 = np.linalg.eig(unit_2) eig_vals2 = np.angle(eig_vals2) e = [] for k in eig_vals2: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals2 = np.array(e) print("Eigenstates :", eig_vect2) print("Eigenvalues :", eig_vals2) bases2 , basis_indices2 = [], [] for _ in range(4): sample = unitary_group.rvs(4) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(4)) bases2.append(basis) basis_indices2.append(ind) print("Basis set :",bases2) print("Basis indices :",basis_indices2) costs_2qubit_b, errors_eig_2qubit_b, errors_costs_2qubit_b, max_overlaps_2qubit_b = get_results( eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, 'original', 4) generate_plots(2, costs_2qubit_b, max_overlaps_2qubit_b, errors_eig_2qubit_b, errors_costs_2qubit_b, "Original") costs_2qubit_c, errors_eig_2qubit_c, errors_costs_2qubit_c, max_overlaps_2qubit_c = get_results( eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, 'modified', 4) generate_plots(2, costs_2qubit_c, max_overlaps_2qubit_c, errors_eig_2qubit_c, errors_costs_2qubit_c, "Modified") unit_3 = unitary_group.rvs(8) eig_vals3, eig_vect3 = np.linalg.eig(unit_3) eig_vals3 = np.angle(eig_vals3) e = [] for k in eig_vals3: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals3 = np.array(e) print("Eigenstates :", eig_vect3) print("Eigenvalues :", eig_vals3) bases3 , basis_indices3 = [], [] for _ in range(4): sample = unitary_group.rvs(8) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(8)) bases3.append(basis) basis_indices3.append(ind) print("Basis indices :",basis_indices3) costs_3qubit_b, errors_eig_3qubit_b, errors_costs_3qubit_b, max_overlaps_3qubit_b = get_results( eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, 'original', 4) generate_plots(3, costs_3qubit_b, max_overlaps_3qubit_b, errors_eig_3qubit_b, errors_costs_3qubit_b, "Original") costs_3qubit_c, errors_eig_3qubit_c, errors_costs_3qubit_c, max_overlaps_3qubit_c = get_results( eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, 'modified', 4) generate_plots(3, costs_3qubit_c, max_overlaps_3qubit_c, errors_eig_3qubit_c, errors_costs_3qubit_c, "Modified") unit_4 = unitary_group.rvs(16) # unit_4 eig_vals4, eig_vect4 = np.linalg.eig(unit_4) eig_vals4 = np.angle(eig_vals4) e = [] for k in eig_vals4: if k < 0: v = (k + 2*np.pi)/(2*np.pi) else: v = (k)/(2*np.pi) e.append(v) eig_vals4 = np.array(e) print("Eigenstates :", eig_vect4) print("Eigenvalues :", eig_vals4) bases4 , basis_indices4 = [], [] for _ in range(4): sample = unitary_group.rvs(16) basis = [] for k in sample: basis.append(np.array(k, dtype=complex)) ind = np.random.choice(range(16)) bases4.append(basis) basis_indices4.append(ind) print("Basis indices :",basis_indices4) costs_4qubit_b, errors_eig_4qubit_b, errors_costs_4qubit_b, max_overlaps_4qubit_b = get_results( eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'original', 4) generate_plots(4, costs_4qubit_b, max_overlaps_4qubit_b, errors_eig_4qubit_b, errors_costs_4qubit_b, "Original") costs_4qubit_c, errors_eig_4qubit_c, errors_costs_4qubit_c, max_overlaps_4qubit_c = get_results( eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'modified', 4) generate_plots(4, costs_4qubit_c, max_overlaps_4qubit_c, errors_eig_4qubit_c, errors_costs_4qubit_c, "Modified")
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import * import matplotlib.pyplot as plt import random from scipy.stats import unitary_group import os import sys sys.path.append("../..") import seaborn as sns import numpy as np from Modules.normal_SPEA import SPEA from Modules.changed_SPEA import global_max_SPEA unit = unitary_group.rvs(4) unit # get the eigenvalues and eigenstates eig_v, eig_vect = np.linalg.eig(unit) eig_v = np.angle(eig_v) eig = [] for k in eig_v: if k < 0: e = (k+2*np.pi)/(2*np.pi) else: e = (k)/(2*np.pi) eig.append(e) eig_v = np.array(eig) print("Eigenvalues :", eig_v) print("Eigenstates :", eig_vect) sample = unitary_group.rvs(4) basis = [] for k in sample: basis.append(k) basis_ind = np.random.choice(range(4)) print("Basis :", basis) print("Basis index :", basis_ind) def generate_plot1(actual_E, returned_E, iters): colors = ['blue', 'orange', 'red', 'green', 'brown', 'magenta', 'pink'] plt.figure(figsize=(9, 7)) plt.scatter(range(iters), returned_E, marker='o', edgecolors='grey', color=np.random.choice(colors), alpha=0.8,) for i, k in enumerate(actual_E): if i == 0: plt.plot([0, iters], [k, k], color='black', linewidth=2, label='Actual Values') else: plt.plot([0, iters], [k, k], color='black', linewidth=2) plt.xlabel("Number of iterations", fontsize=14) plt.ylabel("Eigenvalues", fontsize=14) plt.title("Scatter plot for returned eigenvalues", fontsize=17) plt.legend() plt.grid() def generate_plot2(actual_E, returned_E, size, experiments): colors = ['blue', 'orange', 'red', 'green', 'brown', 'magenta', 'pink'] fig = plt.figure(figsize=(16, 13)) for i in range(size): ax = fig.add_subplot(size/2, 2, i+1) ax.scatter(range(experiments), returned_E[i], marker='o', edgecolors='grey', color=np.random.choice(colors), alpha=0.8,) for i, k in enumerate(actual_E): if i == 0: ax.plot([0, experiments], [k, k], color='black', linewidth=2, label='Actual Values') else: ax.plot([0, experiments], [k, k], color='black', linewidth=2) ax.set_xlabel("Experiment Number", fontsize=14) ax.set_ylabel("Eigenvalues", fontsize=14) ax.set_title("Scatter plot for returned eigenvalues", fontsize=17) ax.legend(loc='best') ax.grid() simulator = Aer.get_backend('qasm_simulator') spea1 = SPEA(unit,resolution=40,error = 2, max_iters=15) eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 100: res = spea1.get_eigen_pair( backend=simulator, algo='alternate', basis=basis, basis_ind=basis_ind) if res['cost'] < 0.75: continue print(res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 100) spea2 = global_max_SPEA(unit, resolution=40, error=2, max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret2 = [] while len(eigen_vals_ret2) != 100: res = spea2.get_eigen_pair( backend=simulator, algo='alternate', basis=basis, basis_ind=basis_ind) if res['cost'] < 0.75: continue print(res) eigen_vals_ret2.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret2, 100) unit = unitary_group.rvs(4) # get the eigenvalues and eigenstates eig_v, eig_vect = np.linalg.eig(unit) eig_v = np.angle(eig_v) eig = [] for k in eig_v: if k < 0: e = (k+2*np.pi)/(2*np.pi) else: e = (k)/(2*np.pi) eig.append(e) eig_v = np.array(eig) print(eig_v) y = np.array([[0,-1j], [1j,0]]) yy= np.kron(y,y) basis = [] for k in yy: basis.append(k) basis eig_ret = [] spea1 = SPEA(unit, resolution=30, error=2, max_iters=10) simulator = Aer.get_backend('qasm_simulator') for i in range(4): basis_index = i eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 15: res = spea1.get_eigen_pair( backend=simulator, algo='alternate', basis=basis, basis_ind=basis_index) if res['cost'] < 0.75: continue print((len(eigen_vals_ret1)/15)*100, "% done...") eigen_vals_ret1.append(res['theta']) eig_ret.append(eigen_vals_ret1) generate_plot2(eig_v, eig_ret, 4, 15) eig_ret2 = [] spea2 = global_max_SPEA(unit, resolution=30, error=2, max_iters=10) simulator = Aer.get_backend('qasm_simulator') for i in range(4): basis_index = i eigen_vals_ret2 = [] while len(eigen_vals_ret2) != 40: res = spea2.get_eigen_pair( backend=simulator, algo='alternate', basis=basis, basis_ind=basis_index) if res['cost'] < 0.75: continue print((len(eigen_vals_ret2)/40)*100, "% done...") eigen_vals_ret2.append(res['theta']) eig_ret2.append(eigen_vals_ret2) generate_plot2(eig_v, eig_ret2, 4, 40) plt.title("Original Algorithm ") for i in range(4): sns.kdeplot(eig_ret[i], shade=True, label='Basis '+str(i)) plt.xlabel("Eigenvalues Returned") plt.legend() plt.title("Modified Algorithm ") for i in range(4): sns.kdeplot(eig_ret2[i], shade=True, label='Basis '+str(i), palette='red') plt.xlabel("Eigenvalues Returned") plt.legend() def min_eigensolver(unitary, algo, experiments=20, min_threshold=0.9): dims = unitary.shape[0] simulator = Aer.get_backend('qasm_simulator') step_size = (1/dims) # generate the steps steps = np.arange(0, 1 + 1e-12, step_size) if steps[-1] != 1: steps = np.append(steps, 1) print("Steps :", steps) if algo == 0: spe = SPEA(unitary, resolution=40, error=2, max_iters=12) else: spe = global_max_SPEA(unitary, resolution=40, error=2, max_iters=12) # start the experiments max_cost = -1 for i in range(len(steps) - 1): # define left and right bounds left = steps[i] right = steps[i+1] costs, eigs = [], [] # lists to store costs for _ in range(experiments): res = spe.get_eigen_pair( backend=simulator, theta_left=left, theta_right=right, randomize=True) costs.append(res['cost']) eigs.append(res['theta']) # if the cost is above threshold, return them if np.average(costs) > min_threshold: return (np.average(costs), eigs) if np.average(costs) > max_cost: max_cost = np.average(costs) best_eigs = eigs # return the cost with the max average cost return (max_cost, best_eigs) unit = unitary_group.rvs(4) unit # get the eigenvalues and eigenstates eig_v, eig_vect = np.linalg.eig(unit) eig_v = np.angle(eig_v) eig = [] for k in eig_v: if k < 0: e = (k+2*np.pi)/(2*np.pi) else: e = (k)/(2*np.pi) eig.append(e) eig_v = np.array(eig) print("Eigenvalues :", eig_v) print("Eigenstates :", eig_vect) res1 = min_eigensolver(unit, algo=0, experiments=40, min_threshold=0.85) res2 = min_eigensolver(unit, algo=1, experiments=40, min_threshold=0.85) res1[1], res2[1] generate_plot1(eig_v,res1[1],40) generate_plot1(eig_v,res2[1],40)
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.monitor import job_monitor from qiskit.compiler import assemble 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 from scipy.stats import unitary_group import matplotlib.pyplot as plt x = np.linspace(0.05, 1, 200) c = np.cos(x) c2 = (np.cos(x))**2 ex = np.exp(-x) ex2 = np.exp(-x**2) x_inv = (1/x) x_inv2 = (1/x**2) plt.figure(dpi=120) plt.title("Cost Function plots", fontsize=20) plt.xlabel("Theta values", fontsize=16) plt.ylabel("Metric values", fontsize=16) plt.plot(x, c, label="$cos(x)$") plt.plot(x, c2, label="$cos^{2}(x)$") plt.plot(x, ex, label="$e^{-x}$") plt.plot(x, ex2, label="$e^{-x^{2}}$") plt.grid() plt.legend() plt.figure(dpi=120) plt.title("Cost Function plots", fontsize=20) plt.xlabel("Theta values", fontsize=16) plt.ylabel("Metric values", fontsize=16) plt.plot(x, x_inv, label="$\\frac{1}{x}$") plt.plot(x, x_inv2, label="$\\frac{1}{x^{2}}$") plt.grid() plt.legend() class global_max_SPEA(): def __init__(self, unitary, cost_function, max_metric_val, resolution=100, 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 metric if not isinstance(max_metric_val, int) and not isinstance(max_metric_val, float): raise TypeError( "The required metric value should be provided as an int or a float.") elif max_metric_val <= 0: raise ValueError( "The required metric must be finite and greater than 0.") elif cost_function in ['cos', 'cos2', 'exp', 'exp2'] and max_metric_val > 1: raise ValueError( "Maximum metric can't be greater than 1 in case of given cost function") self.max_metric = max_metric_val # 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 cost_fns = ['cos', 'cos2', 'exp', 'exp2', 'inv', 'inv2'] # handle cost function if cost_function not in cost_fns: raise ValueError( "Cost function must be one of [cos, cos2, exp, exp2, inv, inv2]") self.cost_function = cost_function 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 ''' # 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 state is a normalized state in ndarray form''' 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 state is a normalized state in ndarray form''' 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 __get_metric_val(self, cost, theta): '''Generate optimization metric value based on the given cost function ''' func = self.cost_function if func == 'cos': return cost*(np.cos(theta)) elif func == 'cos2': return cost*((np.cos(theta))**2) elif func == 'exp': return cost*(np.exp(-theta)) elif func == 'exp2': return cost*(np.exp(-theta**2)) elif func == 'inv': try: return cost/theta except: return 1e7 elif func == 'inv2': try: return cost/(theta**2) except: return 1e7 def get_eigen_pair(self, backend, algo='alternate', theta_left=0, theta_right=1, progress=False, basis=None, basis_ind=None, randomize=True, target_metric=None, shots=512 ): '''Finding the eigenstate pair for the unitary''' # handle algorithm... self.unitary_circuit = self.__get_unitary_circuit(backend) # handle theta bounds 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].") # handle algorithm if not isinstance(algo, str): raise TypeError( "Algorithm must be mentioned as a string from the values {alternate,standard}") elif algo not in ['alternate', 'standard']: raise ValueError( "Algorithm must be specified as 'alternate' or 'standard' ") if target_metric is not None: if (target_metric <= 0): raise ValueError("Target metric must be a real value > 0") # handle 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") 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 # new if target_metric is None: max_metric = self.max_metric else: if self.cost_function in ['cos','cos2','exp','exp2']: assert target_metric <= 1 , "For given cost function, target cost can't be greater than 1" max_metric = target_metric 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 global_metric = self.__get_metric_val(cost, theta_max) # 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 global_metric < max_metric: # 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, metrics = [], [], [], [] 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 * \ (max_metric - global_metric)*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'] # new curr_metric = self.__get_metric_val(curr_cost, curr_theta) # append these parameters if curr_metric > global_metric: # 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) # new metrics.append(curr_metric) 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: sys.stdout.write('\r') sys.stdout.write("%f %%completed" % (100*(i+1)/(2*self.dims))) sys.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 # new # we need to update the best phi , theta max and cost on # the basis of cost / theta_max value index = np.argmax(metrics) # update the parameters of the model cost = costs[index] theta_max = thetas[index] best_phi = states[index] global_metric = metrics[index] angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) print("Current Metric :", global_metric) 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 results['metric'] = global_metric return results unit = unitary_group.rvs(8) unit # get the eigenvalues and eigenstates eig_v, eig_vect = np.linalg.eig(unit) eig_v = np.angle(eig_v) eig = [] for k in eig_v: if k < 0: e = (k+2*np.pi)/(2*np.pi) else: e = (k)/(2*np.pi) eig.append(e) eig_v = np.array(eig) # print("Eigenvalues :", eig_v) # print("Eigenstates :", eig_vect) def generate_plot1(actual_E, returned_E, experiments,function): colors = ['blue', 'orange', 'red', 'green', 'brown', 'magenta', 'pink'] plt.figure(figsize=(9, 7)) plt.scatter(range(experiments), returned_E, marker='o', edgecolors='grey', color=np.random.choice(colors), alpha=0.8,) for i, k in enumerate(actual_E): if i == 0: plt.plot([0, experiments], [k, k], color='black', linewidth=2, label='Actual Values') else: plt.plot([0, experiments], [k, k], color='black', linewidth=2) plt.xlabel("Experiment Number", fontsize=14) plt.ylabel("Eigenvalues", fontsize=14) plt.title("Scatter plot for returned eigenvalues with cost function "+str(function), fontsize=17) plt.legend() plt.grid() spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=0.92,cost_function='cos', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 0.8: continue print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "cos") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=0.92,cost_function='cos2', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 0.8: continue # print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "cos2") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=0.92,cost_function='exp', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 0.8: continue # print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "exp") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=0.92,cost_function='exp2', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 0.8: continue print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "exp2") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=4,cost_function='inv', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 3: continue print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "inv") spea1 = global_max_SPEA(unit, resolution=30, max_metric_val=20,cost_function='inv2', max_iters=15) simulator = Aer.get_backend('qasm_simulator') eigen_vals_ret1 = [] while len(eigen_vals_ret1) != 40: res = spea1.get_eigen_pair( backend=simulator, algo='alternate') if res['metric'] < 15: continue print("Result :", res) eigen_vals_ret1.append(res['theta']) generate_plot1(eig_v, eigen_vals_ret1, 40, "inv2")
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate,Initialize from qiskit.tools.visualization import plot_histogram from qiskit.compiler import assemble import numpy as np from time import sleep from qiskit.tools.monitor import job_monitor from qiskit.extensions import UnitaryGate from qiskit.quantum_info import Statevector import sys from scipy.stats import unitary_group import matplotlib.pyplot as plt class SPEA(): ''' This is a class which implements the Statistical Phase Estimation algorithm 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 for the unitary matrix ''' def __init__(self, unitary, resolution=50, 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() # RANDOMNESS 1 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() # RANDOMNESS 2 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]) 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) # RANDOMNESS 3 # 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 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 = 1 - c0 # 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* # RANDOMNESS 4 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 get_eigen_pair(self, backend, algo='alternate', theta_left = 0,theta_right = 1,progress=False, randomize=True, target_cost=None, basis = None, basis_ind = 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 ''' # handle algorithm... 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(algo, str): raise TypeError( "Algorithm must be mentioned as a string from the values {alternate,standard}") elif algo not in ['alternate', 'standard']: raise ValueError( "Algorithm must be specified as 'alternate' or 'standard' ") 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") 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") 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 = min(1,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, "...") 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'] # at this point I have the best Cost for the state PHI and the if curr_cost > cost: theta_max = float(curr_theta) cost = min(1.0,float(curr_cost)) best_phi = curr_phi found = True if progress: sys.stdout.write('\r') sys.stdout.write("%f %%completed" % (100*(i+1)/(2*self.dims))) sys.stdout.flush() # iteration completes if found == False: # phi was not updated , change a a = a/2 if progress: print("\nNo change, updating a...") else: angle_range /= 2 # updated phi and thus theta too -> refine theta range 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 the warning that iters maxed out # 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.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 from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline from qiskit import IBMQ # defining the absolute error in the eigenvalue deltas = [0.4, 0.3, 0.2, 0.15, 0.1, 0.05, 0.025, 0.01] # find the target costs for each of the algorithm target_costs = [] for i in deltas: cost = (np.cos(i))**2 target_costs.append(cost) target_costs u1 = unitary_group.rvs(2) u1 eigen_phases1, eigen_vectors1 = np.linalg.eig(u1) print("Eigen states of Unitary :",eigen_vectors1) eigen_phases1 = np.angle(eigen_phases1) ep1 = [] for k in eigen_phases1: if k < 0: ep1.append((k + 2*np.pi)/(2*np.pi)) else: ep1.append(k/(2*np.pi)) eigen_phases1 = np.array(ep1) print("Eigen phases of unitary :",eigen_phases1) from normal_SPEA import SPEA backend = Aer.get_backend('qasm_simulator') # looping and storing the results we get generated_deltas, errors = [],[] for delta,cost in zip(deltas,target_costs): spea = SPEA(u1,resolution=35,max_iters=15) max_differences = [] delta_error = [] print("TARGET COST :",cost) print("GIVEN DELTA :",delta) # doing numerous experiments to converge for exp in range(10): result = spea.get_eigen_pair(backend = backend,progress = False, randomize = True, target_cost = cost) print("Result with target cost as",cost,"was returned\n",result) # find the final cost theta = result['theta'] stop_cost = result['cost'] # find the maximum difference between the eigenphases and this returned phase max_diff = max(abs(eigen_phases1 - theta)) max_differences.append(max_diff) # now append this and the error from how it actually should have been # NOTE - there is no error if the max difference is actually less than # the delta desired . if delta - max_diff >= 0: error = 0 else: # this error should not be more than 5-6 % or 0.05 - 0.06 error = abs((delta - max_diff))/delta delta_error.append(error) # the maximum would be a better metric generated_deltas.append(np.average(max_differences)) errors.append(np.average(delta_error)) iters = [i for i in range(1,9)] plt.figure(figsize=(10,8)) plt.title("Plot for Generated and Given maximum $ \delta^{*}$ values",fontsize=16) plt.xlabel("Iteration Number", fontsize = 14) plt.ylabel("Values of $ \delta^{*}$ (maximum average error)",fontsize = 14) plt.grid() plt.plot(iters, deltas, label = 'Actual Values', color = 'black', alpha = 0.7, marker = 'o') plt.plot(iters, generated_deltas, label = 'Generated Values', color = 'green', alpha = 0.7, marker = 's') plt.legend() plt.savefig("Plot for verifying Cost Lower Bound.JPG",dpi = 200) plt.figure(figsize=(10,8)) plt.title("Plot for Error in Generated and Given maximum $ \delta^{*}$ values",fontsize=16) plt.xlabel("Iteration Number", fontsize = 14) plt.ylabel("Relative Error in $ \delta^{*}$",fontsize = 14) plt.grid() plt.plot(iters, errors, label = 'Error Values', color = 'cyan', alpha = 0.8, marker = 'o') plt.legend() plt.savefig("Plot for Error in Cost Lower Bound.JPG",dpi = 200)
https://github.com/epelaaez/QuantumLibrary
epelaaez
import config from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, IBMQ, Aer, execute from qiskit.visualization import plot_histogram from qiskit.providers.ibmq import least_busy def bell_state(): qreg = QuantumRegister(2, 'q') creg = ClassicalRegister(2, 'c') qc = QuantumCircuit(qreg, creg) # Create bell state itself by putting first qubit into superposition and then applying a CNOT gate between the two qubits qc.h(qreg[0]) qc.cx(qreg[0], qreg[1]) # Measure both qubits qc.measure(qreg[0], creg[0]) qc.measure(qreg[1], creg[1]) # Return circuit return qc circ = bell_state() circ.draw() IBMQ.save_account(f"{config.IBM_KEY}", overwrite = True) IBMQ.load_account() backend = Aer.get_backend('qasm_simulator') # Uncomment below to run on hardware # provider = IBMQ.get_provider(hub='ibm-q') # backend = least_busy(provider.backends()) result = execute(circ, backend, shots=1024).result() counts = result.get_counts(circ) plot_histogram(counts)
https://github.com/epelaaez/QuantumLibrary
epelaaez
import config import random from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, IBMQ, Aer, execute from qiskit.visualization import plot_histogram from qiskit.providers.ibmq import least_busy def d_oracle(qc, oracle, choice): """ Add oracle for Deutsch's algoritm, in the form of a gate, to quantum circuit. Parameters: ----------- qc: QuantumCircuit Quantum circuit with 2 qubits. oracle: int Type of oracle. 0 for balanced and 1 for constant. choice: int Choice of oracle type. For a balanced oracle, 0 will make f(x)=x and 1 will make f(x)=¬x. For a constant oracle, 0 will make f(x)=0 and 1 will make f(x)=1. Returns: -------- qc: QuantumCircuit Quantum circuit with Deutsch's algorithm oracle added at the end. """ qreg = QuantumRegister(2, 'q') oracle_circuit = QuantumCircuit(qreg, name='$U_f$') # Balanced oracle if oracle == 0: if choice == 0: oracle_circuit.cx(0, 1) elif choice == 1: oracle_circuit.cx(0, 1) oracle_circuit.x(1) # Constant oracle elif oracle == 1: if choice == 0: pass # qubit is already initialized to 0 elif choice == 1: oracle_circuit.x(1) # Turn oracle into single gate and append to qc oracle_gate = oracle_circuit.to_gate() qc.append(oracle_gate, [0, 1]) return qc def deutsch(oracle = None, choice = None): """ Create quantum circuit implementing Deutsch's algorithm. Parameters: ----------- oracle: int Type of oracle. 0 for balanced and 1 for constant. choice: int Choice of oracle type. For a balanced oracle, 0 will make f(x)=x and 1 will make f(x)=¬x. For a constant oracle, 0 will make f(x)=0 and 1 will make f(x)=1. NOTE: if any parameter is set to none (default), the value will be randomized. Returns: -------- qc: QuantumCircuit Quantum circuit implementing Deutsch's algorithm. """ # Randomize oracle and choice if not given if oracle == None: oracle = random.randint(0, 1) if choice == None: choice = random.randint(0, 1) qreg = QuantumRegister(2, 'q') creg = ClassicalRegister(1, 'c') qc = QuantumCircuit(qreg, creg) # Prepare initial state qc.x(qreg[1]) qc.barrier() # Put into superpusition qc.h(qreg) qc.barrier() # Add oracle d_oracle(qc, oracle, choice) qc.barrier() # Apply interference qc.h(qreg[0]) qc.barrier() # Measure first qubit qc.measure(qreg[0], creg) # Return circuit return qc circ = deutsch() circ.draw() circ_balanced = deutsch(0) circ_constant = deutsch(1) # We will let the choice be random for both circuits IBMQ.save_account(f"{config.IBM_KEY}", overwrite = True) IBMQ.load_account() backend = Aer.get_backend('qasm_simulator') # Uncomment below to run on hardware # provider = IBMQ.get_provider(hub='ibm-q') # backend = least_busy(provider.backends()) result = execute(circ_balanced, backend, shots=1024).result() count_b = result.get_counts(circ_balanced) plot_histogram(count_b) backend = Aer.get_backend('qasm_simulator') # Uncomment below to run on hardware # provider = IBMQ.get_provider(hub='ibm-q') # backend = least_busy(provider.backends()) result = execute(circ_constant, backend, shots=1024).result() count_c = result.get_counts(circ_constant) plot_histogram(count_c) def dj_oracle(qc, n, oracle, choice, to_gate=True): """ Add oracle for Deutsch-Jozsa algoritm, in the form of a gate, to quantum circuit. Parameters: ----------- qc: QuantumCircuit Quantum circuit with n+1 qubits. n: int Number of qubits in first register. n-input to Deutsch-Jozsa. Should be one less that the total size of the circuit. oracle: int Type of oracle. 0 for balanced and 1 for constant. choice: int Choice of oracle type. For a balanced oracle, this parameter is irrelevant. For a constant oracle, 0 will make f(x)=0 and 1 will make f(x)=1. to_gate: bool If true, the oracle will be added as a gate to the original circuit. If false, the individual gates will be added to the original circuit. Returns: -------- qc: QuantumCircuit Quantum circuit with Deutsch-Jozsa oracle added at the end. """ qc_len = 0 for qr in qc.qregs: qc_len += len(qr) if qc_len != n + 1: raise Exception(('Length of oracle and circuit given do not match correctly.' ' Parameter n should be one less than number of qubits in parameter qc.')) if to_gate: qreg_input = QuantumRegister(n, 'x') qreg_output = QuantumRegister(1, 'y') oracle_circuit = QuantumCircuit(qreg_input, qreg_output, name='$U_f$') # Balanced oracle if oracle == 0: for i in range(n): oracle_circuit.cx(qreg_input[i], qreg_output) # Constant oracle elif oracle == 1: if choice == 0: pass # y is already initialized to 0 elif choice == 1: oracle_circuit.x(qreg_output) oracle_gate = oracle_circuit.to_gate() qc.append(oracle_gate, range(n+1)) else: # Balanced oracle if oracle == 0: for i in range(n): qc.cx(i, n) # Constant oracle elif oracle == 1: if choice == 0: pass # y is already initialized to 0 elif choice == 1: qc.x(n) return qc def deutsch_jozsa(n, oracle=None, choice=None, oracle_gate=True): """ Create quantum circuit implementing n-input Deutsch-Jozsa algorithm. Parameters: ----------- n: int Number of qubits in first register. n-input to Deutsch-Jozsa. Should be one less that the total size of the circuit. oracle: int Type of oracle. 0 for balanced and 1 for constant. choice: int Choice of oracle type. For a balanced oracle, this parameter is irrelevant. For a constant oracle, 0 will make f(x)=0 and 1 will make f(x)=1. oracle_gate: bool If true, the oracle will be added as a gate to the original circuit. If false, the individual gates enclosed by barriers will be added to the original circuit. Returns: -------- qc: QuantumCircuit Quantum circuit with Deutsch-Jozsa oracle added at the end. """ # Randomize oracle and choice if not given if oracle == None: oracle = random.randint(0, 1) if choice == None: choice = random.randint(0, 1) qreg_in = QuantumRegister(n, 'x') qreg_out = QuantumRegister(1, 'y') creg = ClassicalRegister(n, 'c') qc = QuantumCircuit(qreg_in, qreg_out, creg) # Prepare initial state qc.x(qreg_in) qc.barrier() # Put into superpusition qc.h(range(n+1)) qc.barrier() # Add oracle dj_oracle(qc, n, oracle, choice, oracle_gate) qc.barrier() # Apply interference qc.h(qreg_in) qc.barrier() # Measure first qubit qc.measure(qreg_in, creg) return qc qc = deutsch_jozsa(3, oracle=0, oracle_gate=False) qc.draw() backend = Aer.get_backend('qasm_simulator') # Uncomment below to run on hardware # provider = IBMQ.get_provider(hub='ibm-q') # backend = least_busy(provider.backends()) result = execute(qc, backend, shots=1024).result() counts = result.get_counts(qc) plot_histogram(counts)
https://github.com/epelaaez/QuantumLibrary
epelaaez
from qiskit import QuantumCircuit import numpy as np def sim_z(t, qc, qubits): """ Add gates to simulate a Pauli Z string exponential Parameters: t: float Time parameter to simulate for qc: QuantumCircuit Circuit to append gates to qubits: array Array indicating qubits indeces (in order) to append the gates to """ for i in range(len(qubits) - 1): qc.cx(qubits[i], qubits[i + 1]) qc.rz(-2 * t, qubits[-1]) for i in range(len(qubits) - 1, 0, -1): qc.cx(qubits[i - 1], qubits[i]) qc = QuantumCircuit(3) sim_z(np.pi, qc, [0, 1, 2]) qc.draw() def sim_pauli(arr, t, qc, qubits): """ Append gates to simulate any Pauli string Parameters: arr: array Array encoding the Pauli string t: float Time parameter to simulate for qc: QuantumCircuit Circuit to append gates to qubits: array Array indicating qubits indeces (in order) to append the gates to """ new_arr = [] new_qub = [] for idx in range(len(arr)): if arr[idx] != 'I': new_arr.append(arr[idx]) new_qub.append(qubits[idx]) h_y = 1 / np.sqrt(2) * np.array([[1, -1j], [1j, -1]]) for i in range(len(new_arr)): if new_arr[i] == 'X': qc.h(new_qub[i]) elif new_arr[i] == 'Y': qc.unitary(h_y, [new_qub[i]], r'$H_y$') sim_z(t, qc, new_qub) for i in range(len(new_arr)): if new_arr[i] == 'X': qc.h(new_qub[i]) elif new_arr[i] == 'Y': qc.unitary(h_y, [new_qub[i]], r'$H_y$') def sim_ham(hamiltonian, t, qc, qubits, trotter=1): """ Simulates Hamiltonian given as Pauli string Parameters: hamiltonian: dict Dictionary encoding the hamiltonian with each Pauli product as a key with the coefficient as value t: float Time parameter to simulate for qc: QuantumCircuit Circuit to append gates to qubits: array Array indicating qubits indeces (in order) to append the gates to """ temp = QuantumCircuit(len(qubits)) delta_t = t / trotter for pauli in hamiltonian: sim_pauli(pauli, hamiltonian[pauli] * delta_t, temp, range(len(qubits))) for i in range(trotter): qc.compose(temp, qubits, inplace=True) qc = QuantumCircuit(3) sim_ham({"XZY": 2, "ZXX": 5, "YXZ": 2}, 1 / (2 * np.pi), qc, [0, 1, 2], trotter=1) qc = qc.reverse_bits() # reverse because of Qiskit's endianness qc.draw() from qiskit import Aer, execute from sympy import Matrix qc = QuantumCircuit(3) sim_ham({"XZY": 2, "ZXX": 5, "YXZ": 2}, 1 / (2 * np.pi), qc, [0, 1, 2], trotter=50) qc = qc.reverse_bits() backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() vec = result.get_statevector() vec = vec / vec[0] # global phase qvec = vec / np.linalg.norm(vec) # normalize Matrix(np.round(qvec, 5)) import scipy # Start with |0> state start = np.zeros(2 ** 3) start[0] = 1 # Get the matrix corresponding to some Pauli product # This function can be optimized, but it is left as it # is for clarity purposes def get_pauli(string): init = string[0] string = string[1:] if init == 'X': out = np.array([[0, 1], [1, 0]]) elif init == 'Z': out = np.array([[1, 0], [0, -1]]) elif init == 'Y': out = np.array([[0, -1j], [1j, 0]]) else: out = np.eye(2) for p in string: if p == 'X': out = np.kron(out, np.array([[0, 1], [1, 0]])) elif p == 'Z': out = np.kron(out, np.array([[1, 0], [0, -1]])) elif p == 'Y': out = np.kron(out, np.array([[0, -1j], [1j, 0]])) else: out = np.kron(out, np.eye(2)) return out # Hamiltonian is calculated from the Pauli decomposition decomp = {"XZY": 2, "ZXX": 5, "YXZ": 2} H = np.zeros((2 ** 3, 2 ** 3)) H = H.astype('complex128') for pauli in decomp: H += decomp[pauli] * get_pauli(pauli) # Hamiltonian is exponentiated and we multiply the starting # vector by it to get our result simul = scipy.linalg.expm(1j * H * (1 / (2 * np.pi))) vec = simul @ start vec = vec / vec[0] # global phase cvec = vec / np.linalg.norm(vec) # normalize Matrix(np.round(cvec, 5)) from qiskit.quantum_info import state_fidelity state_fidelity(qvec, cvec)
https://github.com/epelaaez/QuantumLibrary
epelaaez
from qiskit import QuantumCircuit, Aer, execute from math import pi import numpy as np from qiskit.visualization import plot_bloch_multivector, plot_histogram qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.cx(0,1) qc.draw() statevector_backend = Aer.get_backend('statevector_simulator') final_state = execute(qc,statevector_backend).result().get_statevector() print(final_state) plot_bloch_multivector(final_state) qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.z(1) qc.draw() final_state = execute(qc,statevector_backend).result().get_statevector() print(final_state) plot_bloch_multivector(final_state) qc.cx(0,1) qc.draw() final_state = execute(qc,statevector_backend).result().get_statevector() print(final_state) plot_bloch_multivector(final_state) qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.cx(0,1) qc.h(0) qc.h(1) display(qc.draw()) # `display` is an IPython tool, remove if it cases an error unitary_backend = Aer.get_backend('unitary_simulator') unitary = execute(qc,unitary_backend).result().get_unitary() print(unitary) qc = QuantumCircuit(2) qc.cx(1,0) display(qc.draw()) unitary_backend = Aer.get_backend('unitary_simulator') unitary = execute(qc,unitary_backend).result().get_unitary() print(unitary)
https://github.com/epelaaez/QuantumLibrary
epelaaez
import numpy as np from qiskit import Aer from qiskit.algorithms import Shor import matplotlib.pyplot as plt x = np.linspace(start=0, stop=29, num=30) plt.plot(x, (3**x) % 20, 'x--', linewidth=1) plt.xlabel('x', fontsize=10) plt.ylabel('$3^x$ mod 20', fontsize=10) plt.grid(visible=True) plt.show() backend = Aer.get_backend('qasm_simulator') shors = Shor(backend) qc = shors.construct_circuit(N=3, measurement=True) qc.draw() shors.factor(N=3).factors qc = shors.construct_circuit(N=15, measurement=True) qc.draw() shors.factor(N=15).factors qc = shors.construct_circuit(N=35, measurement=True) print('Number of qubits:', qc.num_qubits, '\nGate operations:', qc.size(), '\nDepth:', qc.depth()) shors.factor(N=35).factors
https://github.com/epelaaez/QuantumLibrary
epelaaez
def dswap_test_circuit(qc1: QuantumCircuit, qc2: QuantumCircuit) -> QuantumCircuit: """ Construct the destructive SWAP test circuit given two circuits. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Helper variables n_total = qc1.num_qubits + qc2.num_qubits range_qc1 = [i for i in range(qc1.num_qubits)] range_qc2 = [i + qc1.num_qubits for i in range(qc2.num_qubits)] # Constructing the SWAP test circuit qc_swap = QuantumCircuit(n_total , n_total) qc_swap.append(qc1, range_qc1) qc_swap.append(qc2, range_qc2) for index, qubit in enumerate(range_qc1): qc_swap.cx(qubit, range_qc2[index]) qc_swap.h(qubit) for index, qubit in enumerate(range_qc1): qc_swap.measure(qubit, 2*index) for index, qubit in enumerate(range_qc2): qc_swap.measure(range_qc2[index] , 2*index + 1) return qc_swap import textwrap import qiskit from qiskit import QuantumCircuit, execute from typing import Union from qiskit.aqua import QuantumInstance from qiskit.providers import BaseBackend def measure_dswap_test(qc1: QuantumCircuit, qc2: QuantumCircuit, backend: Union[BaseBackend,QuantumInstance], num_shots: int=10000) -> float: """Returns the fidelity from a destructive SWAP test. Args: qc1 (QuantumCircuit): Quantum Circuit for the first state. qc2 (QuantumCircuit): Quantum Circuit for the second state. backend (Union[BaseBackend,QuantumInstance]): Backend. num_shots (int, optional): Number of shots. Defaults to 10000. Returns: float: result of the overlap betweeen the first and second state. """ n = qc1.num_qubits swap_circuit = dswap_test_circuit(qc1, qc2) # Check if the backend is a quantum instance. if qiskit.aqua.quantum_instance.QuantumInstance == type(backend): count = backend.execute(swap_circuit).get_counts() else: count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts() result = 0 for meas, counts in count.items(): split_meas = textwrap.wrap(meas, 2) for m in split_meas: if m == '11': result -= counts else: result += counts total = sum(count.values()) return result/(n*total) from qiskit import QuantumCircuit, execute qc1 = QuantumCircuit(n) qc2 = QuantumCircuit(n) backend = BasicAer.get_backend('qasm_simulator') measure_dswap_test(qc1, qc2, backend) from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') num_shots = 10000 count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts() import textwrap result = 0 for meas, counts in count.items(): split_meas = textwrap.wrap(meas, 2) for m in split_meas: if m == '11': result -= counts else: result += counts total = sum(count.values()) result/(n*total)
https://github.com/epelaaez/QuantumLibrary
epelaaez
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.extensions import Initialize from qiskit.ignis.verification import marginal_counts from qiskit.quantum_info import random_statevector # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## SETUP # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical bits crx = ClassicalRegister(1, name="crx") # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a,b) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): """Measures qubits a & b and 'sends' the results to Bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) measure_and_send(teleportation_circuit, 0 ,1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) ## STEP 3 measure_and_send(teleportation_circuit, 0, 1) ## STEP 4 teleportation_circuit.barrier() # Use barrier to separate steps bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() # Create random 1-qubit state psi = random_statevector(2) # Display it nicely display(array_to_latex(psi, prefix="|\\psi\\rangle =")) # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) # Display the circuit qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() plot_bloch_multivector(out_vector)
https://github.com/epelaaez/QuantumLibrary
epelaaez
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=4 max_qubits=15 #reference files are upto 12 Qubits only skip_qubits=2 max_circuits=3 num_shots=4092 gate_counts_plots = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute from qiskit.opflow import PauliTrotterEvolution, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp import time,os,json import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "VQE Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits for display QC_ = None Hf_ = None CO_ = None ################### Circuit Definition ####################################### # Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz # param: n_spin_orbs - The number of spin orbitals. # return: return a Qiskit circuit for this VQE ansatz def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}") # initialize the HF state Hf = HartreeFock(num_qubits, na, nb) qc.append(Hf, qr) # form the list of single and double excitations excitationList = [] for occ_a in range(na): for vir_a in range(na, norb_a): excitationList.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index]) # add to ansatz qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)]) # method 1, only compute the last term in the Hamiltonian if method == 1: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] global normalization normalization = 0.0 # add the first non-identity term identity_qc = qc.copy() identity_qc.measure_all() qc_list.append(identity_qc) # add to circuit list diag.append(qubit_op[1]) normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms # loop over rest of terms for index, p in enumerate(qubit_op[2:]): # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # accumulate normalization normalization += abs(p.coeffs[0]) # add to circuit list if non-diagonal if not is_diag: qc_list.append(qc_with_mea) else: diag_coeff += abs(p.coeffs[0]) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) # modify the name of diagonal circuit qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff)) normalization /= len(qc_list) return qc_list # Function that constructs the circuit for a given cluster operator def ClusterOperatorCircuit(pauli_op, excitationIndex): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}' global CO_ if CO_ == None or qc.num_qubits <= 4: if qc.num_qubits < 7: CO_ = qc # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=2): # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) # save circuit global QC_ if QC_ == None or nqubit <= 4: if nqubit < 7: QC_ = raw_qc return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb, name="Hf") # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # Save smaller circuit global Hf_ if Hf_ == None or norb <= 4: if norb < 7: Hf_ = qc # return the circuit return qc ################ Helper Functions # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(f'ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(f'Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(qc,references,num_qubits): # total circuit name (pauli string + coefficient) total_name = qc.name # pauli string pauli_string = total_name.split()[0] # get the correct measurement if (len(total_name.split()) == 2): correct_dist = references[pauli_string] else: circuit_id = int(total_name.split()[2]) correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"] return correct_dist,total_name # Max qubits must be 12 since the referenced files only go to 12 qubits MAX_QUBITS = 12 method = 1 def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2, max_circuits=max_circuits, num_shots=num_shots): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() max_qubits = max(max_qubits, min_qubits) # max must be >= min # validate parameters (smallest circuit is 4 qubits and largest is 10 qubits) max_qubits = min(max_qubits, MAX_QUBITS) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) if method == 2: max_circuits = 1 if max_qubits < 4: print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm") return global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for input_size in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine the number of circuits to execute for this group num_circuits = min(3, max_circuits) num_qubits = input_size fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # random seed np.random.seed(0) numckts.append(num_circuits) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # Method 1 (default) if method == 1: # loop over circuits for circuit_id in range(num_circuits): # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) # method 2 elif method == 2: # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) print(qc_list) print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}") for qc in qc_list: print("*********************************************") #print(f"qc of {qc} qubits for qc_list value: {qc_list}") # get circuit id if method == 1: circuit_id = qc.name.split()[2] else: circuit_id = qc.name.split()[0] #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value print("operations: ",operations) algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() # load pre-computed data if len(qc.name.split()) == 2: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json') with open(filename) as f: references = json.load(f) else: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json') with open(filename) as f: references = json.load(f) #Correct distribution to compare with counts correct_dist,total_name = analyzer(qc,references,num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) print(fidelity_dict) # modify fidelity based on the coefficient if (len(total_name.split()) == 2): fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization ) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!") print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/epelaaez/QuantumLibrary
epelaaez
!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/epelaaez/QuantumLibrary
epelaaez
# To clean enviroment variables %reset import numpy as np import pandas as pd import folium import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit_algorithms import SamplingVQE from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler df = pd.read_csv("uscities.csv") columnsNeeded = ["city", "lat", "lng"] # Inicialization of variables locationsNumber = 15 # OJO que en local me crashea si sobrepaso 5 coordenatesDf = df[columnsNeeded].iloc[:locationsNumber] n = coordenatesDf.shape[0] # number of nodes + depot (n+1) K = 3 # number of vehicles print(coordenatesDf) # Initialize instance values by calculate the squared Euclidean distances between a set of coordinates # represented in the dataframe. def generate_instance(coordenatesDf): n = coordenatesDf.shape[0] xc = coordenatesDf["lat"] yc = coordenatesDf["lng"] loc = coordenatesDf["city"] instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance, loc # Initialize the problem by randomly generating the instance lat, lng, instance, loc = generate_instance(coordenatesDf) print(lat, lng, loc, instance) #print(instance) class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 #vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) #optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) print(qp) #quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) print(classical_cost) m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m print(quantum_cost) x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x_quantum[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m algorithms = ("Classic", "Quantum") data = { 'K = 1': (2249.2068134000006, 1706.2245994000696), 'k = 2': (2771.940853740001, 1845.127222779207), 'K = 3': (3981.1556002800016, 3981.155600280501), } x = np.arange(len(algorithms)) # the label locations width = 0.25 # the width of the bars multiplier = 0 fig, ax = plt.subplots(layout='constrained') for attribute, measurement in data.items(): offset = width * multiplier rects = ax.bar(x + offset, measurement, width, label=attribute) ax.bar_label(rects, padding=3) multiplier += 1 # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Length (mm)') ax.set_title('Comparision of Quantum and Classical Cost') ax.set_xticks(x + width, algorithms) ax.legend(loc='upper left', ncols=3) ax.set_ylim(0, 5000) plt.show()
https://github.com/epelaaez/QuantumLibrary
epelaaez
from qiskit import QuantumCircuit, execute, Aer from qiskit.opflow import One, Zero, Plus, Minus from qiskit.opflow import I, X, Y, Z, S, H from qiskit.visualization import plot_bloch_multivector, plot_bloch_vector, plot_histogram from math import pi, sqrt, acos, asin, e, log, sin, cos from numpy import angle Zero One Plus Minus 1.5 * Zero -3 * Plus Zero^Zero^One Plus^Minus^Zero^Zero Zero + One Plus + Minus (Zero^Zero^One) + (Zero^One^Zero) + (One^Zero^Zero) (Zero^Zero^One) - 1.5*(Zero^One^Zero) + 3*(One^Zero^Zero) def arbitrary_state(beta): ##### ================================== # Write your solution in here. ##### ================================== Zero.eval('0') Zero.eval('1') Minus.eval('0') Minus.eval('1') ~Zero ~One ~Plus print("< 0 | 0 > =",(~Zero @ Zero).eval()) print("< 1 | 0 > =",(~One @ Zero).eval()) beta = 0.232 + 0.341j arbitrary_state(beta) beta = 0.232 + 0.341j print("< 1 | Ψ > =",(~One @ arbitrary_state(beta)).eval()) print("< 0 | Ψ > =",(~Zero @ arbitrary_state(beta)).eval()) print("< Ψ | Ψ > =", (~arbitrary_state(beta) @ arbitrary_state(beta)).eval()) def normality_check(beta): ##### ================================== # Write your solution in here. ##### ================================== # Play with your beta parameter to see if this value changes. beta = 0.232 + 0.341j print("|< 1 | Ψ >|^2 + |< 0 | Ψ >|^2 =", normality_check(beta)) def convert_braket_to_Bloch(beta): if beta == 0: # special case return [1.0, 0, 0] ##### ================================== # Write your solution in here. ##### ================================== return [1.0, theta, phi] # Check beta = -1/sqrt(2)*1j plot_bloch_vector(convert_braket_to_Bloch(beta), coord_type='spherical', title=r"$|\psi\rangle = \frac{1}{\sqrt{2}}|0\rangle-\frac{1}{\sqrt{2}}i|0\rangle$") # Play with more values of beta to see if it matches with your expectation beta = -1/sqrt(10)*1j plot_bloch_vector(convert_braket_to_Bloch(beta), coord_type='spherical', title=r"$|\psi\rangle = \sqrt{1-|\beta|^2}|0\rangle+\beta|0\rangle$ in Spherical") X Y Z def expectation_Z(beta): ##### ================================== # Write your solution in here. There are more than one solution here... ##### ================================== print("<Z> =", expectation_Z(beta)) def expectation_X(beta): ##### ================================== # Write your solution in here. There are more than one solution here... ##### ================================== def expectation_Y(beta): ##### ================================== # Write your solution in here. There are more than one solution here... ##### ================================== def get_cartesian_coordinate(beta): ##### ================================== # Write your solution in here. There are more than one solution here... ##### ================================== return [x, y, z] # Play with more values of beta to see if it matches with your previous Bloch sphere beta = -1/sqrt(10)*1j plot_bloch_vector(get_cartesian_coordinate(beta), coord_type='cartesian', title=r"$|\psi\rangle = \sqrt{1-|\beta|^2}|0\rangle+\beta|0\rangle$ in Cartesian") # Let's define the quantum simulator sv_simulator = Aer.get_backend("statevector_simulator") qasm_simulator = Aer.get_backend("qasm_simulator") this_circ = QuantumCircuit(1) this_circ.initialize([1/sqrt(2), -1/sqrt(2)]) this_circ.measure_all() this_circ.draw('mpl') shots = 1024 counts = execute(this_circ, backend=qasm_simulator, shots=shots).result().get_counts() print(counts) plot_histogram(counts, title=r"Measuring the $|+\rangle$ state") def contruct_arbitrary_state_on_circuit(beta): ##### ================================== # Write your solution in here. Here you do not need to append the measurement part in this function ##### ================================== return circuit shots = 81920 beta = 0.213 this_circuit = contruct_arbitrary_state_on_circuit(beta) this_circuit.measure_all() counts = execute(this_circuit, backend=qasm_simulator, shots=shots).result().get_counts() print("Probability in |1> basis =", beta**2) plot_histogram(counts, title=r"Measuring the arbitrary $|\psi(\beta)\rangle$ state") def expectation_Z_with_QASM(beta, shots): ##### ================================== # Write your solution in here. Here ##### ================================== return expectation beta = -1/sqrt(2)*1j shots = 81920 print("Expectation <Z> with QASM =", expectation_Z_with_QASM(beta, shots=shots)) print("Expectation <Z> with opflow =", expectation_Z(beta)) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/epelaaez/QuantumLibrary
epelaaez
# To clean enviroment variables %reset import numpy as np import pandas as pd import folium import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit_algorithms import SamplingVQE from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler df = pd.read_csv("uscities.csv") columnsNeeded = ["city", "lat", "lng"] # Inicialization of variables locationsNumber = 15 # OJO que en local me crashea si sobrepaso 5 coordenatesDf = df[columnsNeeded].iloc[:locationsNumber] n = coordenatesDf.shape[0] # number of nodes + depot (n+1) K = 3 # number of vehicles print(coordenatesDf) # Initialize instance values by calculate the squared Euclidean distances between a set of coordinates # represented in the dataframe. def generate_instance(coordenatesDf): n = coordenatesDf.shape[0] xc = coordenatesDf["lat"] yc = coordenatesDf["lng"] loc = coordenatesDf["city"] instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance, loc # Initialize the problem by randomly generating the instance lat, lng, instance, loc = generate_instance(coordenatesDf) print(lat, lng, loc, instance) #print(instance) class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 #vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) #optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) print(qp) #quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) print(classical_cost) m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m print(quantum_cost) x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x_quantum[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m algorithms = ("Classic", "Quantum") data = { 'K = 1': (2249.2068134000006, 1706.2245994000696), 'k = 2': (2771.940853740001, 1845.127222779207), 'K = 3': (3981.1556002800016, 3981.155600280501), } x = np.arange(len(algorithms)) # the label locations width = 0.25 # the width of the bars multiplier = 0 fig, ax = plt.subplots(layout='constrained') for attribute, measurement in data.items(): offset = width * multiplier rects = ax.bar(x + offset, measurement, width, label=attribute) ax.bar_label(rects, padding=3) multiplier += 1 # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Length (mm)') ax.set_title('Comparision of Quantum and Classical Cost') ax.set_xticks(x + width, algorithms) ax.legend(loc='upper left', ncols=3) ax.set_ylim(0, 5000) plt.show()
https://github.com/epelaaez/QuantumLibrary
epelaaez
import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_bloch_multivector, array_to_latex from grader import * language(False) phi_plus = QuantumCircuit(2) phi_plus.h(0) phi_plus.cnot(0, 1) phi_plus.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') result = execute(phi_plus, backend).result().get_statevector() array_to_latex(result) phi_minus = QuantumCircuit(2) ##### ================================== # Write your solution in here. ##### ================================== phi_minus.draw('mpl') # This cell will tell you if what you did gives the correct result. # Just take it as an indication, the tests do not take into consideration every possible option # If you think that your answer is (in)correct and the grader says different, just ask me please # Don't try to tamper with the code, please :) ex1_grader(phi_minus) psi_plus = QuantumCircuit(2) ##### ================================== # Write your solution in here. ##### ================================== psi_plus.draw('mpl') ex2_grader(psi_plus) psi_minus = QuantumCircuit(2) ##### ================================== # Write your solution in here. ##### ================================== psi_minus.draw('mpl') ex3_grader(psi_minus) GHZ = QuantumCircuit(3) ##### ================================== # Write your solution in here. ##### ================================== GHZ.draw('mpl') ex4_grader(GHZ) Even = QuantumCircuit(3) ##### ================================== # Write your solution in here. ##### ================================== Even.draw('mpl') ex5_grader(Even) Odd = QuantumCircuit(3) ##### ================================== # Write your solution in here. ##### ================================== Odd.draw('mpl') ex6_grader(Odd) def measure_z_axis(qc, qubit, cbit): #Measurements have to be saved in classical bits qc.measure(qubit, cbit) def measure_x_axis(qc, qubit, cbit): ##### ================================== # Write your solution in here. ##### ================================== ex7_grader(measure_x_axis) def expectation_value_single_qubit(qc, nshots=8092): # Run the given circuit that is already measuring the selected basis backend_shots = Aer.get_backend('qasm_simulator') counts = execute(qc, backend_shots, shots=nshots).result().get_counts() #Counts is a dictionary that contains the number of zeros and the number of ones measured # This is just to make things easier in your solution if '1' not in counts.keys(): counts['1'] = 0 if '0' not in counts.keys(): counts['0'] = 0 # Get the number of times that 0 and 1 were measured n_zeros = counts['0'] n_ones = counts['1'] # Compute the probabilities p_0 = n_zeros/nshots p_1 = n_ones/nshots #OR 1-p_0 expectation_value = 1*p_0+(-1)*p_1 return expectation_value # Measure <Z> over a state that you like qc_z = QuantumCircuit(1,1) measure_z_axis(qc_z, 0, 0) print('<Z>=', expectation_value_single_qubit(qc_z)) qc_z.draw('mpl') # Measure <X> over a state that you like qc_x = QuantumCircuit(1,1) measure_x_axis(qc_x, 0, 0) print('<X>=', expectation_value_single_qubit(qc_x)) qc_x.draw('mpl') ##### ================================== # Write your solution in here. # Create bell state circuit # For each of the operators that we want to measure (ZZ, ZX, XZ and XX) create a new circuit (maybe using qc.copy()) # that measures along that axis. chsh_circuits = [] ##### ================================== chsh_circuits[0].draw('mpl') chsh_circuits[1].draw('mpl') chsh_circuits[2].draw('mpl') chsh_circuits[3].draw('mpl') # I couldn't come up with tests that would not give the answer away if you looked at the code so you are on your own here! # We can run all the circuits at the same time and then post process the data nshots = 8092 # The more shots, the less error backend_shots = Aer.get_backend('qasm_simulator') counts_list = execute(chsh_circuits, backend_shots, shots=nshots).result().get_counts() counts_list ##### ================================== # Write your solution in here. # For each of the circuits, take the counts that you got from that circuit, compute the probability # of each state and combine them together being very careful of which sign goes with which term # You might want to take some inspiration from the function expectation_value_single_qubit # If you are completely lost and don't know how to solve this, just ask ##### ================================== # If you don't know if your answer is correct you can compute the results by hand # (it's probably easier than doing this) and check if everything is working ##### ================================== # Write your solution in here. exp_AB = exp_Ab = exp_aB = exp_ab = CHSH = ##### ================================== print('Your result is <CHSH>=', CHSH) print('The correct result is <CHSH>=', 2*np.sqrt(2)) ##### ================================== # Write your solution in here. Can_entanglement_be_teleported = #Write True or False :D ##### ================================== # There is no grader for this question hehe ##### ================================== # Write your solution in here. Where_did_the_bell_pair_go = 'Write where you think they went' ##### ================================== # There is no grader for this question hehe ##### ================================== # Write your solution in here. ##### ================================== import qiskit.tools.jupyter %qiskit_version_table
https://github.com/epelaaez/QuantumLibrary
epelaaez
# To clean enviroment variables %reset import numpy as np import pandas as pd import folium import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit_algorithms import SamplingVQE from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler df = pd.read_csv("uscities.csv") columnsNeeded = ["city", "lat", "lng"] # Inicialization of variables locationsNumber = 15 # OJO que en local me crashea si sobrepaso 5 coordenatesDf = df[columnsNeeded].iloc[:locationsNumber] n = coordenatesDf.shape[0] # number of nodes + depot (n+1) K = 3 # number of vehicles print(coordenatesDf) # Initialize instance values by calculate the squared Euclidean distances between a set of coordinates # represented in the dataframe. def generate_instance(coordenatesDf): n = coordenatesDf.shape[0] xc = coordenatesDf["lat"] yc = coordenatesDf["lng"] loc = coordenatesDf["city"] instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance, loc # Initialize the problem by randomly generating the instance lat, lng, instance, loc = generate_instance(coordenatesDf) print(lat, lng, loc, instance) #print(instance) class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 #vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) #optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) print(qp) #quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) print(classical_cost) m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m print(quantum_cost) x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x_quantum[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m algorithms = ("Classic", "Quantum") data = { 'K = 1': (2249.2068134000006, 1706.2245994000696), 'k = 2': (2771.940853740001, 1845.127222779207), 'K = 3': (3981.1556002800016, 3981.155600280501), } x = np.arange(len(algorithms)) # the label locations width = 0.25 # the width of the bars multiplier = 0 fig, ax = plt.subplots(layout='constrained') for attribute, measurement in data.items(): offset = width * multiplier rects = ax.bar(x + offset, measurement, width, label=attribute) ax.bar_label(rects, padding=3) multiplier += 1 # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Length (mm)') ax.set_title('Comparision of Quantum and Classical Cost') ax.set_xticks(x + width, algorithms) ax.legend(loc='upper left', ncols=3) ax.set_ylim(0, 5000) plt.show()
https://github.com/epelaaez/QuantumLibrary
epelaaez
# Import helper module from local folder import sys import os sys.path.append(os.getcwd()) from resources import helper # Numerical and plotting tools import numpy as np import matplotlib.pyplot as plt # Import SI unit conversion factors from resources.helper import GHz, MHz, kHz, us, ns # Importing standard Qiskit libraries from qiskit import IBMQ from qiskit.tools.jupyter import * # Loading your IBM Quantum account IBMQ.load_account() IBMQ.providers() # see a list of providers you have access to # Get the special provider assigned to you using information from the output above hub_name = 'iqc2021-1' # e.g. 'iqc2021-1' group_name = 'challenge-26' # e.g. 'challenge-1' project_name = 'ex4' # Your project name should be 'ex4' provider = IBMQ.get_provider(hub=hub_name, group=group_name, project=project_name) # Get `ibmq_jakarta` backend from the provider backend_name = 'ibmq_jakarta' backend = provider.get_backend(backend_name) backend # See details of the `ibmq_jakarta` quantum system from qiskit import pulse from qiskit.pulse import Play, Schedule, DriveChannel # Please use qubit 0 throughout the notebook qubit = 0 backend_config = backend.configuration() exc_chans = helper.get_exc_chans(globals()) dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() center_frequency = backend_defaults.qubit_freq_est inst_sched_map = backend_defaults.instruction_schedule_map inst_sched_map.instructions # Retrieve calibrated measurement pulse from backend meas = inst_sched_map.get('measure', qubits=[qubit]) meas.exclude(channels=exc_chans).draw(time_range=[0,1000]) from qiskit.pulse import DriveChannel, Gaussian # The same spec pulse for both 01 and 12 spec drive_amp = 0.25 drive_duration = inst_sched_map.get('x', qubits=[qubit]).duration # Calibrated backend pulse use advanced DRAG pulse to reduce leakage to the |2> state. # Here we will use simple Gaussian pulse drive_sigma = drive_duration // 4 # DRAG pulses typically 4*sigma long. spec_pulse = 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 = helper.get_spec01_freqs(center_frequency, qubit) # Create the base schedule # Start with drive pulse acting on the drive channel spec01_scheds = [] for freq in spec_freqs_GHz: with pulse.build(name="Spec Pulse at %.3f GHz" % freq) as spec01_sched: with pulse.align_sequential(): # Pay close attention to this part to solve the problem at the end pulse.set_frequency(freq*GHz, DriveChannel(qubit)) pulse.play(spec_pulse, DriveChannel(qubit)) pulse.call(meas) spec01_scheds.append(spec01_sched) # Draw spec01 schedule spec01_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000]) from qiskit.tools.monitor import job_monitor # Run the job on a real backend spec01_job = backend.run(spec01_scheds, job_name="Spec 01", **helper.job_params) print(spec01_job.job_id()) job_monitor(spec01_job) # If the queuing time is too long, you can save the job id # And retrieve the job after it's done # Replace 'JOB_ID' with your job id and uncomment to line below #spec01_job = backend.retrieve_job('JOB_ID') from resources.helper import SpecFitter amp_guess = 5e6 f01_guess = 5 B = 1 C = 0 fit_guess = [amp_guess, f01_guess, B, C] fit = SpecFitter(spec01_job.result(), spec_freqs_GHz, qubits=[qubit], fit_p0=fit_guess) fit.plot(0, series='z') f01 = fit.spec_freq(0, series='z') print("Spec01 frequency is %.6f GHz" % f01) # Retrieve qubit frequency from backend properties f01_calibrated = backend.properties().frequency(qubit) / GHz f01_error = abs(f01-f01_calibrated) * 1000 # error in MHz print("Qubit frequency error is %.6f MHz" % f01_error) max_rabi_amp = 0.75 rabi_amps = helper.get_rabi_amps(max_rabi_amp) rabi_scheds = [] for ridx, amp in enumerate(rabi_amps): with pulse.build(name="rabisched_%d_0" % ridx) as sched: # '0' corresponds to Rabi with pulse.align_sequential(): pulse.set_frequency(f01*GHz, DriveChannel(qubit)) rabi_pulse = Gaussian(duration=drive_duration, amp=amp, \ sigma=drive_sigma, name=f"Rabi drive amplitude = {amp}") pulse.play(rabi_pulse, DriveChannel(qubit)) pulse.call(meas) rabi_scheds.append(sched) # Draw rabi schedule rabi_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000]) # Run the job on a real device rabi_job = backend.run(rabi_scheds, job_name="Rabi", **helper.job_params) print(rabi_job.job_id()) job_monitor(rabi_job) # If the queuing time is too long, you can save the job id # And retrieve the job after it's done # Replace 'JOB_ID' with the the your job id and uncomment to line below #rabi_job = backend.retrieve_job('JOB_ID') from qiskit.ignis.characterization.calibrations.fitters import RabiFitter amp_guess = 5e7 fRabi_guess = 2 phi_guess = 0.5 c_guess = 0 fit_guess = [amp_guess, fRabi_guess, phi_guess, c_guess] fit = RabiFitter(rabi_job.result(), rabi_amps, qubits=[qubit], fit_p0=fit_guess) fit.plot(qind=0, series='0') x180_amp = fit.pi_amplitude() print("Pi amplitude is %.3f" % x180_amp) # Define pi pulse x_pulse = Gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') def build_spec12_pulse_schedule(freq, anharm_guess_GHz): with pulse.build(name="Spec Pulse at %.3f GHz" % (freq+anharm_guess_GHz)) as spec12_schedule: with pulse.align_sequential(): # WRITE YOUR CODE BETWEEN THESE LINES - START pulse.play(x_pulse, DriveChannel(qubit)) pulse.set_frequency((freq+anharm_guess_GHz)*GHz, DriveChannel(qubit)) pulse.play(spec_pulse, DriveChannel(qubit)) pulse.call(meas) # WRITE YOUR CODE BETWEEN THESE LINES - END return spec12_schedule anharmonicity_guess_GHz = -0.3 # your anharmonicity guess freqs_GHz = helper.get_spec12_freqs(f01, qubit) # Now vary the sideband frequency for each spec pulse spec12_scheds = [] for freq in freqs_GHz: spec12_scheds.append(build_spec12_pulse_schedule(freq, anharmonicity_guess_GHz)) # Draw spec12 schedule spec12_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000]) # Run the job on a real device spec12_job = backend.run(spec12_scheds, job_name="Spec 12", **helper.job_params) print(spec12_job.job_id()) job_monitor(spec12_job) # If the queuing time is too long, you can save the job id # And retrieve the job after it's done # Replace 'JOB_ID' with the the your job id and uncomment to line below #spec12_job = backend.retrieve_job('JOB_ID') amp_guess = 2e7 f12_guess = f01 - 0.3 B = .1 C = 0 fit_guess = [amp_guess, f12_guess, B, C] fit = SpecFitter(spec12_job.result(), freqs_GHz+anharmonicity_guess_GHz, qubits=[qubit], fit_p0=fit_guess) fit.plot(0, series='z') f12 = fit.spec_freq(0, series='z') print("Spec12 frequency is %.6f GHz" % f12) # Check your answer using following code from qc_grader import grade_ex4 grade_ex4(f12,qubit,backend_name) # Submit your answer. You can re-submit at any time. from qc_grader import submit_ex4 submit_ex4(f12,qubit,backend_name) Ec = f01 - f12 Ej = (2*f01-f12)**2/(8*(f01-f12)) print(f"Ej/Ec: {Ej/Ec:.2f}") # This value is typically ~ 30
https://github.com/epelaaez/QuantumLibrary
epelaaez
from qiskit_nature.drivers import PySCFDriver molecule = "H .0 .0 .0; H .0 .0 0.739" driver = PySCFDriver(atom=molecule) qmolecule = driver.run() print('Number of electrons:', qmolecule.num_alpha + qmolecule.num_beta) print('Number of molecular orbitals:', qmolecule.num_molecular_orbitals) print('Number of spin-orbitals:', 2 * qmolecule.num_molecular_orbitals) print('Qubits to simulate with Jordan-Wigner:', 2 * qmolecule.num_molecular_orbitals) print('Nuclear repulsion energy:', qmolecule.nuclear_repulsion_energy) from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem problem = ElectronicStructureProblem(driver) # Generate the second-quantized operators second_q_ops = problem.second_q_ops() # Hamiltonian main_op = second_q_ops[0] from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter # Setup the mapper and qubit converter mapper_type = 'JordanWignerMapper' if mapper_type == 'ParityMapper': mapper = ParityMapper() elif mapper_type == 'JordanWignerMapper': mapper = JordanWignerMapper() elif mapper_type == 'BravyiKitaevMapper': mapper = BravyiKitaevMapper() converter = QubitConverter(mapper=mapper, two_qubit_reduction=False) # The fermionic operators are mapped to qubit operators num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) qubit_op = converter.convert(main_op, num_particles=num_particles) from qiskit_nature.circuit.library import HartreeFock num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals init_state = HartreeFock(num_spin_orbitals, num_particles, converter) print(init_state) from qiskit.circuit.library import TwoLocal from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD # Choose the ansatz ansatz_type = "Custom" # Parameters for q-UCC antatze num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals # Put arguments for twolocal if ansatz_type == "TwoLocal": # Single qubit rotations that are placed on all qubits with independent parameters rotation_blocks = ['ry', 'rz'] # Entangling gates entanglement_blocks = 'cx' # How the qubits are entangled entanglement = 'full' # Repetitions of rotation_blocks + entanglement_blocks with independent parameters repetitions = 3 # Skip the final rotation_blocks layer skip_final_rotation_layer = True ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions, entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer) # Add the initial state ansatz.compose(init_state, front=True, inplace=True) elif ansatz_type == "UCCSD": ansatz = UCCSD(converter,num_particles,num_spin_orbitals,initial_state = init_state) elif ansatz_type == "PUCCD": ansatz = PUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state) elif ansatz_type == "SUCCD": ansatz = SUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state) elif ansatz_type == "Custom": # Example of how to write your own circuit from qiskit.circuit import Parameter, QuantumCircuit, QuantumRegister n = qubit_op.num_qubits # Make an empty quantum circuit qc = QuantumCircuit(qubit_op.num_qubits) for i in range(2): thetas = [] for j in range(n): thetas.append(Parameter(f'a({i}{j})')) # Place a Hadamard gates qc.h([0,1,2,3]) # Place a CNOT ladder for i in range(n-1): qc.cx(i, i+1) # rz rotations on all qubits for k in range(n): qc.rz(thetas[k], k) qc.barrier() ansatz = qc ansatz.compose(init_state, front=True, inplace=True) ansatz.draw('mpl') from qiskit import Aer backend = Aer.get_backend('statevector_simulator') from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP optimizer_type = 'COBYLA' # You may want to tune the parameters # of each optimizer, here the defaults are used if optimizer_type == 'COBYLA': optimizer = COBYLA(maxiter=500) elif optimizer_type == 'L_BFGS_B': optimizer = L_BFGS_B(maxfun=500) elif optimizer_type == 'SPSA': optimizer = SPSA(maxiter=500) elif optimizer_type == 'SLSQP': optimizer = SLSQP(maxiter=500) from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver import numpy as np def exact_diagonalizer(problem, converter): solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(converter, solver) result = calc.solve(problem) return result result_exact = exact_diagonalizer(problem, converter) exact_energy = np.real(result_exact.eigenenergies[0]) print("Exact electronic energy", exact_energy) print(result_exact) # The targeted electronic energy for H2 is -1.85336 Ha # Check with your VQE result. from qiskit.algorithms import VQE from IPython.display import display, clear_output # Print and save the data in lists def callback(eval_count, parameters, mean, std): # Overwrites the same line when printing display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) counts = [] values = [] params = [] deviation = [] # Set initial parameters of the ansatz # We choose a fixed small displacement # So all participants start from similar starting point try: initial_point = [0.01] * len(ansatz.ordered_parameters) except: initial_point = [0.01] * ansatz.num_parameters algorithm = VQE(ansatz, optimizer=optimizer, quantum_instance=backend, callback=callback, initial_point=initial_point) result = algorithm.compute_minimum_eigenvalue(qubit_op) print(result) # Store results in a dictionary from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller # Unroller transpile your circuit into CNOTs and U gates pass_ = Unroller(['u', 'cx']) pm = PassManager(pass_) ansatz_tp = pm.run(ansatz) cnots = ansatz_tp.count_ops()['cx'] score = cnots accuracy_threshold = 4.0 # in mHa energy = result.optimal_value if ansatz_type == "TwoLocal": result_dict = { 'optimizer': optimizer.__class__.__name__, 'mapping': converter.mapper.__class__.__name__, 'ansatz': ansatz.__class__.__name__, 'rotation blocks': rotation_blocks, 'entanglement_blocks': entanglement_blocks, 'entanglement': entanglement, 'repetitions': repetitions, 'skip_final_rotation_layer': skip_final_rotation_layer, 'energy (Ha)': energy, 'error (mHa)': (energy-exact_energy)*1000, 'pass': (energy-exact_energy)*1000 <= accuracy_threshold, '# of parameters': len(result.optimal_point), 'final parameters': result.optimal_point, '# of evaluations': result.optimizer_evals, 'optimizer time': result.optimizer_time, '# of qubits': int(qubit_op.num_qubits), '# of CNOTs': cnots, 'score': score} else: result_dict = { 'optimizer': optimizer.__class__.__name__, 'mapping': converter.mapper.__class__.__name__, 'ansatz': ansatz.__class__.__name__, 'rotation blocks': None, 'entanglement_blocks': None, 'entanglement': None, 'repetitions': None, 'skip_final_rotation_layer': None, 'energy (Ha)': energy, 'error (mHa)': (energy-exact_energy)*1000, 'pass': (energy-exact_energy)*1000 <= accuracy_threshold, '# of parameters': len(result.optimal_point), 'final parameters': result.optimal_point, '# of evaluations': result.optimizer_evals, 'optimizer time': result.optimizer_time, '# of qubits': int(qubit_op.num_qubits), '# of CNOTs': cnots, 'score': score} # Plot the results import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.set_xlabel('Iterations') ax.set_ylabel('Energy') ax.grid() fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}\nScore: {score:.0f}') plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}") ax.plot(counts, values) ax.axhline(exact_energy, linestyle='--') fig_title = f"\ {result_dict['optimizer']}-\ {result_dict['mapping']}-\ {result_dict['ansatz']}-\ Energy({result_dict['energy (Ha)']:.3f})-\ Score({result_dict['score']:.0f})\ .png" fig.savefig(fig_title, dpi=300) # Display and save the data import pandas as pd import os.path filename = 'results_h2.csv' if os.path.isfile(filename): result_df = pd.read_csv(filename) result_df = result_df.append([result_dict]) else: result_df = pd.DataFrame.from_dict([result_dict]) result_df.to_csv(filename) result_df[['optimizer','ansatz', '# of qubits', '# of parameters','rotation blocks', 'entanglement_blocks', 'entanglement', 'repetitions', 'error (mHa)', 'pass', 'score']] # Question 1 # Question 2 ansatz = PUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state) # or ansatz = SUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state) # using SPSA optimizer = SPSA(maxiter=500) # Question 3 from qiskit.circuit import Parameter, QuantumCircuit, QuantumRegister n = qubit_op.num_qubits qc = QuantumCircuit(qubit_op.num_qubits) for i in range(2): thetas = [] for j in range(n): thetas.append(Parameter(f'a({i}{j})')) # Place a Hadamard gates qc.h([0,1,2,3]) # Place a CNOT ladder for i in range(n-1): qc.cx(i, i+1) # rz rotations on all qubits for k in range(n): qc.rz(thetas[k], k) qc.barrier() ansatz = qc # ansatz with 6 CNOTs => cost of 6 ansatz.draw('mpl') def getScore(ansatz): pass_ = Unroller(['u', 'cx']) pm = PassManager(pass_) ansatz_tp = pm.run(ansatz) cnots = ansatz_tp.count_ops()['cx'] print("Score:", cnots) from qiskit_nature.transformers import FreezeCoreTransformer molecule = 'Li 0.0 0.0 0.0; H 0.0 0.0 1.5474' driver = PySCFDriver(atom=molecule) qmolecule = driver.run() problem = ElectronicStructureProblem(driver, [FreezeCoreTransformer(remove_orbitals=[3,4])]) second_q_ops = problem.second_q_ops() # Second-quantized operators main_op = second_q_ops[0] # Hamiltonian mapper = ParityMapper() converter = QubitConverter(mapper=mapper, two_qubit_reduction=True, z2symmetry_reduction=[1,1]) num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) qubit_op = converter.convert(main_op, num_particles=num_particles) print("Number of qubits:", qubit_op.num_qubits) num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals init_state = HartreeFock(num_spin_orbitals, num_particles, converter) init_state.draw('mpl') n = qubit_op.num_qubits # Make an empty quantum circuit qc = QuantumCircuit(qubit_op.num_qubits) qc.barrier() for i in range(1): # Declare parameters thetas = [] betas = [] phis = [] for k in range(n): thetas.append(Parameter(f'x({i}{k})')) betas.append(Parameter(f'y({i}{k})')) phis.append(Parameter(f'z({i}{k})')) for m in range(n): qc.u(thetas[m], betas[m], phis[m], m) qc.cnot(0,1) qc.cnot(1,2) qc.cnot(2,3) for i in range(3): # Declare parameters thetas = [] betas = [] phis = [] for k in range(n): thetas.append(Parameter(f'a({i}{k})')) betas.append(Parameter(f'b({i}{k})')) phis.append(Parameter(f'c({i}{k})')) for m in range(n): qc.u(thetas[m], betas[m], phis[m], m) for i in range(2): # Declare parameters thetas = [] betas = [] phis = [] for k in range(n): thetas.append(Parameter(f'd({i}{k})')) betas.append(Parameter(f'e({i}{k})')) phis.append(Parameter(f'f({i}{k})')) for m in range(n): qc.rz(thetas[m], m) qc.ry(betas[m], m) qc.rz(phis[m], m) ansatz = qc ansatz.compose(init_state, front=True, inplace=True) getScore(ansatz) ansatz.draw('mpl') rotation_blocks = ['rz', 'ry', 'rz', 'ry'] entanglement_blocks = 'cx' entanglement = 'linear' repetitions = 1 skip_final_rotation_layer = False ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions, entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer) ansatz.compose(init_state, front=True, inplace=True) getScore(ansatz) ansatz.draw('mpl') optimizer_type = 'COBYLA' if optimizer_type == 'COBYLA': optimizer = COBYLA(maxiter=5000) elif optimizer_type == 'L_BFGS_B': optimizer = L_BFGS_B(maxfun=5000) elif optimizer_type == 'SPSA': optimizer = SPSA(maxiter=5000) elif optimizer_type == 'SLSQP': optimizer = SLSQP(maxiter=5000) def callback(eval_count, parameters, mean, std): # Overwrites the same line when printing display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) counts = [] values = [] params = [] deviation = [] # Set initial parameters of the ansatz # We choose a fixed small displacement # So all participants start from similar starting point try: initial_point = [0.01] * len(ansatz.ordered_parameters) except: initial_point = [0.01] * ansatz.num_parameters algorithm = VQE(ansatz, optimizer=optimizer, quantum_instance=backend, callback=callback, initial_point=initial_point) result = algorithm.compute_minimum_eigenvalue(qubit_op) print("Calculated eigenvalue:", result.eigenvalue) print("Optimizer evaluations:", result.optimizer_evals) def exact_diagonalizer(problem, converter): solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(converter, solver) result = calc.solve(problem) return result result_exact = exact_diagonalizer(problem, converter) exact_energy = np.real(result_exact.eigenenergies[0]) print("Exact electronic energy:", exact_energy) accuracy_threshold = 4.0 # in mHa energy = result.optimal_value print("Exact electronic energy:", exact_energy) print("Energy from VQE:", energy) print("Error:", (energy-exact_energy) * 1000) print("Pass:", (energy-exact_energy) * 1000 <= accuracy_threshold) # Check your answer using following code from qc_grader import grade_ex5 freeze_core = True # change to True if you freezed core electrons grade_ex5(ansatz,qubit_op,result,freeze_core) # Submit your answer. You can re-submit at any time. from qc_grader import submit_ex5 submit_ex5(ansatz,qubit_op,result,freeze_core)
https://github.com/epelaaez/QuantumLibrary
epelaaez
# To clean enviroment variables %reset import numpy as np import pandas as pd import folium import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit_algorithms import SamplingVQE from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler df = pd.read_csv("uscities.csv") columnsNeeded = ["city", "lat", "lng"] # Inicialization of variables locationsNumber = 15 # OJO que en local me crashea si sobrepaso 5 coordenatesDf = df[columnsNeeded].iloc[:locationsNumber] n = coordenatesDf.shape[0] # number of nodes + depot (n+1) K = 3 # number of vehicles print(coordenatesDf) # Initialize instance values by calculate the squared Euclidean distances between a set of coordinates # represented in the dataframe. def generate_instance(coordenatesDf): n = coordenatesDf.shape[0] xc = coordenatesDf["lat"] yc = coordenatesDf["lng"] loc = coordenatesDf["city"] instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance, loc # Initialize the problem by randomly generating the instance lat, lng, instance, loc = generate_instance(coordenatesDf) print(lat, lng, loc, instance) #print(instance) class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 #vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) #optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) print(qp) #quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) print(classical_cost) m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m print(quantum_cost) x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 m = folium.Map(location=[39.487660, -97.594333], zoom_start=0) marker_icon1 = folium.Icon(color = "red") for i in range(len(lat)): if (i == 0): folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m) else: folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m) for ii in range(0, n**2): if x_quantum[ii] > 0: ix = ii // n iy = ii % n folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m) m algorithms = ("Classic", "Quantum") data = { 'K = 1': (2249.2068134000006, 1706.2245994000696), 'k = 2': (2771.940853740001, 1845.127222779207), 'K = 3': (3981.1556002800016, 3981.155600280501), } x = np.arange(len(algorithms)) # the label locations width = 0.25 # the width of the bars multiplier = 0 fig, ax = plt.subplots(layout='constrained') for attribute, measurement in data.items(): offset = width * multiplier rects = ax.bar(x + offset, measurement, width, label=attribute) ax.bar_label(rects, padding=3) multiplier += 1 # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Length (mm)') ax.set_title('Comparision of Quantum and Classical Cost') ax.set_xticks(x + width, algorithms) ax.legend(loc='upper left', ncols=3) ax.set_ylim(0, 5000) plt.show()
https://github.com/epelaaez/QuantumLibrary
epelaaez
import numpy as np import matplotlib.pyplot as plt import itertools from qiskit import * from qiskit.visualization import plot_histogram from sympy import Matrix from scipy.optimize import curve_fit, minimize from scipy.linalg import eig as eig_solver from scipy.linalg import sqrtm from IPython.display import clear_output # np.seterr(all="ignore") def one_qubit_tomography(input_state, samples): """ Performs quantum state tomography in a single qubit. Parameters: input_state: np.array 1-qubit state for which we want to perform quantum state tomography samples: int Number of samples available of the input state Returns: predicted_state: np.array Density matrix of state predicted via quantum state tomography fidelity: float Fidelity of predicted state in respected to input state """ input_state = np.array(input_state) circuits = [] # Z basis measurement qc = QuantumCircuit(1) qc.initialize(input_state, 0) qc.measure_all() circuits.append(qc) # X basis measurement qc = QuantumCircuit(1) qc.initialize(input_state, 0) qc.h(0) qc.measure_all() circuits.append(qc) # Y basis measurement qc = QuantumCircuit(1) qc.initialize(input_state, 0) qc.sdg(0) qc.h(0) qc.measure_all() circuits.append(qc) # run circuits backend = Aer.get_backend('qasm_simulator') job = execute(circuits, backend, shots=samples) counts = job.result().get_counts() # get expectation values, ordered the same way as the circuits expectation_vals = [] for count in counts: m = (count.get('0', 0) - count.get('1', 0)) / samples expectation_vals.append(m) # calculate µ matrix Z = np.array([[1, 0], [0, -1]]) X = np.array([[0, 1], [1, 0]]) Y = np.array([[0, -1j], [1j, 0]]) I = np.array([[1, 0], [0, 1]]) mu = (I + expectation_vals[0] * Z + expectation_vals[1] * X + expectation_vals[2] * Y) / 2 # calculate eigenvalues of µ matrix eigen = np.linalg.eig(mu) vals = eigen[0] vecs = eigen[1].transpose() # order eigenvalues from largest to smallest eig_vals = sorted(vals, reverse=True) idx = [] for val in eig_vals: idx.append(np.where(vals == val)[0][0]) eig_vecs = [] for i in idx: eig_vecs.append(vecs[i]) # calculate eigenvalues of the density matrix accumulator = 0 lamb_vals = [None] * len(eig_vals) for i in range(len(eig_vals) - 1, -1, -1): if eig_vals[i] + (accumulator / (i + 1)) >= 0: for j in range(i + 1): lamb_vals[j] = eig_vals[j] + (accumulator / (i + 1)) break else: lamb_vals[i] = 0 accumulator += eig_vals[i] # calculate density matrix predicted_state = lamb_vals[0] * np.outer(eig_vecs[0], eig_vecs[0].conj()) \ + lamb_vals[1] * np.outer(eig_vecs[1], eig_vecs[1].conj()) # calculate fidelity fidelity = input_state.conj().dot(predicted_state).dot(input_state) return predicted_state, fidelity density, fidelity = one_qubit_tomography(np.array([np.sqrt(1 / 2), np.sqrt(1 / 2)]), 100) print('Predicted density matrix:') display(Matrix(np.round(density, 5))) print(f'With fidelity: {np.round(fidelity, 5)}') shots = [] fidelities = [] initial_state = np.array([np.sqrt(1 / 2), np.sqrt(1 / 2)]) for i in range(2, 1500): shots.append(i) density, fidelity = one_qubit_tomography(initial_state, i) fidelities.append(fidelity) shots = np.array(shots) plt.figure(figsize=(14, 6)) plt.plot(shots, np.real(fidelities)) plt.ylabel('Fidelity') plt.xlabel('Shots per measurement') plt.title('Shots against fidelity for one qubit state tomography'); def func(t, a, b, c): return a * np.log(t * b) + c popt, pcov = curve_fit(func, shots, np.real(fidelities), p0=(1, 1, 1)) plt.figure(figsize=(14, 6)) plt.plot(shots, np.real(fidelities), label="Original data") plt.plot(shots, func(shots, *popt), 'r-', label="Fitted Curve") plt.legend(); for i in range(2, 1500): if func(i, *popt) >= 1: print(f'Peak fidelity found at {i} shots') break density, fidelity = one_qubit_tomography(np.array([0, 1]), 1000) print('Predicted density matrix:') display(Matrix(np.round(density, 3))) print(f'With fidelity: {np.round(fidelity, 5)}') density, fidelity = one_qubit_tomography(np.array([np.sqrt(2 / 3), 1j * np.sqrt(1 / 3)]), 1000) print('Predicted density matrix:') display(Matrix(np.round(density, 3))) print(f'With fidelity: {np.round(fidelity, 5)}') density, fidelity = one_qubit_tomography(np.array([np.sqrt(1 / 5), np.sqrt(4 / 5)]), 1000) print('Predicted density matrix:') display(Matrix(np.round(density, 3))) print(f'With fidelity: {np.round(fidelity, 5)}') def measure_x_basis(qc, qubit): """ Add a measurement in the X basis to the given qubit Parameters: qc: QuantumCircuit Quantum circuit with the qubit to which you want to add the measurement qubit: int Index of qubit you want to add the measurement to """ qc.h(qubit) qc.measure(qubit, qubit) def measure_y_basis(qc, qubit): """ Add a measurement in the Y basis to the given qubit Parameters: qc: QuantumCircuit Quantum circuit with the qubit to which you want to add the measurement qubit: int Index of qubit you want to add the measurement to """ qc.sdg(qubit) qc.h(qubit) qc.measure(qubit, qubit) def measure_z_basis(qc, qubit): """ Add a measurement in the Z basis to the given qubit Parameters: qc: QuantumCircuit Quantum circuit with the qubit to which you want to add the measurement qubit: int Index of qubit you want to add the measurement to """ qc.measure(qubit, qubit) def measurements_strings(n, arr=['X', 'Y', 'Z']): strs = [] combs = list(itertools.combinations_with_replacement(arr, n)) for comb in combs: for item in set(list(itertools.permutations(comb))): strs.append(item) return strs len(measurements_strings(4)) def tensor_operator(arr): arr = list(arr)[::-1] I = np.array([[1, 0], [0, 1]]) X = np.array([[0, 1], [1, 0]]) Y = np.array([[0, -1j], [1j, 0]]) Z = np.array([[1, 0], [0, -1]]) first = arr.pop(0) if first == 'I': out = I elif first == 'X': out = X elif first == 'Y': out = Y else: out = Z for op in arr: if op == 'I': out = np.kron(out, I) elif op == 'X': out = np.kron(out, X) elif op == 'Y': out = np.kron(out, Y) else: out = np.kron(out, Z) return out.astype('complex') tensor_operator(['X', 'Z']) def get_exp_value(operator_exp, operators_meas, counts, shots): """ Parameters: operator_exp: tuple operators_meas: list counts: list shots: int """ new_counts = {} ignore = [] # if the operator of the expectation value contains the identity in any qubit if 'I' in operator_exp: rep_op = [] for idx, x in enumerate(operator_exp): if x == 'I': ignore.append(idx) rep_op.append('X') else: rep_op.append(x) # if there aren't any identities in the expectation operator else: rep_op = operator_exp # get index of operator_exp in experiment operator_meas, which is the same as in counts for idx, x in enumerate(operators_meas): if x == tuple(rep_op): count_idx = idx # create new counts dictionary for idx, value in counts[count_idx].items(): w = idx[::-1] for i in ignore: w = w[:i] + 'x' + w[i + 1:] if w in new_counts.keys(): new_counts[w] += value else: new_counts[w] = value # get expectation value exp_value = 0 for idx, num_meas in new_counts.items(): meas_val = 1 for x in idx: if x == '1': meas_val *= -1 else: pass exp_value += meas_val * num_meas exp_value /= shots return exp_value def mu_optimize(mu, n): # calculate eigenvalues of µ matrix eigen = np.linalg.eig(mu) vals = eigen[0] vecs = eigen[1].transpose() # order eigenvalues from largest to smallest eig_vals = sorted(vals, reverse=True) idx = [] for val in eig_vals: idx.append(np.where(vals == val)[0][0]) eig_vecs = [] for i in idx: eig_vecs.append(vecs[i]) # calculate eigenvalues of the density matrix accumulator = 0 lamb_vals = [None] * len(eig_vals) for i in range(len(eig_vals) - 1, -1, -1): if eig_vals[i] + (accumulator / (i + 1)) >= 0: for j in range(i + 1): lamb_vals[j] = eig_vals[j] + (accumulator / (i + 1)) break else: lamb_vals[i] = 0 accumulator += eig_vals[i] # calculate density matrix predicted_state = np.zeros((2 ** n, 2 ** n), 'complex') for idx, lamb_val in enumerate(lamb_vals): predicted_state += lamb_vals[idx] * np.outer(eig_vecs[idx], eig_vecs[idx].conj()) return predicted_state def tomography(input_state, samples): """ Performs quantum state tomography in an n-qubit state. Parameters: input_state: np.array n-qubit state for which we want to perform quantum state tomography samples: int Number of samples available of the input state Returns: predicted_state: np.array Density matrix of state predicted via quantum state tomography fidelity: float Fidelity of predicted state in respected to input state """ # get number of qubits and bases to be measured in n = int(np.log(len(input_state)) / np.log(2)) bases = measurements_strings(n) # generate 3^n circuits with each measurement operator in {X, Y, Z}^n circs = [] for base in bases: qc = QuantumCircuit(n, n) qc.initialize(input_state) for idx, b in enumerate(base): if b == 'X': measure_x_basis(qc, idx) elif b == 'Y': measure_y_basis(qc, idx) elif b == 'Z': measure_z_basis(qc, idx) circs.append(qc) # run circuits backend = Aer.get_backend('qasm_simulator') job = execute(circs, backend, shots=samples) # each measurement basis gets a third of the available copies counts = job.result().get_counts() # get all expectation values ops = measurements_strings(n, arr=['I', 'X', 'Y', 'Z'])[1:] # we need to consider identity operator here exp_vals = [] for op in ops: exp_vals.append(get_exp_value(op, bases, counts, samples)) # calculate µ matrix mu = tensor_operator(['I' for _ in range(n)]) for idx, op in enumerate(ops): mu += exp_vals[idx] * tensor_operator(op) mu /= (2 ** n) # optimize the µ matrix to get the predicted density matrix predicted_state = mu_optimize(mu, n) # calculate fidelity fidelity = input_state.conj().dot(predicted_state).dot(input_state) return predicted_state, fidelity input_state = np.array([1 / np.sqrt(2), 1 / np.sqrt(2)]) density, fidelity = tomography(input_state, 1000) print('Predicted density matrix:') display(Matrix(np.round(density, 3))) print(f'With fidelity: {np.round(fidelity, 5)}') results = [] for i in range(1, 6): n = 2 ** i input_state = np.full((n,), 1 / np.sqrt(n)) fidelities = [] for j in range(100, 20000, 100): density, fidelity = tomography(input_state, j) fidelities.append(fidelity) results.append(fidelities) domain = np.array(list(range(100, 20000, 100))) plt.figure(figsize=(14, 6)) for idx, result in enumerate(results): plt.plot(domain, np.real(result), label=f'{idx + 1} qubits') plt.legend() plt.xlabel('Shots per measurement') plt.ylabel('Fidelity of predicted state') plt.title('Fidelity against shots per measurement for states of different dimensions'); plt.figure(figsize=(14, 6)) parameters = [] def func(t, a, b, c): return a * np.log(t * b) + c for idx, result in enumerate(results): popt, pcov = curve_fit(func, domain, np.real(result), p0=(1, 1, 1)) parameters.append(popt) print(f'Parameters for {idx + 1} qubits: {popt}') # plt.plot(domain, np.real(result), label=f'{idx + 1} qubits') plt.plot(domain, func(domain, *popt), label=f"Fitted log for {idx+1} qubits") plt.legend() print('From fitted data:') for idx, popt in enumerate(parameters): for i in range(1, 20000): if func(i, *popt) >= 0.99: print(f'Fidelity greater than or equal to 0.99 found at {i} shots for {idx + 1} qubits') break print('\nFrom experimental data:') for idx, result in enumerate(results): for i, r in enumerate(result): if r >= 0.99: print(f'Fidelity greater than or equal to 0.99 found at {domain[i]} shots for {idx + 1} qubits') break n = 2 ** 5 input_state = np.full((n,), 1 / np.sqrt(n)) density, fidelity = tomography(input_state, 12100) print(f'Fidelity: {np.round(fidelity, 5)}') def ansatz(n, d, qc, reg, params): """ Build ansatz needed for variational circuit. Parameters: n: int Size of the ansatz circuit d: int Number of layers for the ansatz; depth qc: QuantumCircuit Qiskit quantum circuit in which to add the ansatz reg: QuantumRegister Register to which you want to add the ansatz params: np.array Numpy array with the parameters for the rotation gates in the ansatz """ arr_idx = 0 for i in range(1, d + 1): # even layers if i % 2 == 0: for j in range(n): qc.ry(params[arr_idx], reg[j]) arr_idx += 1 for k in range(1, n): if k + 1 > n: break else: qc.cz(reg[0], reg[k]) # odd layers else: for j in range(n): qc.ry(params[arr_idx], reg[j]) arr_idx += 1 for k in range(n - 2, -1, -1): if k + 1 > n - 1: break else: qc.cz(reg[-1], reg[k]) # extra final layer for i in range(n): qc.rx(params[arr_idx], reg[i]) arr_idx += 1 def swap_test(n, qc, reg_1, reg_2, aux, aux_c, basis=0): """ Add swap test circuit between two registers using an auxilary qubit. Paremetrs: n: int Size of both registers to which we apply the SWAP test qc: QuantumCircuit Quantum circuit containing all the qubits we are going to act on reg_1: QuantumRegister First register on the test reg_2: QuantumRegister Second register on the test aux: QuantumRegister Register with the ancilla qubit used in the SWAP test aux_c: ClassicalRegister Register to store measurement value of the aux quantum register basis: int Basis in which to perform the SWAP test; 0 for X, 1 for Y and 2 for Z """ # change states in registers to compare to the given basis if basis == 0: pass elif basis == 1: qc.sdg(reg_1) qc.h(reg_1) qc.sdg(reg_2) qc.h(reg_2) elif basis == 2: qc.h(reg_1) qc.h(reg_2) qc.h(aux) for i in range(n): qc.cswap(aux, reg_1[i], reg_2[i]) qc.h(aux) qc.measure(aux, aux_c) def loss_func(params, ansatz, target_state, n, d, shots, backend): """ Calculate loss function of variational circuit used to reconstruct the target state via state tomography. Parameters: params: np.array Array with the parameters of the variational circuit to try ansatz: func Function that takes a circuit of size n and a set of parameters to add a parametrized circuit to it Must be of the form: ansatz(n, d, qc, reg, params) target_state: np.array Statevector of the target state in which we are performing the tomography n: int Number of qubits needed to represent the target state d: int Desired depth of the variational circuit shots: int Number of times to run the quantum circuit backend: IBMQBackend Backend to run the quantum circuit in Returns: loss: float Calculated loss value through the SWAP test """ loss_vals = [] for i in range(3): # initialize all registers and quantum circuit reg_1 = QuantumRegister(n, 'pure') reg_2 = QuantumRegister(n, 'var') aux = QuantumRegister(1, 'aux') aux_c = ClassicalRegister(1, 'c') qc = QuantumCircuit(reg_1, reg_2, aux, aux_c) # initialize target state in register 1 init = QuantumCircuit(n) init.initialize(target_state) init = transpile(init, basis_gates=['cx', 'u']) init_gate = init.to_gate(label=' init ') qc.append(init_gate, reg_1) # add variational circuit in register 2 ansatz(n, d, qc, reg_2, params) # perform swap test between registers 1 and 2 swap_test(n, qc, reg_1, reg_2, aux, aux_c, basis=i+1) # run circuit to calculate the loss function job = backend.run(transpile(qc, backend), shots=shots) counts = job.result().get_counts() if 1 - 2 * (counts.get('1', 0) / shots) < 0: # avoid rounding errors loss = 0 else: loss = 1 - np.sqrt(1 - 2 * (counts.get('1', 0) / shots)) loss_vals.append(loss) clear_output(wait=True) print(f'X: {loss_vals[0]}. Y: {loss_vals[1]}. Z: {loss_vals[2]}. Avg: {np.average(loss_vals)}') return np.average(loss_vals) n = 2 d = 5 shots = 10000 target = np.random.rand(2 ** n) target = target / np.linalg.norm(target) # target = np.full(2 ** n, 1 / np.sqrt(2 ** n)) # equal superposition of all basis states guess = [0 for _ in range(n * d + n)] backend = Aer.get_backend('qasm_simulator') op_result = minimize(loss_func, guess, args=(ansatz, target, n, d, shots, backend), method='COBYLA') print(f'Target state: {target}') print(f'Calculated parameters: {op_result.x}') print(f'With loss value: {op_result.fun}') reg = QuantumRegister(n, 'reg') qc = QuantumCircuit(reg) ansatz(n, d, qc, reg, op_result.x) display(qc.draw('mpl')) backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() vector = result.get_statevector()[None] print(f'Ansatz has {dict(qc.count_ops())}') Matrix(np.round(vector, 5)) reg = QuantumRegister(n) qc = QuantumCircuit(reg) ansatz(n, d, qc, reg, op_result.x) qc.measure_all() qc2 = QuantumCircuit(n) qc2.initialize(target) qc2.measure_all() backend = Aer.get_backend('qasm_simulator') result = execute([qc, qc2], backend, shots=10000).result() counts = result.get_counts() plot_histogram(counts, figsize=(14,5), legend=['Predicted', 'Target']) fidelity = np.abs(target.conj().dot(vector[0])) ** 2 print(f'Fidelity of predicted state compared to target state: {fidelity}') def tomography(ansatz, layers, num_params, loss_func, target, shots, method='COBYLA', repeat=False): """ Performs state tomography on the target state using a variational algorithm. Parameters: ansatz: func Function that takes a circuit of size n and a set of parameters to add a parametrized circuit to it Must be of the form: ansatz(n, layers, qc, reg, params) layers: int Number of layers of the ansatz to add to the variational circuit num_params: int Number of parameters the specified ansatz needs loss_func: func Function that adds the cost function to the circuit, which uses the SWAP test Must be of the form: loss_func(params, ansatz, target_state, n, layers, shots, backend) target: np.array 2^n normalized array with the target statevector shots: int Number of available shots for each measurement of the variational circuit method: str String with name of SciPy optimizer to use to optimize the parameters; defaults to COBYLA repeat: bool If True, it will repeat the optimization procedure until the final loss value is less than 0.01 Returns: op_result.x: np.array Array with the optimized parameters op_result.fun: float Value of the given loss function with the found optimal parameters """ n = int(np.log(len(target)) / np.log(2)) guess = [0 for _ in range(num_params)] backend = Aer.get_backend('qasm_simulator') op_result = minimize(loss_func, guess, args=(ansatz, target, n, layers, shots, backend), method=method) if repeat: loss_val = op_result.fun while loss_val >= 0.01: params = op_result.x op_result = minimize(loss_func, params, args=(ansatz, target, n, layers, shots, backend), method=method) loss_val = op_result.fun return op_result.x, op_result.fun num_qubits = 3 layers = 4 num_params = num_qubits * (layers + 1) target = np.random.rand(2 ** num_qubits) target = target / np.linalg.norm(target) shots = 10000 tomography(ansatz, layers, num_params, loss_func, target, shots, 'COBYLA', repeat=True)
https://github.com/epelaaez/QuantumLibrary
epelaaez
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.circuit import Parameter def block(n: int, param_prefix: str = "θ"): qc = QuantumCircuit(n) for i in range(n): qc.ry(Parameter(param_prefix + "_" + str(i)), i) for i in range(0, n-1, 2): qc.cx(i, i+1) for i in range(1, n-1, 2): qc.cx(i, i+1) qc.name = "block" return qc block(4).draw("mpl") def alt(l: int, n: int, m: int): if m % 2 != 0: raise Exception("Parameter `m` must be an even number") if n % m != 0: raise Exception("Parameter `n` divided by `m` must be integer") qc = QuantumCircuit(n) for i in range(l): if (i + 1) % 2 == 0: qc.append(block(m//2, param_prefix=f"θ_{i}_0"), range(0, m//2)) for j in range(m//2, n-m//2, m): qc.append(block(m, param_prefix=f"θ_{i}_{j}"), range(j, j+m)) qc.append(block(m//2, param_prefix=f"θ_{i}_{j+1}"), range(n-m//2, n)) else: for j in range(0, n, m): qc.append(block(m, param_prefix=f"θ_{i}_{j}"), range(j, j+m)) return qc alt(3, 8, 4).draw("mpl") def ten(l: int, n: int, m: int): if m % 2 != 0: raise Exception("Parameter `m` must be an even number") if n % m != 0: raise Exception("Parameter `n` divided by `m` must be integer") qc = QuantumCircuit(n) for i in range(l): for j in range(0, n, m): qc.append(block(m, param_prefix=f"θ_{i}_{j}"), range(j, j+m)) return qc ten(3, 8, 4).draw("mpl") from qiskit.algorithms import VQE from qiskit.opflow import Z, I from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import TwoLocal import matplotlib.pyplot as plt def test_ansatz(ansatz, num_qubits, fig_title): hamiltonian = (Z ^ Z) ^ (I ^ (num_qubits - 2)) target_energy = -1 optimizer = SPSA() np.random.seed(2022) initial_point = np.random.random(ansatz.num_parameters) intermediate_info = {"nfev": [], "parameters": [], "energy": [], "stddev": []} def callback(nfev, parameters, energy, stddev): intermediate_info["nfev"].append(nfev) intermediate_info["parameters"].append(parameters) intermediate_info["energy"].append(energy) intermediate_info["stddev"].append(stddev) local_vqe = VQE( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, quantum_instance=QasmSimulatorPy(), callback=callback, ) local_result = local_vqe.compute_minimum_eigenvalue(hamiltonian) print("Eigenvalue:", local_result.eigenvalue) print("Target:", target_energy) fig, ax = plt.subplots(figsize=(12, 8)) ax.plot(intermediate_info["nfev"], intermediate_info["energy"], color="red") ax.set_xlabel("Optimization step", fontsize = 14) ax.set_ylabel("Energy", color="red", fontsize=12) ax2=ax.twinx() ax2.plot(intermediate_info["nfev"], intermediate_info["stddev"], color="blue") ax2.set_ylabel("Deviation",color="blue",fontsize=12) plt.title(fig_title) plt.show() num_qubits = 8 layers = 3 block_size = 2 alt_ansatz = alt(layers, num_qubits, block_size) test_ansatz(alt_ansatz, num_qubits, "Alternating layered ansatz") ten_ansatz = ten(layers, num_qubits, block_size) test_ansatz(ten_ansatz, num_qubits, "Tensor product ansatz") two_local_ansatz = TwoLocal(num_qubits, "ry", "cx", reps=layers) test_ansatz(two_local_ansatz, num_qubits, "Two local ansatz")
https://github.com/epelaaez/QuantumLibrary
epelaaez
from qiskit import * import numpy as np n = 5 control_reg = QuantumRegister(n, 'c') target_reg = QuantumRegister(1, 't') ancilla_reg = QuantumRegister(1, 'a') circuit = QuantumCircuit(control_reg, target_reg, ancilla_reg) circuit.mct(control_reg[:int(np.ceil(n/2))], ancilla_reg[0]) circuit.mct(control_reg[int(np.ceil(n/2)):] + ancilla_reg[:], target_reg[0]) circuit.mct(control_reg[:int(np.ceil(n/2))], ancilla_reg[0]) circuit.mct(control_reg[int(np.ceil(n/2)):] + ancilla_reg[:], target_reg[0]) circuit.draw('mpl') def n_m_2_ancilla(circuit, control_reg, target_reg, ancilla_reg): n = len(control_reg) # first mountain circuit.ccx(ancilla_reg[-1], control_reg[-1], target_reg[0]) for i in range(n - 4, -1, -1): circuit.ccx(ancilla_reg[i], control_reg[i + 2], ancilla_reg[i + 1]) circuit.ccx(control_reg[0], control_reg[1], ancilla_reg[0]) for i in range(0, n - 3): circuit.ccx(ancilla_reg[i], control_reg[i + 2], ancilla_reg[i + 1]) circuit.ccx(ancilla_reg[-1], control_reg[-1], target_reg[0]) # second mountain, i.e., uncomputation for i in range(n - 4, -1, -1): circuit.ccx(ancilla_reg[i], control_reg[i + 2], ancilla_reg[i + 1]) circuit.ccx(control_reg[0], control_reg[1], ancilla_reg[0]) for i in range(0, n - 3): circuit.ccx(ancilla_reg[i], control_reg[i + 2], ancilla_reg[i + 1]) n = 5 control_reg = QuantumRegister(n, 'c') target_reg = QuantumRegister(1, 't') ancilla_reg = QuantumRegister(n - 2, 'a') circuit = QuantumCircuit(control_reg, target_reg, ancilla_reg) n_m_2_ancilla(circuit, control_reg, target_reg, ancilla_reg) circuit.draw('mpl') n = 7 control_reg = QuantumRegister(n, 'c') target_reg = QuantumRegister(1, 't') ancilla_reg = QuantumRegister(1, 'a') circuit = QuantumCircuit(control_reg, target_reg, ancilla_reg) for _ in range(2): # first gate controls = [i for i in range(n) if i % 2 == 0] target = [-1] ancilla = [i for i in range(n) if i not in controls] while len(ancilla) != len(controls) - 2: ancilla.pop(0) n_m_2_ancilla(circuit, controls, target, ancilla) circuit.barrier() # second gate controls = [i for i in range(n) if i % 2 == 1] + [n + 1] target = [-2] ancilla = [i for i in range(n) if i not in controls] while len(ancilla) != len(controls) - 2: ancilla.pop(0) n_m_2_ancilla(circuit, controls, target, ancilla) circuit.barrier() circuit.draw('mpl')
https://github.com/epelaaez/QuantumLibrary
epelaaez
import numpy as np from qiskit.quantum_info import state_fidelity def schmidt_decomp_even(state): n = int(np.log2(len(state))) mat = state.reshape(2 ** (n // 2), 2 ** (n // 2)) u, s, v = np.linalg.svd(mat) a = [u[:, i].reshape(2 ** (n // 2), 1) for i in range(2 ** (n // 2))] b = [v[i, :].reshape(2 ** (n // 2), 1) for i in range(2 ** (n // 2))] new_state = np.sum([np.kron(a[i], b[i]) * s[i] for i in range(2 ** (n // 2))], axis=0) assert np.isclose(state_fidelity(state, new_state), 1), "Didnt work :(" return a, b, s n = 2 # must be even state = np.random.rand(2 ** n) state = state / np.linalg.norm(state) a, b, s = schmidt_decomp_even(state) from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Statevector, random_statevector from sympy import Matrix qc = QuantumCircuit(n) qc.ry(2 * np.arccos(s[0]), 0) qc.draw() Matrix(np.round(Statevector(qc), 5)) qc.cx(0, 1) qc.draw() Matrix(np.round(Statevector(qc), 5)) theta = 2 * np.arccos(a[0][0][0]) phi = np.real(np.log(a[0][1][0] / np.sin(np.arccos(a[0][0][0])), dtype='complex') / 1j) lamb = np.real(np.log(-a[1][0][0] / np.sin(np.arccos(a[0][0][0])), dtype='complex') / 1j) qc.u(theta, phi, lamb, 0) qc.draw() Matrix(np.round(Statevector(qc), 5)) theta = 2 * np.arccos(b[0][0][0]) phi = np.real(np.log(b[0][1][0] / np.sin(np.arccos(b[0][0][0])), dtype='complex') / 1j) lamb = np.real(np.log(-b[1][0][0] / np.sin(np.arccos(b[0][0][0])), dtype='complex') / 1j) qc.u(theta, phi, lamb, 1) qc.draw() Matrix(np.round(Statevector(qc.reverse_bits()), 5)) Matrix(np.round(state, 5)) def two_qubit_state(state): qc = QuantumCircuit(2) # Normalize state and get Schmidt decomposition state = state / np.linalg.norm(state) a, b, s = schmidt_decomp_even(state) # Phase 1 qc.ry(2 * np.arccos(s[0]), 0) # Phase 2 qc.cx(0, 1) # Phase 3 qc.unitary(np.block([a[0].flatten().T, a[1].flatten().T]).reshape(2, 2).T, 0) # Phase 4 qc.unitary(np.block([b[0].flatten().T, b[1].flatten().T]).reshape(2, 2).T, 1) return qc state = random_statevector(4).data qc = two_qubit_state(state) qc.decompose().draw() circ = Statevector(qc.reverse_bits()).data Matrix(np.round(circ, 5)) Matrix(np.round(state, 5)) for _ in range(100): state = random_statevector(4).data qc = two_qubit_state(state) circ = Statevector(qc.reverse_bits()).data assert np.allclose(circ, state)
https://github.com/epelaaez/QuantumLibrary
epelaaez
from qiskit import * from qiskit.visualization import plot_histogram from qiskit.circuit.library import QFT, SwapGate from qiskit.extensions import UnitaryGate from random import randrange from sympy import Matrix import numpy as np from fractions import Fraction import pandas as pd def euclids(a, b): """ Given two integers a and b, compute gcd(a, b) using Euclid's algorithm. Parameters: ----------- a: int First integer for Euclid's algorithm b: int Second integer for Euclid's algorithm Returns: -------- b: int Returns gcd(a, b) stored on input b """ while True: r = a % b if not r: break a = b b = r return b def a2jmodN(a, j, N): """ Compute a^{2^j} (mod N) by repeated squaring Parameters: ----------- a: int Value for a j: int Value for j N: int Value for N Returns: -------- a: int a^{2^j} (mod N) """ for i in range(j): a = np.mod(a**2, N) return a def mod_inv(a, N): for i in range(N): if (a * i) % N == 1: return i raise Exception(f"Modular inverse of {a} mod {N} doesn't exist") def set_initial(n, val_a): """ Construct gate to set initial state of register with size n to val_a. For example n=4 with val_a=5 will apply X gates on qubits 0 and 2. Parameters: ----------- n: int Size of register we want to initialize val_a: int Value to which we want to initialize Returns: -------- init_gate: Gate Constructed gate """ if ((2**n) - 1) < val_a: raise Exception(f'Cannot initialize {val_a} into given register, there are no sufficient qubits') reg_a = QuantumRegister(n) gate = QuantumCircuit(reg_a) bin_a = "{0:b}".format(val_a).zfill(n) for idx, i in enumerate(bin_a[::-1]): if i == '1': gate.x(idx) init_gate = gate.to_gate(label=f'Init {val_a}') return init_gate qc = QuantumCircuit(4) init = set_initial(4, 5) qc.append(init, [0,1,2,3]) qc = transpile(qc, basis_gates=['u', 'cx']) qc.draw('mpl') def adder(n, val_a, dag=False): """ Construct gate to add val_a into register b in the Fourier basis. Register b must contain the number on the Fourier basis already. The subtracter gate gives us b - a if b ≥ a or 2^{n+1}−(a−b) if b < a. It is obtained by inversing the adder. Parameters: ----------- n: QuantumRegister Size of register b val_a: int Value to which register a will be initialized dag: Boolean If set to true, the dagger of the adder gate (the subtracter) is appended Returns: -------- adder_gate: Gate Constructed gate """ bin_a = "{0:b}".format(val_a).zfill(n) phase = lambda lam: np.array([[1, 0], [0, np.exp(1j * lam)]]) identity = np.array([[1, 0], [0, 1]]) arr_gates = [] for i in range(n): qubit_gate = identity for j in range(i, n): if bin_a[j] == '1': qubit_gate = phase(np.pi / (2 ** (j - i))) @ qubit_gate arr_gates.append(qubit_gate) unitary = arr_gates[0] for i in range(1, len(arr_gates)): unitary = np.kron(arr_gates[i], unitary) adder_gate = UnitaryGate(unitary) adder_gate.label = f"Add {val_a}" if dag == True: adder_gate = adder_gate.inverse() adder_gate.label = f"Subtract {val_a}" return adder_gate b = QuantumRegister(4, name='q') q = QuantumCircuit(b) add_1 = 5 add_2 = 3 init = set_initial(b.size, add_1) q.append(init, b[:]) qft = QFT(4, name="$QFT$") q.append(qft, b[:]) add = adder(4, add_2, dag=True) q.append(add, b[:]) qft_i = QFT(4, inverse=True, name="$QFT^\dag$") q.append(qft_i, b[:]) display(q.draw('mpl')) backend = Aer.get_backend('statevector_simulator') q = transpile(q, basis_gates=['cx', 'u']) result = backend.run(q).result() counts = result.get_counts() counts def mod_adder(n, val_a, val_N): """ Construct gate to compute a + b mod N in the Fourier basis. Register b must contain the number on the Fourier basis already, and the answer will be in this register. Parameters: ----------- n: QuantumRegister Size of register b val_a: int Value to add to register val_N: int We take mod of a + b respect to this value Returns: -------- mod_adder_gate: Gate Constructed gate """ reg_c = QuantumRegister(2) reg_b = QuantumRegister(n) aux = QuantumRegister(1) gate = QuantumCircuit(reg_c, reg_b, aux) qft = QFT(n, name="$QFT$").to_gate() qft_inv = QFT(n, inverse=True, name="$QFT^\dag$").to_gate() gate.append(adder(n, val_a).control(2), reg_c[:] + reg_b[:]) gate.append(adder(n, val_N, dag=True), reg_b[:]) gate.append(qft_inv, reg_b[:]) gate.cx(reg_b[-1], aux[0]) gate.append(qft, reg_b[:]) gate.append(adder(n, val_N).control(1), aux[:] + reg_b[:]) gate.append(adder(n, val_a, dag=True).control(2), reg_c[:] + reg_b[:]) gate.append(qft_inv, reg_b[:]) gate.x(reg_b[-1]) gate.cx(reg_b[-1], aux[0]) gate.x(reg_b[-1]) gate.append(qft, reg_b[:]) gate.append(adder(n, val_a).control(2), reg_c[:] + reg_b[:]) mod_adder_gate = gate.to_gate(label=f"Add {val_a} mod {val_N}") return mod_adder_gate c = QuantumRegister(2, name='c') b = QuantumRegister(4, name='b') aux = QuantumRegister(1, name='aux') clas = ClassicalRegister(4, name='cl') aux_clas = ClassicalRegister(1, name='acl') qc = QuantumCircuit(c,b,aux,clas,aux_clas) val_a = 4 val_b = 7 # b < 2 ** (n - 1) val_N = 8 init = set_initial(b.size, val_b) qc.append(init, b[:]) qft = QFT(4) qc.append(qft, b[:]) qc.x(c) mod_add = mod_adder(b.size, val_a, val_N) qc.append(mod_add, c[:] + b[:] + aux[:]) add = adder(b.size, 3) qc.append(add, b[:]) qft_1 = QFT(4, inverse=True) qc.append(qft_1, b[:]) qc.measure(b,clas) qc.measure(aux,aux_clas) display(qc.draw('mpl')) backend = Aer.get_backend('qasm_simulator') qc = transpile(qc, basis_gates=['u', 'cx']) result = backend.run(qc).result() counts = result.get_counts() counts def ctrl_mult(n, val_a, val_N, dag=False): """ Construct gate that computes (b + ax) mod N if control qubit is set to 1. The gate transforms the value in register b to the Fourier basis within it. Parameters: ----------- n: QuantumRegister Size of registers b and x val_a: int Value to multiply by x val_N: int We take mod of (b + ax) mod N respect to this value dag: bool If set to true, the dagger of the adder gate (the subtracter) is appended Returns: -------- ctrl_mult_gate: Gate Constructed gate """ reg_c = QuantumRegister(1) reg_x = QuantumRegister(n) reg_b = QuantumRegister(n) aux = QuantumRegister(1) gate = QuantumCircuit(reg_c, reg_x, reg_b, aux) qft = QFT(n, name="$QFT$").to_gate() qft_inv = QFT(n, inverse=True, name="$QFT^\dag$").to_gate() gate.append(qft, reg_b[:]) for i in range(n): gate.append(mod_adder(n, (2**i) * val_a, val_N), reg_c[:] + [reg_x[:][i]] + reg_b[:] + aux[:]) gate.append(qft_inv, reg_b[:]) ctrl_mult_gate = gate.to_gate(label=f"Mult {val_a} mod {val_N}") if dag == True: ctrl_mult_gate = ctrl_mult_gate.inverse() ctrl_mult_gate.label = f"Mult {val_a} mod {val_N} inv" return ctrl_mult_gate def u_a(n, val_a, val_N): reg_c = QuantumRegister(1) reg_x = QuantumRegister(n) reg_y = QuantumRegister(n) aux = QuantumRegister(1) gate = QuantumCircuit(reg_c, reg_x, reg_y, aux) gate.append(ctrl_mult(n, val_a, val_N), reg_c[:] + reg_x[:] + reg_y[:] + aux[:]) temp_qc = QuantumCircuit(2*n) temp_qc.swap([i for i in range(n)], [i for i in range(n, 2*n)]) cswap = temp_qc.to_gate(label='CSWAP').control(1) gate.append(cswap, reg_c[:] + reg_x[:] + reg_y[:]) gate.append(ctrl_mult(n, mod_inv(val_a, val_N), val_N, dag=True), reg_c[:] + reg_x[:] + reg_y[:] + aux[:]) u_a_gate = gate.to_gate(label=f"$U_{val_a}$") return u_a_gate val_a = 4 val_n = 7 val_x = 1 c = QuantumRegister(1, name='c') x = QuantumRegister(5, name='x') y = QuantumRegister(5, name='y') aux = QuantumRegister(1, name='aux') clas_0 = ClassicalRegister(5) clas_1 = ClassicalRegister(5) qc = QuantumCircuit(c, x, y, aux, clas_0, clas_1) qc.x(c) init_x = set_initial(5, val_x) qc.append(init_x, x[:]) u = u_a(5, val_a, val_n) qc.append(u, c[:] + x[:] + y[:] + aux[:]) qc.measure(x, clas_0) qc.measure(y, clas_1) display(qc.draw('mpl')) print("Expected: ", (val_a * val_x) % val_n) backend = Aer.get_backend('qasm_simulator') qc = transpile(qc, basis_gates=['u', 'cx']) result = backend.run(qc).result() counts = result.get_counts() print(counts) n = len("{0:b}".format(15)) a = 2 N = 15 reg_a = QuantumRegister(2 * n, name='a') reg_b = QuantumRegister(2 * n, name='b') aux = QuantumRegister(1, name='aux') clas = ClassicalRegister(2 * n, name='c') qc = QuantumCircuit(reg_a, reg_b, aux, clas) qc.h(reg_a) qc.x(reg_b[0]) qc.append(u_a(n, a2jmodN(a, 0, N), N), [reg_a[:][0]] + reg_b[:] + aux[:]) qc.append(u_a(n, a2jmodN(a, 1, N), N), [reg_a[:][1]] + reg_b[:] + aux[:]) qc.append(u_a(n, a2jmodN(a, 2, N), N), [reg_a[:][2]] + reg_b[:] + aux[:]) qc.append(u_a(n, a2jmodN(a, 3, N), N), [reg_a[:][3]] + reg_b[:] + aux[:]) qc.append(u_a(n, a2jmodN(a, 4, N), N), [reg_a[:][4]] + reg_b[:] + aux[:]) qc.append(u_a(n, a2jmodN(a, 5, N), N), [reg_a[:][5]] + reg_b[:] + aux[:]) qc.append(u_a(n, a2jmodN(a, 6, N), N), [reg_a[:][6]] + reg_b[:] + aux[:]) qc.append(u_a(n, a2jmodN(a, 7, N), N), [reg_a[:][7]] + reg_b[:] + aux[:]) qc.append(QFT(2 * n, inverse=True), reg_a[:]) qc.barrier() qc.measure(reg_a, clas) qc.draw('mpl') aer_sim = Aer.get_backend('aer_simulator') qc = transpile(qc, aer_sim) results = aer_sim.run(qc).result() counts = results.get_counts() plot_histogram(counts) filtered_counts = [] for count in counts: total += counts[count] if counts[count] > 50: filtered_counts.append(count) filtered_counts rows, measured_phases = [], [] for output in filtered_counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**(2 * n)) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**(2 * n)} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) r_guesses.append(frac.denominator) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) r = 4 guesses = [euclids(a**(r//2)-1, N), euclids(a**(r//2)+1, N)] print(guesses)
https://github.com/nielsaNTNU/qiskit_utilities
nielsaNTNU
import qiskit.tools.jupyter import matplotlib as ml from GenerateRandomCircuit import * backends_dict={} backendname_sim = 'qasm_simulator' backends_dict[backendname_sim] = Aer.get_backend(backendname_sim) #load IBMQ account #IBMQ.save_account('yourAPItoken') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') for backendname in ['ibmq_16_melbourne', 'ibmqx2']: backends_dict[backendname] = provider.get_backend(backendname) G_qasm_simulator=createGraph(backends_dict['qasm_simulator'],5) nx.draw_networkx(G_qasm_simulator) G_ibmqx2=createGraph(backends_dict['ibmqx2']) nx.draw_networkx(G_ibmqx2) G_melbourne=createGraph(backends_dict['ibmq_16_melbourne']) nx.draw_networkx(G_melbourne) circ = randomCircuit(G_ibmqx2) circ.draw(output='mpl') circ = randomCircuit(G_ibmqx2, cnots=9) circ.draw(output='mpl') circ = randomCircuit(G_ibmqx2, depth=10) circ.draw(output='mpl') circ = randomCircuit(G_ibmqx2, cnots=13, depth=2) circ.draw(output='mpl') circ = randomCircuit(G_ibmqx2, cnots=3, depth=9) circ.draw(output='mpl') circ = randomCircuit(G_ibmqx2, cnots=14, depth=9) circ.draw(output='mpl') circ = randomCircuit(G_ibmqx2, cnots=14, depth=9, barrier=True) circ.draw(output='mpl') circ = randomCircuit(G_ibmqx2, cnots=16, depth=33) circ.draw(output='mpl') circ = randomCircuit(G_qasm_simulator, depth=10) circ.draw(output='mpl') circ = randomCircuit(G_melbourne, depth=10) circ.draw(output='mpl')
https://github.com/nielsaNTNU/qiskit_utilities
nielsaNTNU
from qiskit import * import numpy as np import networkx as nx import random as ran from qiskit.visualization import * def ranCircCXD(G, circ, cnots, depth, barrier, cc, dd, num_V, MI, V, L): if (2*cnots + 1 < depth): print("Impossible circuit parameters: number of CNOTs is too low to reach the desired depth. Try again with different parameters.") elif (depth*len(MI) < cnots): print("Impossible circuit parameters: depth is too low to fit all the required CNOTs into the given graph. Try again with different parameters.") else: print("Constructing circuit with ", cnots, " CNOTs and ", depth," depth...") #preconstruction: for j in V: for d in range(depth): cc[j].append(0) print('Preconstruction...') k = 0 sparse = True contin = True #adding CNOT gates: while (sparse): n = 0 cc = [] for j in V: cc.append([]) for j in V: for d in range(depth): cc[j].append(0) #print('new attempt:', k) if (k > 100*cnots*depth*depth): print("Sorry, unable to construct the circuit after ", k, " attempts. Try again with different parameters.") contin = False break while (n < cnots): k +=1 if (k > 100*cnots*depth*depth): break edge = ran.sample(G.edges(),1)[0] node1 = edge[0] node2 = edge[1] d = ran.randint(0,depth-1) if (cc[node1][d] == 0 and cc[node2][d] == 0): if ran.choice([0,1]): cc[node1][d] = ['C', node2] cc[node2][d] = 'X' else: cc[node2][d] = ['C', node1] cc[node1][d] = 'X' n +=1 #check if circuit is too sparse unsparse = False for j in V: sparsehere = False for d in range(depth-1): if (cc[j][d] == 0 and cc[j][d+1] == 0): sparsehere = True break if not(sparsehere): unsparse = True if (unsparse): sparse = False #print('cc looks like this:') #print(cc) #actual construction: if (contin): print('Successful at attempt ', k) print('Constructing circuit...') for j in V: if (isinstance(cc[j][0],list)): if (cc[j][0][0] == 'C'): if (cc[cc[j][0][1]][0] == 'X'): circ.cx(j,cc[j][0][1]) elif (cc[j][0] == 0): theta = ran.uniform(0.0, 2*np.pi) phi = ran.uniform(0.0, 2*np.pi) lam = ran.uniform(0.0, 2*np.pi) circ.u3(theta, phi, lam, j) for d in range(1,depth): if(barrier): circ.barrier() for j in V: if (isinstance(cc[j][d],list)): if (cc[j][d][0] == 'C'): if (cc[cc[j][d][1]][d] == 'X'): circ.cx(j,cc[j][d][1]) elif ((cc[j][d] == 0) and (cc[j][d-1] != 0)): theta = ran.uniform(0.0, 2*np.pi) phi = ran.uniform(0.0, 2*np.pi) lam = ran.uniform(0.0, 2*np.pi) circ.u3(theta, phi, lam, j) def ranCircCX(G, circ, cnots, barrier, cc, num_V): print("Constructing circuit with ", cnots, " CNOTs and arbitrary depth...") n = 0 while (n < cnots): gate=ran.choice(['CX','U3']) #choose randomly between CNOT and U3 if (gate == 'U3'): node = ran.choice(range(num_V)) if (not(cc[node]) or (cc[node][-1] != 'U3')): theta = ran.uniform(0.0, 2*np.pi) phi = ran.uniform(0.0, 2*np.pi) lam = ran.uniform(0.0, 2*np.pi) circ.u3(theta, phi, lam, node) cc[node].append('U3') else: n += 1 edge = ran.sample(G.edges(),1)[0] node1 = edge[0] node2 = edge[1] if ran.choice([0,1]): circ.cx(node1,node2) cc[node1].append('C') cc[node2].append('X') else: circ.cx(node2,node1) cc[node2].append('C') cc[node1].append('X') def ranCircD(G, circ, depth, barrier, cc, dd, num_V): print("Constructing circuit with arbitrarly many CNOTs and ", depth," depth...") d = 0 while(d < depth): if(barrier): circ.barrier() gate=ran.choice(['CX','U3']) #choose randomly between CNOT and U3 if (gate == 'U3'): node = ran.choice(range(num_V)) if (not(cc[node]) or (cc[node][-1] != 'U3')): theta = ran.uniform(0.0, 2*np.pi) phi = ran.uniform(0.0, 2*np.pi) lam = ran.uniform(0.0, 2*np.pi) circ.u3(theta, phi, lam, node) cc[node].append('U3') dd[node] += 1 else: edge = ran.sample(G.edges(),1)[0] node1 = edge[0] node2 = edge[1] if ran.choice([0,1]): circ.cx(node1,node2) cc[node1].append('C') cc[node2].append('X') else: circ.cx(node2,node1) cc[node2].append('C') cc[node1].append('X') dd[node1] += 1 dd[node2] += 1 dd[node1] = max(dd[node1],dd[node2]) dd[node2] = dd[node1] d = max(dd) #print(d) def createGraph(backend, n_qubits=0): if backend.configuration().simulator: if n_qubits <= 0: raise ValueError("Please specify number of qubits for a simulator.") G=nx.complete_graph(n_qubits) else: n_qubits=backend.configuration().n_qubits G=nx.Graph() G.add_nodes_from(np.arange(n_qubits)) G.add_edges_from(backend.configuration().coupling_map) return G def randomCircuit(G, cnots=0, depth=0, barrier=False): #Either cnots or depth can be zero, which means "unspecified". V = list(G.nodes) num_V = len(V) L = nx.line_graph(G) MI = nx.maximal_independent_set(L) q = QuantumRegister(num_V) c = ClassicalRegister(num_V) circ = QuantumCircuit(q,c) circ.barrier() ran.seed() #copy of circuit for internal tracing: cc = [] for j in V: cc.append([]) dd = [] for j in V: dd.append(0) #begin construction: if (cnots and depth): ranCircCXD(G, circ, cnots, depth, barrier, cc, dd, num_V, MI, V, L) elif (cnots and not(depth)): ranCircCX(G, circ, cnots, barrier, cc, num_V) elif (not(cnots) and depth): ranCircD(G, circ, depth, barrier, cc, dd, num_V) else: print("This will only return an empty circuit.") circ.barrier() print('Depth is: ', circ.depth()) circ.measure(q,c) return circ
https://github.com/nielsaNTNU/qiskit_utilities
nielsaNTNU
import pylab as pl import qiskit.tools.jupyter from GenerateRandomCircuit import * from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.quantum_info import Kraus, SuperOp from qiskit.providers.aer import QasmSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import QuantumError, ReadoutError from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error backendname_sim = Aer.get_backend('qasm_simulator') G_qasm_simulator=createGraph(backendname_sim,5) nx.draw_networkx(G_qasm_simulator) circ = randomCircuit(G_qasm_simulator, depth=20) circ.draw(output='mpl') circs=[] for i in range(1024): circs.append(circ) job_clean = execute(circs, backendname_sim, shots=1024) results_clean=job_clean.result().results # counts_clean=job.result().get_counts() # plot_histogram(counts_clean) # T1 and T2 values for qubits 0-3 T1s = np.random.normal(50e3, 10e3, 5) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e3, 10e3, 5) # Sampled from normal distribution mean 50 microsec # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(5)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(5): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(5): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) job_thermal = execute(circs, backendname_sim, basis_gates=noise_thermal.basis_gates, noise_model=noise_thermal,shots=1024) results_thermal=job_thermal.result().results # result_thermal = job.result() counts_clean = job_clean.result().get_counts(0) counts_thermal = job_thermal.result().get_counts(0) # Plot noisy output plot_histogram([counts_thermal,counts_clean],legend=['thermal','clean']) numones=np.zeros((2**5,1)) for i in range(2**5): numones[i]=bin(i).count("1") def expectationValue(results): #num_qubits = results[0].header.n_qubits E=np.zeros((len(results),1)) for item in range(0,len(results)): shots = results[item].shots counts = results[item].data.counts for key in list(counts.__dict__.keys()): c=getattr(counts, key)#number of counts E[item] += numones[int(key,0)]*c/shots E_conv = np.zeros_like(E) for j in range(1,len(results)+1): E_conv[j-1] = sum(E[0:j])/j return E, E_conv E_clean, E_conv_clean = expectationValue(job_clean.result().results) E_thermal, E_conv_thermal = expectationValue(job_thermal.result().results) pl.plot(E_conv_clean) pl.plot(E_conv_thermal)
https://github.com/nielsaNTNU/qiskit_utilities
nielsaNTNU
import numpy as np import pylab as pl import qiskit.tools.jupyter from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.quantum_info import Kraus, SuperOp from qiskit.providers.aer import QasmSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit import * from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import QuantumError, ReadoutError from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error backendname_sim = Aer.get_backend('qasm_simulator') circ = QuantumCircuit(2,2) circ.h(0) circ.cx(0,1) circ.measure(0,0) circ.measure(1,1) circ.draw(output='mpl') circs=[] for i in range(1024): circs.append(circ) job_clean = execute(circs, backendname_sim, shots=1024) results_clean=job_clean.result().results # counts_clean=job.result().get_counts() # plot_histogram(counts_clean) # T1 and T2 values for qubits 0-4 T1s = np.random.normal(50e2, 10e2, 5) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e2, 10e2, 5) # Sampled from normal distribution mean 50 microsec # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(5)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(5): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(5): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) job_thermal = execute(circs, backendname_sim, basis_gates=noise_thermal.basis_gates, noise_model=noise_thermal,shots=1024) results_thermal=job_thermal.result().results # result_thermal = job.result() counts_clean = job_clean.result().get_counts(0) counts_thermal = job_thermal.result().get_counts(0) # Plot noisy output plot_histogram([counts_thermal,counts_clean],legend=['thermal','clean']) numones=np.zeros((2**5,1)) for i in range(2**5): numones[i]=bin(i).count("1") def expectationValue(results): #num_qubits = results[0].header.n_qubits E=np.zeros((len(results),1)) for item in range(0,len(results)): shots = results[item].shots counts = results[item].data.counts for key in list(counts.__dict__.keys()): c=getattr(counts, key)#number of counts E[item] += numones[int(key,0)]*c/shots E_conv = np.zeros_like(E) for j in range(1,len(results)+1): E_conv[j-1] = sum(E[0:j])/j return E, E_conv E_clean, E_conv_clean = expectationValue(job_clean.result().results) E_thermal, E_conv_thermal = expectationValue(job_thermal.result().results) pl.plot(E_conv_clean) pl.plot(E_conv_thermal)
https://github.com/nielsaNTNU/qiskit_utilities
nielsaNTNU
import numpy as np import os import datetime import time import pickle from qiskit import * from qiskit.providers.jobstatus import JOB_FINAL_STATES, JobStatus def start_or_retrieve_job(filename, backend, circuit=None, options=None): """function that 1) retrieves the job from the backend if saved to file, 2) or executes a job on a backend and saves it to file Parameters ---------- filename : string The filename to write/read from. The extension ".job" is automatically appended to the string. backend : qiskit.providers.ibmq.ibmqbackend.IBMQBackend The backend where the job has been/is to be executed. circuit : qiskit.circuit.quantumcircuit.QuantumCircuit, optional The circuit that is to be executed. options: dict, optional The following is a list of all options and their default value options={'shots': 1024, 'forcererun': False, 'useapitoken': False, 'directory': 'jobs'} the directory is created if it does not exist Returns ------- job : qiskit.providers.ibmq.job.ibmqjob.IBMQJob, qiskit.providers.aer.aerjob.AerJob """ ### options parsing if options == None: options={} shots = options.get('shots', 1024) forcererun = options.get('forcererun', False) useapitoken = options.get('useapitoken', False) directory = options.get('directory', 'jobs') filename = filename+'.job' if not os.path.exists(directory): os.makedirs(directory) if not(forcererun) and os.path.isfile(directory+'/'+filename): #read job id from file and retrieve the job with open(directory+'/'+filename, 'r') as f: apitoken = f.readline().rstrip() backendname = f.readline().rstrip() job_id = f.readline().rstrip() if useapitoken: IBMQ.save_account(apitoken, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend_tmp = provider.get_backend(backendname) if backend.name() != backend_tmp.name(): raise Exception("The backend of the job was "+backend_tmp.name()+", but you requested "+backend.name()) job = backend_tmp.retrieve_job(job_id) else: job = backend.retrieve_job(job_id) else: # otherwise start the job and write the id to file hasnotrun = True while hasnotrun: error = False try: job = execute(circuit, backend, shots=int(shots)) except Exception as e: error = True sec = 60 if "Error code: 3458" in str(e): print(filename +' No credits available, retry in '+str(sec)+' seconds'+', time='+str(datetime.datetime.now()), end='\r') else: print('{j} Error! Code: {c}, Message: {m}, Time {t}'.format(j=str(filename), c = type(e).__name__, m = str(e), t=str(datetime.datetime.now())), ", retry in ",str(sec),' seconds', end='\r') time.sleep(sec) if not(error): hasnotrun = False job_id = job.job_id() apitoken = IBMQ.active_account()['token'] backendname = backend.name() if job_id != '': file = open(directory+'/'+filename,'w') file.write(apitoken+'\n') file.write(backendname+'\n') file.write(job_id) file.close() return job def write_results(filename, job, options=None): """function that writes the results of a job to file Parameters ---------- filename : string The filename to write to. The extension ".result" is automatically appended to the string. job : qiskit.providers.ibmq.job.ibmqjob.IBMQJob, qiskit.providers.aer.aerjob.AerJob The job to get the results from options: dict, optional The following is a list of all options and their default value options={'overwrite': False, 'directory': 'results'} Returns ------- success : bool set to True if the results from the job are written to file it is set to False, e.g., if the job has not yet finished successfully """ ### options parsing if options == None: options={} overwrite = options.get('overwrite', False) directory = options.get('directory', 'results') filename=filename+'.result' if not os.path.exists(directory): os.makedirs(directory) success = False fileexists = os.path.isfile(directory+'/'+filename) if (fileexists and overwrite) or not(fileexists): jobstatus = job.status() if jobstatus == JobStatus.DONE: res=job.result().results tmpfile = open(directory+'/'+filename,'wb') pickle.dump(res,tmpfile) tmpfile.close() success = True return success def read_results(filename, options=None): """function that reads results from file Parameters ---------- filename : string The filename to read from. The extension ".result" is automatically appended to the string. options: dict, optional The following is a list of all options and their default value options={'directory': 'results'} Returns ------- results : Object the form is dictated by job.result().results can be None, if the file does not exist success : bool set to True if the results """ ### options parsing if options == None: options={} directory = options.get('directory', 'results') filename=filename+'.result' results = None if os.path.isfile(directory+'/'+filename): tmpfile = open(directory+'/'+filename,'rb') results=pickle.load(tmpfile) tmpfile.close() return results def get_id_error_rate(backend): errorrate=[] gates=backend.properties().gates for i in range(0,len(gates)): if getattr(gates[i],'gate') == 'id': gerror = getattr(getattr(gates[i],'parameters')[0], 'value') errorrate.append(gerror) return errorrate def get_U3_error_rate(backend): errorrate=[] gates=backend.properties().gates for i in range(0,len(gates)): if getattr(gates[i],'gate') == 'u3': gerror = getattr(getattr(gates[i],'parameters')[0], 'value') errorrate.append(gerror) return errorrate def get_T1(backend): val=[] unit=[] gates=backend.properties().gates for i in range(backend.configuration().n_qubits): qubit=backend.properties().qubits[i][0] assert qubit.name == 'T1' val.append(qubit.value) unit.append(qubit.unit) return val, unit def get_T2(backend): val=[] unit=[] gates=backend.properties().gates for i in range(backend.configuration().n_qubits): qubit=backend.properties().qubits[i][1] assert qubit.name == 'T2' val.append(qubit.value) unit.append(qubit.unit) return val, unit def get_readouterrors(backend): val=[] gates=backend.properties().gates for i in range(backend.configuration().n_qubits): qubit=backend.properties().qubits[i][3] assert qubit.name == 'readout_error' val.append(qubit.value) return val def get_prob_meas0_prep1(backend): val=[] gates=backend.properties().gates for i in range(backend.configuration().n_qubits): qubit=backend.properties().qubits[i][4] assert qubit.name == 'prob_meas0_prep1' val.append(qubit.value) return val def get_prob_meas1_prep0(backend): val=[] gates=backend.properties().gates for i in range(backend.configuration().n_qubits): qubit=backend.properties().qubits[i][5] assert qubit.name == 'prob_meas1_prep0' val.append(qubit.value) return val def get_cx_error_map(backend): """ function that returns a 2d array containing CX error rates. """ num_qubits=backend.configuration().n_qubits two_qubit_error_map = np.zeros((num_qubits,num_qubits)) backendproperties=backend.properties() gates=backendproperties.gates for i in range(0,len(gates)): if getattr(gates[i],'gate') == 'cx': cxname = getattr(gates[i],'name') error = getattr(getattr(gates[i],'parameters')[0], 'value') #print(cxname, error) for p in range(num_qubits): for q in range(num_qubits): if p==q: continue if cxname == 'cx'+str(p)+'_'+str(q): two_qubit_error_map[p][q] = error break return two_qubit_error_map def getNumberOfControlledGates(circuit): """function that returns the number of CX, CY, CZ gates. N.B.: swap gates are counted as 3 CX gates. """ numCx=0 numCy=0 numCz=0 for instr, qargs, cargs in circuit.data: gate_string = instr.qasm() if gate_string == "swap": numCx += 3 elif gate_string == "cx": numCx += 1 elif gate_string == "cy": numCy += 1 elif gate_string == "cz": numCz += 1 return numCx, numCy, numCz def convert_to_binarystring(results): list=[] for item in range(0,len(results)): dict={} co = results[item].data.counts for i in range(0,2**5): if(hasattr(co,hex(i))): binstring="{0:b}".format(i).zfill(5) counts = getattr(co, hex(i)) dict[binstring] = counts list.append(dict) return list
https://github.com/mspronesti/qlearnkit
mspronesti
!pip install qlearnkit['pennylane'] !pip install matplotlib import qlearnkit as ql import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from matplotlib import pyplot as plt tag_to_ix = {"DET": 0, "NN": 1, "V": 2} # Assign each tag with a unique index ix_to_tag = {i: k for k, i in tag_to_ix.items()} def prepare_sequence(seq, to_ix): idxs = [to_ix[w] for w in seq] return torch.tensor(idxs, dtype=torch.long) training_data = [ # Tags are: DET - determiner; NN - noun; V - verb # For example, the word "The" is a determiner ("The dog ate the apple".split(), ["DET", "NN", "V", "DET", "NN"]), ("Everybody read that book".split(), ["NN", "V", "DET", "NN"]) ] word_to_ix = {} # For each words-list (sentence) and tags-list in each tuple of training_data for sent, tags in training_data: for word in sent: if word not in word_to_ix: # word has not been assigned an index yet word_to_ix[word] = len(word_to_ix) # Assign each word with a unique index print(f"Vocabulary: {word_to_ix}") print(f"Entities: {ix_to_tag}") class LSTMTagger(nn.Module): def __init__(self, model, embedding_dim, hidden_dim, vocab_size, tagset_size): super(LSTMTagger, self).__init__() self.hidden_dim = hidden_dim self.word_embeddings = nn.Embedding(vocab_size, embedding_dim) self.model = model # The linear layer that maps from hidden state space to tag space self.hidden2tag = nn.Linear(hidden_dim, tagset_size) def forward(self, sentence): embeds = self.word_embeddings(sentence) lstm_out, _ = self.model(embeds.view(len(sentence), 1, -1)) tag_logits = self.hidden2tag(lstm_out.view(len(sentence), -1)) tag_scores = F.log_softmax(tag_logits, dim=1) return tag_scores embedding_dim = 8 hidden_dim = 6 n_layers = 1 n_qubits = 4 n_epochs = 300 device = 'default.qubit' def trainer(lstm_model, embedding_dim, hidden_dim, n_epochs, model_label): # the LSTM Tagger Model model = LSTMTagger(lstm_model, embedding_dim, hidden_dim, vocab_size=len(word_to_ix), tagset_size=len(tag_to_ix)) # loss function and Stochastic Gradient Descend # as optimizers loss_function = nn.NLLLoss() optimizer = optim.SGD(model.parameters(), lr=0.1) history = { 'loss': [], 'acc': [] } for epoch in range(n_epochs): losses = [] preds = [] targets = [] for sentence, tags in training_data: # Step 1. Remember that Pytorch accumulates gradients. # We need to clear them out before each instance model.zero_grad() # Step 2. Get our inputs ready for the network, that is, turn them into # Tensors of word indices. sentence_in = prepare_sequence(sentence, word_to_ix) labels = prepare_sequence(tags, tag_to_ix) # Step 3. Run our forward pass. tag_scores = model(sentence_in) # Step 4. Compute the loss, gradients, and update the parameters by # calling optimizer.step() loss = loss_function(tag_scores, labels) loss.backward() optimizer.step() losses.append(float(loss)) probs = torch.softmax(tag_scores, dim=-1) preds.append(probs.argmax(dim=-1)) targets.append(labels) avg_loss = np.mean(losses) history['loss'].append(avg_loss) # print("preds", preds) preds = torch.cat(preds) targets = torch.cat(targets) corrects = (preds == targets) accuracy = corrects.sum().float() / float(targets.size(0)) history['acc'].append(accuracy) print(f"Epoch {epoch + 1} / {n_epochs}: Loss = {avg_loss:.3f} Acc = {accuracy:.2f}") with torch.no_grad(): input_sentence = training_data[0][0] labels = training_data[0][1] inputs = prepare_sequence(input_sentence, word_to_ix) tag_scores = model(inputs) tag_ids = torch.argmax(tag_scores, dim=1).numpy() tag_labels = [ix_to_tag[k] for k in tag_ids] print(f"Sentence: {input_sentence}") print(f"Labels: {labels}") print(f"Predicted: {tag_labels}") fig, ax1 = plt.subplots() ax1.set_xlabel("Epoch") ax1.set_ylabel("Loss") ax1.plot(history['loss'], label=f"{model_label} Loss") ax2 = ax1.twinx() ax2.set_ylabel("Accuracy") ax2.plot(history['acc'], label=f"{model_label} LSTM Accuracy", color='tab:red') plt.title("Part-of-Speech Tagger Training") plt.ylim(0., 1.5) plt.legend(loc="upper right") plt.show() import qlearnkit.nn as qnn qlstm = qnn.QLongShortTermMemory( embedding_dim, hidden_dim, n_layers, n_qubits=n_qubits, device=device ) # random values to feed into the QNode inputs = torch.rand(embedding_dim, n_qubits) weights = torch.rand(n_layers, n_qubits, 3) import pennylane as qml dev = qml.device(device, wires=n_qubits) circ = qml.QNode(qlstm._construct_vqc, dev) print(qml.draw(circ, expansion_strategy='device', show_all_wires=True)(inputs, weights)) trainer(qlstm, embedding_dim, hidden_dim, n_epochs, model_label='Hybrid Quantum') clstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=n_layers) trainer(clstm, embedding_dim, hidden_dim, n_epochs,model_label='Classical')
https://github.com/mspronesti/qlearnkit
mspronesti
# TODO: uncomment the next line after release qlearnkit 0.2.0 #!pip install qlearnkit !pip install matplotlib import numpy as np from qlearnkit.algorithms.qsvm import QSVClassifier from sklearn.preprocessing import MinMaxScaler from sklearn.datasets import load_iris from sklearn.svm import SVC from matplotlib import pyplot as plt from qiskit import BasicAer from qiskit.circuit.library import PauliFeatureMap from qiskit.utils import QuantumInstance # import some data to play with iris = load_iris() mms = MinMaxScaler() X = iris.data[:, :2] # we only take the first two features. We could # avoid this ugly slicing by using a two-dim dataset X = mms.fit_transform(X) y = iris.target seed = 42 encoding_map = PauliFeatureMap(2) quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'), shots=1024, optimization_level=1, seed_simulator=seed, seed_transpiler=seed) svc = SVC(kernel='linear') qsvc = QSVClassifier(encoding_map=encoding_map, quantum_instance=quantum_instance) svc.fit(X,y) qsvc.fit(X,y) h = 0.1 # step size in the mesh # create a mesh to plot in x_min, x_max = X[:, 0].min() - 0.2, X[:, 0].max() + 0.2 y_min, y_max = X[:, 1].min() - 0.2, X[:, 1].max() + 0.2 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # title for the plots titles = ['SVC with linear kernel', 'QSVC with Pauli feature map'] for i, clf in enumerate((svc, qsvc)): # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, x_max]x[y_min, y_max]. plt.subplot(2, 1, i + 1) plt.subplots_adjust(wspace=0.4, hspace=0.4) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap="RdBu", alpha=0.8) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, cmap="RdBu",edgecolor="grey" ) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.title(titles[i]) plt.show()
https://github.com/mspronesti/qlearnkit
mspronesti
import logging from typing import Union, Optional, List import numpy as np from abc import abstractmethod from qiskit import QuantumCircuit from qiskit.providers import Backend from qiskit.result import Result from sklearn.base import TransformerMixin from qiskit.utils import QuantumInstance from qiskit.exceptions import QiskitError logger = logging.getLogger(__name__) class QuantumEstimator(TransformerMixin): def __init__( self, encoding_map=None, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None, ): """ Args: encoding_map: Map to classical data to quantum states. This class does not impose any constraint on it. It can either be a custom encoding map or a qiskit FeatureMap quantum_instance: The quantum instance to set. Can be a :class:`~qiskit.utils.QuantumInstance` or a :class:`~qiskit.providers.Backend` """ self.X_train = np.asarray([]) self.y_train = np.asarray([]) self._encoding_map = encoding_map self._set_quantum_instance(quantum_instance) @abstractmethod def fit(self, X_train: np.ndarray, y_train: np.ndarray): """ Fits the model using X as training dataset and y as training labels Args: X_train: training dataset y_train: training labels """ raise NotImplementedError("Must have implemented this.") @abstractmethod def predict(self, X_test: np.ndarray) -> np.ndarray: """ Predicts the labels associated to the unclassified data X_test Args: X_test: the unclassified data Returns: the labels associated to X_test """ raise NotImplementedError("Must have implemented this.") @property def quantum_instance(self) -> QuantumInstance: """Returns the quantum instance to evaluate the circuit.""" return self._quantum_instance @quantum_instance.setter def quantum_instance( self, quantum_instance: Optional[Union[QuantumInstance, Backend]] ): """Quantum Instance setter""" self._set_quantum_instance(quantum_instance) def _set_quantum_instance( self, quantum_instance: Optional[Union[QuantumInstance, Backend]] ): """ Internal method to set a quantum instance according to its type Args: The quantum instance to set. Can be a :class:``~qiskit.utils.QuantumInstance``, a :class:`~qiskit.providers.Backend` or a :class:`~qiskit.providers.BaseBackend` """ if isinstance(quantum_instance, Backend): quantum_instance = QuantumInstance(quantum_instance) self._quantum_instance = quantum_instance @property def encoding_map(self): """Returns the Encoding Map""" return self._encoding_map @encoding_map.setter def encoding_map(self, encoding_map): """Encoding Map setter""" self._encoding_map = encoding_map def execute( self, qcircuits: Union[QuantumCircuit, List[QuantumCircuit]] ) -> Union[Optional[Result], None]: """ Executes the given quantum circuit Args: qcircuits: a :class:`~qiskit.QuantumCircuit` or a list of this type to be executed Returns: the execution results """ if self._quantum_instance is None: raise QiskitError("Circuits execution requires a quantum instance") logger.info("Executing circuits...") # Instead of transpiling and assembling the quantum object # and running the backend, we call execute from the quantum # instance that does it at once a very efficient way # please notice: this execution is parallelized # which is why we pass a list of circuits and not one at a time result = self._quantum_instance.execute(qcircuits) return result @abstractmethod def score( self, X: np.ndarray, y: np.ndarray, sample_weight: Optional[np.ndarray] = None ) -> float: """ Returns a score of this model given samples and true values for the samples. In case of classification, this value should correspond to mean accuracy, in case of regression, the coefficient of determination :math:`R^2` of the prediction. In case of clustering, the `y` parameter is typically ignored. Args: X: array-like of shape (n_samples, n_features) y: array-like of labels of shape (n_samples,) sample_weight: array-like of shape (n_samples,), default=None The weights for each observation in X. If None, all observations are assigned equal weight. Returns: a float score of the model. """ raise NotImplementedError("Must have implemented this.")
https://github.com/mspronesti/qlearnkit
mspronesti
import warnings import logging import numpy as np from copy import deepcopy from typing import List, Dict, Union, Optional from qiskit import QuantumCircuit from qiskit.result import Result from qiskit.providers import Backend from qiskit.tools import parallel_map from qiskit.utils import QuantumInstance from sklearn.exceptions import NotFittedError from sklearn.base import ClusterMixin from ..quantum_estimator import QuantumEstimator from .centroid_initialization import random, kmeans_plus_plus, naive_sharding from .qkmeans_circuit import construct_circuit logger = logging.getLogger(__name__) class QKMeans(ClusterMixin, QuantumEstimator): """ The Quantum K-Means algorithm for classification Note: The naming conventions follow the KMeans from sklearn.cluster Example: Classify data using the Iris dataset. .. jupyter-execute:: import numpy as np import matplotlib.pyplot as plt from qlearnkit.algorithms import QKMeans from qiskit import BasicAer from qiskit.utils import QuantumInstance, algorithm_globals from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split seed = 42 algorithm_globals.random_seed = seed quantum_instance = QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024, optimization_level=1, seed_simulator=seed, seed_transpiler=seed) # Use iris data set for training and test data X, y = load_iris(return_X_y=True) num_features = 2 X = np.asarray([x[0:num_features] for x, y_ in zip(X, y) if y_ != 2]) y = np.asarray([y_ for x, y_ in zip(X, y) if y_ != 2]) qkmeans = QKMeans(n_clusters=3, quantum_instance=quantum_instance ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=seed) qkmeans.fit(X_train) print(qkmeans.labels_) print(qkmeans.cluster_centers_) # Plot the results colors = ['blue', 'orange', 'green'] for i in range(X_train.shape[0]): plt.scatter(X_train[i, 0], X_train[i, 1], color=colors[qkmeans.labels_[i]]) plt.scatter(qkmeans.cluster_centers_[:, 0], qkmeans.cluster_centers_[:, 1], marker='*', c='g', s=150) plt.show() # Predict new points prediction = qkmeans.predict(X_test) print(prediction) """ def __init__( self, n_clusters: int = 6, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None, *, init: Union[str, np.ndarray] = "kmeans++", n_init: int = 1, max_iter: int = 30, tol: float = 1e-4, random_state: int = 42, ): """ Args: n_clusters: The number of clusters to form as well as the number of centroids to generate. quantum_instance: the quantum instance to set. Can be a :class:`~qiskit.utils.QuantumInstance` or a :class:`~qiskit.providers.Backend` init: Method of initialization of centroids. n_init: Number of time the qkmeans algorithm will be run with different centroid seeds. max_iter: Maximum number of iterations of the qkmeans algorithm for a single run. tol: Tolerance with regard to the difference of the cluster centroids of two consecutive iterations to declare convergence. random_state: Determines random number generation for centroid initialization. """ super().__init__(quantum_instance=quantum_instance) self.n_clusters = n_clusters self.init = init self.max_iter = max_iter self.n_iter_ = 0 self.tol = tol self.n_init = n_init self.n_clusters = n_clusters self.random_state = random_state self.cluster_centers_ = None # do not rename : this name is needed for # `fit_predict` inherited method from # `ClusterMixin` base class self.labels_ = None def _init_centroid( self, X: np.ndarray, init: Union[str, np.ndarray], random_state: int ): """ Initializes the centroids according to the following criteria: 'kmeans++': Create cluster centroids using the k-means++ algorithm. 'random': Create random cluster centroids. 'naive_sharding': Create cluster centroids using deterministic naive sharding algorithm. If an array is passed, it should be of shape (n_clusters, n_features) and gives the initial centers. Args: X: Training dataset. init: Method of initialization of centroids. random_state: Determines random number generation for centroid initialization. """ if isinstance(init, str): if init == "random": self.cluster_centers_ = random(X, self.n_clusters, random_state) elif init == "kmeans++": self.cluster_centers_ = kmeans_plus_plus( X, self.n_clusters, random_state ) elif init == "naive": self.cluster_centers_ = naive_sharding(X, self.n_clusters) else: raise ValueError( f"Unknown centroids initialization method {init}. " f"Expected random, kmeans++, naive or vector of " f"centers, but {init} was provided" ) else: self.cluster_centers_ = init def _recompute_centroids(self): """ Reassign centroid value to be the calculated mean value for each cluster. If a cluster is empty the corresponding centroid remains the same. """ for i in range(self.n_clusters): if np.sum(self.labels_ == i) != 0: self.cluster_centers_[i] = np.mean( self.X_train[self.labels_ == i], axis=0 ) def _compute_distances_centroids(self, counts: Dict[str, int]) -> List[int]: """ Compute distance, without explicitly measure it, of a point with respect to all the centroids using a dictionary of counts, which refers to the following circuit: .. parsed-literal:: ┌───┐ ┌───┐ |0anc>: ┤ H ├────────────■──────┤ H ├────────M └───┘ | └───┘ ┌───┐ ┌────┐ | |0>: ───┤ H ├───┤ U3 ├───X────────── └───┘ └────┘ | ┌───┐ ┌────┐ | |0>: ───┤ H ├───┤ U3 ├───X────────── └───┘ └────┘ Args: counts: Counts resulting after the simulation. Returns: The computed distance. """ distance_centroids = [0] * self.n_clusters x = 1 for i in range(0, self.n_clusters): binary = format(x, "b").zfill(self.n_clusters) distance_centroids[i] = counts[binary] if binary in counts else 0 x = x << 1 return distance_centroids def _get_distances_centroids(self, results: Result) -> np.ndarray: """ Retrieves distances from counts via :func:`_compute_distances_centroids` Args: results: :class:`~qiskit.Result` object of execution results Returns: np.ndarray of distances """ counts = results.get_counts() # compute distance from centroids using counts distances_list = list( map(lambda count: self._compute_distances_centroids(count), counts) ) return np.asarray(distances_list) def _construct_circuits(self, X_test: np.ndarray) -> List[QuantumCircuit]: """ Creates the circuits to be executed on the gated quantum computer for the classification process Args: X_test: The unclassified input data. Returns: List of quantum circuits created for the computation """ logger.info("Starting circuits construction ...") """ circuits = [] for xt in X_test: circuits.append(construct_circuit(xt, self.cluster_centers_, self.n_clusters)) """ circuits = parallel_map( construct_circuit, X_test, task_args=[self.cluster_centers_, self.n_clusters], ) logger.info("Done.") return circuits def fit(self, X: np.ndarray, y: np.ndarray = None): """ Fits the model using X as training dataset and y as training labels. For the qkmeans algorithm y is ignored. The fit model creates clusters from the training dataset given as input Args: X: training dataset y: Ignored. Kept here for API consistency Returns: trained QKMeans object """ self.X_train = np.asarray(X) self._init_centroid(self.X_train, self.init, self.random_state) self.labels_ = np.zeros(self.X_train.shape[0]) error = np.inf self.n_iter_ = 0 # while error not below tolerance, reiterate the # centroid computation for a maximum of `max_iter` times while error > self.tol and self.n_iter_ < self.max_iter: # construct circuits using training data # notice: the construction uses the centroids # which are recomputed after every iteration circuits = self._construct_circuits(self.X_train) # executing and computing distances from centroids results = self.execute(circuits) distances = self._get_distances_centroids(results) # assigning clusters and recomputing centroids self.labels_ = np.argmin(distances, axis=1) cluster_centers_old = deepcopy(self.cluster_centers_) self._recompute_centroids() # evaluating error and updating iteration count error = np.linalg.norm(self.cluster_centers_ - cluster_centers_old) self.n_iter_ = self.n_iter_ + 1 if self.n_iter_ == self.max_iter: warnings.warn( f"QKMeans failed to converge after " f"{self.max_iter} iterations." ) return self def predict(self, X_test: np.ndarray) -> np.ndarray: """Predict the labels of the provided data. Args: X_test: ndarray, test samples Returns: Index of the cluster each sample belongs to. """ if self.labels_ is None: raise NotFittedError( "This QKMeans instance is not fitted yet. " "Call 'fit' with appropriate arguments before using " "this estimator." ) circuits = self._construct_circuits(X_test) results = self.execute(circuits) distances = self._get_distances_centroids(results) predicted_labels = np.argmin(distances, axis=1) return predicted_labels def score( self, X: np.ndarray, y: np.ndarray = None, sample_weight: Optional[np.ndarray] = None, ) -> float: """ Returns Mean Silhouette Coefficient for all samples. Args: X: array of features y: Ignored. Not used, present here for API consistency by convention. sample_weight: Ignored. Not used, present here for API consistency by convention. Returns: Mean Silhouette Coefficient for all samples. """ from sklearn.metrics import silhouette_score predicted_labels = self.predict(X) return silhouette_score(X, predicted_labels)
https://github.com/mspronesti/qlearnkit
mspronesti
import logging import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister logger = logging.getLogger(__name__) def _map_function(x): r""" We map data feature values to :math:`\theta` and :math:`\phi` values using the following eqaution: .. math:: \phi = (x + 1) \frac{\pi}{2} where :math:`\phi` is the phase and :math:`\theta` the angle """ return (x + 1) * np.pi / 2 def _map_features(input_point, centroids, n_centroids: int): r""" Map the input point and the centroids to :math:`\theta` and :math:`\phi` values via the :func:`_map_function` method. Args: input_point: Input point to map. centroids: Array of points to map. n_centroids: Number of centroids. Returns: Tuple containing input point and centroids mapped. """ phi_centroids_list = [] theta_centroids_list = [] phi_input = _map_function(input_point[0]) theta_input = _map_function(input_point[1]) for i in range(0, n_centroids): phi_centroids_list.append(_map_function(centroids[i][0])) theta_centroids_list.append(_map_function(centroids[i][1])) return phi_input, theta_input, phi_centroids_list, theta_centroids_list def construct_circuit(input_point: np.ndarray, centroids: np.ndarray, k: int) -> QuantumCircuit: """ Apply a Hadamard to the ancillary qubit and our mapped data points. Encode data points using U3 gate. Perform controlled swap to entangle the state with the ancillary qubit Apply another Hadamard gate to the ancillary qubit. .. parsed-literal:: ┌───┐ ┌───┐ |0anc>: ┤ H ├────────────■──────┤ H ├────────M └───┘ | └───┘ ┌───┐ ┌────┐ | |0>: ───┤ H ├───┤ U3 ├───X────────── └───┘ └────┘ | ┌───┐ ┌────┐ | |0>: ───┤ H ├───┤ U3 ├───X────────── └───┘ └────┘ Args: input_point: Input point from which calculate the distance. centroids: Array of points representing the centroids to calculate the distance to k: Number of centroids Returns: The quantum circuit created """ phi_input, theta_input, phi_centroids_list, theta_centroids_list = \ _map_features(input_point, centroids, k) # We need 3 quantum registers, of size k one for a data point (input), # one for each centroid and one for each ancillary qreg_input = QuantumRegister(k, name='qreg_input') qreg_centroid = QuantumRegister(k, name='qreg_centroid') qreg_psi = QuantumRegister(k, name='qreg_psi') # Create a k bit ClassicalRegister to hold the result # of the measurements creg = ClassicalRegister(k, 'creg') # Create the quantum circuit containing our registers qc = QuantumCircuit(qreg_input, qreg_centroid, qreg_psi, creg, name='qc') for i in range(0, k): # Apply Hadamard qc.h(qreg_psi[i]) qc.h(qreg_input[i]) qc.h(qreg_centroid[i]) # Encode new point and centroid qc.u(theta_input, phi_input, 0, qreg_input[i]) qc.u(theta_centroids_list[i], phi_centroids_list[i], 0, qreg_centroid[i]) # Perform controlled swap qc.cswap(qreg_psi[i], qreg_input[i], qreg_centroid[i]) # Apply second Hadamard to ancillary qc.h(qreg_psi[i]) # Measure ancillary qc.measure(qreg_psi[i], creg[i]) return qc
https://github.com/mspronesti/qlearnkit
mspronesti
import numbers from abc import ABC from typing import List, Dict, Optional, Union import numpy as np import logging from qiskit import QuantumCircuit from qiskit.providers import Backend from qiskit.result import Result from qiskit.tools import parallel_map from qiskit.utils import QuantumInstance from ..quantum_estimator import QuantumEstimator from ...circuits import SwaptestCircuit from ...encodings import EncodingMap logger = logging.getLogger(__name__) class QNeighborsBase(QuantumEstimator, ABC): def __init__(self, n_neighbors: int = 3, encoding_map: Optional[EncodingMap] = None, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None): """ Base class for Nearest Neighbors algorithms Args: n_neighbors: number of neighbors. It's the :math:`k` parameter of the knn algorithm encoding_map: map to classical data to quantum states. This class does not impose any constraint on it. quantum_instance: the quantum instance to set. Can be a :class:`~qiskit.utils.QuantumInstance` or a :class:`~qiskit.providers.Backend` """ super().__init__(encoding_map, quantum_instance) if n_neighbors <= 0: raise ValueError(f"Expected n_neighbors > 0. Got {n_neighbors}") elif not isinstance(n_neighbors, numbers.Integral): raise TypeError( "n_neighbors does not take %s value, enter integer value" % type(n_neighbors) ) self.n_neighbors = n_neighbors def fit(self, X, y): """ Fits the model using X as training dataset and y as training labels Args: X: training dataset y: training labels """ self.X_train = np.asarray(X) self.y_train = np.asarray(y) logger.info("setting training data: ") for _X, _y in zip(X, y): logger.info("%s: %s", _X, _y) def _compute_fidelity(self, counts: Dict[str, int]): r""" Computes the fidelity, used as a measure of distance, from a dictionary of counts, which refers to the swap test circuit having a test datapoint and a train datapoint as inputs employing the following formula .. math:: \sqrt{\left | \frac{counts[0] - counts[1]}{n\_shots} \right | } Args: counts: the counts resulting after the simulation Returns: the computed fidelity """ counts_0 = counts.get('0', 0) counts_1 = counts.get('1', 1) # squared fidelity f_2 = np.abs(counts_0 - counts_1) / self._quantum_instance.run_config.shots return np.sqrt(f_2) def _get_fidelities(self, results: Result, test_size: int) -> np.ndarray: r""" Retrieves the list of all fidelities given the circuit results, computed via the :func:`calculate_fidelities` method Args: results: the simulation results test_size: the size of the test dataset Returns: numpy ndarray of all fidelities """ train_size = self.X_train.shape[0] all_counts = results.get_counts() # List[Dict(str, int)] fidelities = np.empty( shape=(test_size, train_size) ) for i, (counts) in enumerate(all_counts): fidelity = self._compute_fidelity(counts) # the i-th subarray of the ndarray `fidelities` contains # the values that we will use for the majority voting to # predict the label of the i-th test input data fidelities[i // train_size][i % train_size] = fidelity return fidelities @staticmethod def _construct_circuit(feature_vector_1: np.ndarray, feature_vector_2: np.ndarray, encoding_map: EncodingMap = None) -> QuantumCircuit: r""" Constructs a swap test circuit employing a controlled swap. For instance .. parsed-literal:: ┌───┐ ┌───┐┌─┐ q_0: ────┤ H ├─────■─┤ H ├┤M├ ┌───┴───┴───┐ │ └───┘└╥┘ q_1: ┤ circuit-0 ├─X───────╫─ ├───────────┤ │ ║ q_2: ┤ circuit-1 ├─X───────╫─ └───────────┘ ║ c: 1/══════════════════════╩═ 0 where feature_vector_1 = [1,0], feature_vector_2 = [0, 1] A swap test circuit allows to measure the fidelity between two quantum states, which can be interpreted as a distance measure of some sort. In other words, given two quanutm states :math:`|\alpha\rangle, \ |\beta\rangle` it measures how symmetric the state :math:`|\alpha\rangle \otimes |\beta\rangle` is Args: feature_vector_1: first feature vector feature_vector_2: second feature vector encoding_map: the mapping to quantum state to extract a :class:`~qiskit.QuantumCircuit` Returns: swap test circuit """ if len(feature_vector_1) != len(feature_vector_2): raise ValueError("Input state vectors must have same length to" "perform swap test. Lengths were:" f"{len(feature_vector_1)}" f"{len(feature_vector_2)}") if encoding_map is None: raise ValueError("encoding map must be specified to construct" "swap test circuit") q1 = encoding_map.construct_circuit(feature_vector_1) q2 = encoding_map.construct_circuit(feature_vector_2) return SwaptestCircuit(q1, q2) def _construct_circuits(self, X_test: np.ndarray) -> List[QuantumCircuit]: """ Creates the circuits to be executed on the gated quantum computer for the classification process Args: X_test: the unclassified input data """ logger.info("Starting parallel circuits construction ...") circuits = [] for i, xtest in enumerate(X_test): # computing distance of xtest with respect to # each point in X_train circuits_line = parallel_map( QNeighborsBase._construct_circuit, self.X_train, task_args=[xtest, self._encoding_map] ) circuits = circuits + circuits_line logger.info("Done.") return circuits def _kneighbors(self, y_train: np.ndarray, fidelities: np.ndarray, *, return_indices=False): """ Retrieves the training labels associated to the :math:`k` nearest neighbors and (optionally) their indices Args: y_train: the training labels fidelities: the fidelities array return_indices: (bool) weather to return the indices or not Returns: neigh_labels: ndarray of shape (n_queries, n_neighbors) Array representing the labels of the :math:`k` nearest points neigh_indices: ndarray of shape (n_queries, n_neighbors) Array representing the indices of the :math:`k` nearest points, only present if return_indices=True. """ if np.any(fidelities < -0.2) or np.any(fidelities > 1.2): raise ValueError("Detected fidelities values not in range 0<=F<=1:" f"{fidelities[fidelities < -0.2]}" f"{fidelities[fidelities > 1.2]}") # first sort neighbors neigh_indices = np.argsort(fidelities) # extract indices according to number of neighbors # and dimension n_queries, _ = fidelities.shape if n_queries == 1: neigh_indices = neigh_indices[-self.n_neighbors:] else: neigh_indices = neigh_indices[:, -self.n_neighbors:] neigh_labels = y_train[neigh_indices] if return_indices: return neigh_labels, neigh_indices else: return neigh_labels
https://github.com/mspronesti/qlearnkit
mspronesti
from sklearn.exceptions import NotFittedError import logging import numpy as np from qiskit.providers import Backend from qiskit.utils import QuantumInstance from typing import Optional, Union from sklearn.base import ClassifierMixin import scipy.stats as stats from .qknn_base import QNeighborsBase from ...encodings import EncodingMap logger = logging.getLogger(__name__) class QKNeighborsClassifier(ClassifierMixin, QNeighborsBase): r""" The Quantum K-Nearest Neighbors algorithm for classification Note: The naming conventions follow the KNeighborsClassifier from sklearn.neighbors Example: Classify data using the Iris dataset. .. jupyter-execute:: import numpy as np from qlearnkit.algorithms import QKNeighborsClassifier from qlearnkit.encodings import AmplitudeEncoding from qiskit import BasicAer from qiskit.utils import QuantumInstance, algorithm_globals from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split seed = 42 algorithm_globals.random_seed = seed quantum_instance = QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024, optimization_level=1, seed_simulator=seed, seed_transpiler=seed) encoding_map = AmplitudeEncoding(n_features=2) # Use iris data set for training and test data X, y = load_iris(return_X_y=True) X = np.asarray([x[0:2] for x, y_ in zip(X, y) if y_ != 2]) y = np.asarray([y_ for x, y_ in zip(X, y) if y_ != 2]) qknn = QKNeighborsClassifier( n_neighbors=3, quantum_instance=quantum_instance, encoding_map=encoding_map ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=seed) qknn.fit(X_train, y_train) print(f"Testing accuracy: " f"{qknn.score(X_test, y_test):0.2f}") """ def __init__(self, n_neighbors: int = 3, encoding_map: Optional[EncodingMap] = None, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None): """ Creates a QKNeighborsClassifier Object Args: n_neighbors: number of neighbors participating in the majority vote encoding_map: map to classical data to quantum states. This class does not impose any constraint on it. quantum_instance: the quantum instance to set. Can be a :class:`~qiskit.utils.QuantumInstance` or a :class:`~qiskit.providers.Backend` """ super().__init__(n_neighbors, encoding_map, quantum_instance) def _majority_voting(self, y_train: np.ndarray, fidelities: np.ndarray) -> np.ndarray: r""" Performs the classical majority vote procedure of the K-Nearest Neighbors classifier with the :math:`k` nearest to determine class Args: y_train: the train labels fidelities: the list ``F`` of fidelities used as a measure of distance Returns: a list of predicted labels for the test data Raises: ValueError: if :math:`\exists f \in F \ t.c. f \notin [0, 1]`, assuming a tolerance of `0.2` """ k_nearest = self._kneighbors(y_train, fidelities) # getting most frequent values in `k_nearest` # in a more efficient way than looping and # using, for instance, collections.Counter n_queries = self.X_train.shape[0] if n_queries == 1: # case of 1D array labels, _ = stats.mode(k_nearest, keepdims=True) else: labels, _ = stats.mode(k_nearest, keepdims=True, axis=1) # eventually flatten the np.ndarray # returned by stats.mode return labels.real.flatten() def predict(self, X_test: np.ndarray) -> np.ndarray: """ Predict the labels of the provided data. Args: X_test: ndarray, test samples """ if self.X_train is None: raise NotFittedError( "This QKNeighborsClassifier instance is not fitted yet. " "Call 'fit' with appropriate arguments before using " "this estimator.") circuits = self._construct_circuits(X_test) results = self.execute(circuits) # the execution results are employed to compute # fidelities which are used for the majority voting fidelities = self._get_fidelities(results, len(X_test)) return self._majority_voting(self.y_train, fidelities)
https://github.com/mspronesti/qlearnkit
mspronesti
import logging from typing import Optional, Union import numpy as np from sklearn.base import ClassifierMixin from sklearn.exceptions import NotFittedError from qiskit.utils import QuantumInstance from qiskit.providers import Backend from qiskit.circuit.library import NLocal, ZZFeatureMap from ..quantum_estimator import QuantumEstimator from ..kernel_method_mixin import KernelMethodMixin logger = logging.getLogger(__name__) class QSVClassifier(KernelMethodMixin, ClassifierMixin, QuantumEstimator): r""" The Quantum Support Vector Machine algorithm for classification. Maps datapoints to quantum states using a FeatureMap or similar QuantumCircuit. Example: Classify data using the Iris dataset. .. jupyter-execute:: import numpy as np from qlearnkit.algorithms import QSVClassifier from qiskit import BasicAer from qiskit.utils import QuantumInstance, algorithm_globals from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from qiskit.circuit.library import ZZFeatureMap seed = 42 algorithm_globals.random_seed = seed quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'), shots=1024, optimization_level=1, seed_simulator=seed, seed_transpiler=seed) # Use iris data set for training and test data X, y = load_iris(return_X_y=True) num_features = 2 X = np.asarray([x[0:num_features] for x, y_ in zip(X, y) if y_ != 2]) y = np.asarray([y_ for x, y_ in zip(X, y) if y_ != 2]) encoding_map = ZZFeatureMap(2) qsvc = QSVClassifier( encoding_map=encoding_map, quantum_instance=quantum_instance ) # use iris dataset X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=seed) qsvc.fit(X_train, y_train) print(f"Testing accuracy: " f"{qsvc.score(X_test, y_test):0.2f}") """ def __init__(self, encoding_map: Optional[NLocal] = None, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None, gamma: Union[float, str] = 'scale'): """ Creates a Quantum Support Vector Classifier Args: encoding_map: map to classical data to quantum states. Default: :class:`~qiskit_machine_learning.circuit.library.ZZFeatureMap` quantum_instance: the quantum instance to set. Can be a :class:`~qiskit.utils.QuantumInstance` or a :class:`~qiskit.providers.Backend` gamma: regularization parameter (float or string, default 1.0) Admitted string values: { "scale", "auto" } """ if gamma == 0: raise ValueError( "The gamma value of 0.0 is invalid. Use 'auto' to set" " gamma to a value of 1 / n_features." ) encoding_map = encoding_map if encoding_map else ZZFeatureMap(2) super().__init__(encoding_map, quantum_instance) # Initial setting for _gamma # Numerical value is set in fit method self.gamma = gamma self.label_class_dict = None self.class_label_dict = None self.alpha = None self.bias = None self.n_classes = None def fit(self, X, y): """ Fits the model using X as training dataset and y as training labels. The actual computation is done at the "predict" stage to allow running the qiskit backend only once Args: X: training dataset y: training labels """ self.X_train = np.asarray(X) self.y_train = np.asarray(y) self.n_classes = np.unique(y).size n_features = self.X_train.shape[1] if isinstance(self.gamma, str): if self.gamma == "scale": self._gamma = 1.0 / (n_features * np.var(self.X_train)) elif self.gamma == "auto": self._gamma = 1.0 / n_features else: raise ValueError( "When 'gamma' is a string, it should be either 'scale' or " "'auto'. Got '{}' instead." % self.gamma ) else: self._gamma = self.gamma self.label_class_dict, self.class_label_dict = QSVClassifier._create_label_class_dicts(self.y_train) if self.n_classes == 1: raise ValueError("All samples have the same label") if self.n_classes == 2: classes_matrix = np.array(np.vectorize(self.label_class_dict.get)(self.y_train)) else: # Prepares an array of [+1,-1] values for each class # and organizes them in a matrix per the svm formulation. # This matrix notation will be useful later on to avoid nested for loops. classes_array = np.array([np.vectorize(self.label_class_dict.get)(self.y_train)]) classes_array = classes_array.T classes_matrix = np.equal(classes_array, np.arange(self.n_classes) * np.ones((classes_array.size, self.n_classes))) self.train_classes = classes_matrix * 2 - 1 logger.info("setting training data: ") for _X, _y in zip(X, y): logger.info("%s: %s", _X, _y) # Sets the training matrix to None to signal it must be # recomputed again in case train data changes self._reset_train_matrix() @staticmethod def _create_label_class_dicts(labels): """ Creates dictionaries to convert from labels to classes used by svm. Classes are the integer values in range [0, 1, ..., n_classes] Args: labels: labels for which the dictionaries will be created Returns: dictionaries to convert from the user labels to the internal representation and vice versa """ unique_labels = np.unique(labels) label_class_dict = { unique_labels[i]: i for i in range(unique_labels.size) } class_label_dict = { c: unique_labels[c] for c in range(unique_labels.size) } return label_class_dict, class_label_dict def _compute_alpha(self, train_kernel_matrix): """ Computes alpha parameters for data in the training set. Alpha parameters will be used as weights in prediction. Internally distinguishes between binary and multiclass case Args: train_kernel_matrix: matrix of distances from each point to each point in the training set Returns: numpy ndarray of alpha parameters """ n_train = train_kernel_matrix.shape[0] omega = train_kernel_matrix gamma_inv = 1 / self._gamma ones = np.ones(n_train) eye = np.eye(n_train) A = np.vstack([ np.block([np.zeros(1), ones.reshape([1, n_train])]), np.block([ones.reshape([n_train, 1]), omega + gamma_inv * eye]) ]) if self.n_classes == 2: B = np.vstack([np.zeros(1), self.train_classes.reshape(-1, 1)]) else: B = np.vstack([np.zeros(self.n_classes), self.train_classes]) # Binary case: X is a vector containing alpha values. # Multiclass case: X is a (n_train+1,n_classes) matrix # containing alpha values for each of the n_classes qridge systems. # This is equivalent to solving n_classes distinct binary problems. X = np.linalg.solve(A, B) bias = X[0, :] alpha = np.squeeze(X[1:, :]) return alpha, bias def _compute_predictions_multiclass(self, train_kernel_matrix, test_kernel_matrix): """ Uses kernel matrices to find n_classes dividing hyperplanes, following a one-to-rest approach. Based on Least Squares Support Vector Machine formulation. Actually solves n_classes qridge systems in order to separate multiple classes. Args: train_kernel_matrix: matrix of distances between training datapoints test_kernel_matrix: matrix of distances between training and test datapoints Returns: numpy ndarray of predicted classes. Uses the internal representation """ # Fit self.alpha, self.bias = self._compute_alpha(train_kernel_matrix) # Predict prediction_classes = np.argmax(test_kernel_matrix @ self.alpha + self.bias, axis=1) return prediction_classes def _compute_predictions_binary(self, train_kernel_matrix, test_kernel_matrix): """ Uses kernel matrices to find the dividing hyperplane. Based on Least Squares Support Vector Machine formulation. Specialized case which uses a np.sign call instead of computing multiple hyperplanes and using argmax Args: train_kernel_matrix: matrix of distances between training datapoints test_kernel_matrix: matrix of distances between training and test datapoints Returns: numpy ndarray of predicted classes. Uses the internal representation """ # Fit self.alpha, self.bias = self._compute_alpha(train_kernel_matrix) # Predict prediction_classes = np.sign(test_kernel_matrix @ self.alpha + self.bias) prediction_classes = (prediction_classes + 1) / 2 return prediction_classes def predict(self, X_test: np.ndarray) -> np.ndarray: """ Solves a Least Squares problem to predict value of input data. Internally distinguishes between binary and multiclass case. For the binary case solves an optimization problem to find a dividing hyperplane. For the multiclass case uses a one-to-rest approach and thus needs to run the algorithm n_classes different times. Args: X_test: the test data Returns: numpy ndarray of predicted labels """ if self.X_train is None: raise NotFittedError( "This QSVClassifier instance is not fitted yet. " "Call 'fit' with appropriate arguments before using " "this estimator.") logger.info("Computing kernel matrices...") train_kernel_matrix, test_kernel_matrix = self._compute_kernel_matrices(self.X_train, X_test) logger.info("Done.") logger.info("Computing predictions...") if self.n_classes == 2: classes_predict = self._compute_predictions_binary( train_kernel_matrix, test_kernel_matrix ) else: classes_predict = self._compute_predictions_multiclass(train_kernel_matrix, test_kernel_matrix) # Converts back from internal numerical classes used in SVM # to user provided labels. y_predict = np.vectorize(self.class_label_dict.get)(classes_predict) logger.info("Done.") return y_predict
https://github.com/mspronesti/qlearnkit
mspronesti
from qiskit import QuantumCircuit from typing import Optional class SwaptestCircuit(QuantumCircuit): r""" Constructs a swap test circuit employing a controlled swap: .. parsed-literal:: ┌───┐ ┌───┐┌─┐ q_0: ────┤ H ├─────■─┤ H ├┤M├ ┌───┴───┴───┐ │ └───┘└╥┘ q_1: ┤ circuit-0 ├─X───────╫─ ├───────────┤ │ ║ q_2: ┤ circuit-1 ├─X───────╫─ └───────────┘ ║ c: 1/══════════════════════╩═ 0 A swap test circuit allows to measure the fidelity between two quantum states, which can be interpreted as a distance measure of some sort. In other words, given two quanutm states :math:`|\alpha\rangle, \ |\beta\rangle`, it measures how symmetric the state :math:`|\alpha\rangle \otimes |\beta\rangle` is """ def __init__(self, qc_state_1: QuantumCircuit, qc_state_2: QuantumCircuit, name: Optional[str] = None): n_total = qc_state_1.num_qubits + qc_state_2.num_qubits super().__init__(n_total + 1, 1, name=name) range_qc1 = [i + 1 for i in range(qc_state_1.num_qubits)] range_qc2 = [i + qc_state_1.num_qubits + 1 for i in range(qc_state_1.num_qubits)] self.compose(qc_state_1, range_qc1, inplace=True) self.compose(qc_state_2, range_qc2, inplace=True) # first apply hadamard self.h(0) # then perform controlled swaps for index, qubit in enumerate(range_qc1): self.cswap(0, qubit, range_qc2[index]) # eventually reapply hadamard self.h(0) # Measurement on the auxiliary qubit self.barrier() self.measure(0, 0)
https://github.com/mspronesti/qlearnkit
mspronesti
import numpy as np from qiskit import QuantumCircuit, QuantumRegister from .encoding_map import EncodingMap from ..circuits.circuit_utils import to_basis_gates """Encoding classical data to quantum state via amplitude encoding.""" class AmplitudeEncoding(EncodingMap): """ Amplitude Encoding map """ def __init__(self, n_features: int = 2): super().__init__(n_features) n_qubits = np.log2(n_features) if not n_qubits.is_integer(): # if number of qubits is not a positive # power of 2, an extra qubit is needed n_qubits = np.ceil(n_qubits) elif n_qubits == 0: # in this scenario, n_features = 1 # then we need 1 qubit n_qubits = 1 self._num_qubits = int(n_qubits) def construct_circuit(self, x) -> QuantumCircuit: """ Constructs circuit for amplitude encoding Args: x: 1D classical data vector to be encoded must satisfy len(x) == num_features """ self._check_feature_vector(x) if self.num_features % 2 != 0: # Number of features should be # a positive power of 2 for `initialize`, # then we add some padding x = np.pad(x, (0, (1 << self.num_qubits) - len(x))) state_vector = self.state_vector(x) q = QuantumRegister(self.num_qubits) qc = QuantumCircuit(q) qc.initialize(state_vector, [q[i] for i in range(self.num_qubits)]) # convert final circuit to basis gates # to unwrap the "initialize" block qc = to_basis_gates(qc) # remove the reset gates the unroller added qc.data = [d for d in qc.data if d[0].name != "reset"] return qc def state_vector(self, x): r""" The encoding of a state via amplitude encoding operates as follows: given a quantum state :math:`\psi`, it processes the data such that .. math::\langle\psi|\psi\rangle = 1, Args: x: the classical data Returns: (np.array) encoded quantum state """ if isinstance(x, list): x = np.asarray(x) norm = np.linalg.norm(x) # retrieves the normalized vector # if the norm is not zero return x / norm if not norm == 0 else x
https://github.com/mspronesti/qlearnkit
mspronesti
from .encoding_map import EncodingMap import numpy as np from functools import reduce from qiskit import QuantumCircuit from qiskit.circuit.library.standard_gates import RXGate, RYGate, RZGate """Encoding classical data to quantum state via amplitude encoding.""" class AngleEncoding(EncodingMap): """ Angle Encoding algorithm. Assumes data is feature-normalized. """ def __init__( self, n_features: int = 2, rotation: str = "Y", scaling: float = np.pi / 2 ): r""" Args: rotation: the direction admitted values: X, Y, Z scaling: scaling factor for normalized input data. The default scaling :math:`\pi/2` does not induce a relative phase difference. """ ROT = {"X": RXGate, "Y": RYGate, "Z": RZGate} if rotation not in ROT: raise ValueError("No such rotation direction {}".format(rotation)) super().__init__(n_features) # angle encoding requires 1 qubit # for each feature self._num_qubits = n_features self.gate = ROT[rotation] self.scaling = scaling def construct_circuit(self, x) -> QuantumCircuit: """ Args: x (np.array): The input data to encode Returns: The circuit that encodes x. Assumes data is feature-normalized. Assumes every element in x is in [0, 1] """ self._check_feature_vector(x) circuit = QuantumCircuit(self.num_qubits) for i in range(self.num_qubits): circuit.append(self.gate(2 * self.scaling * x[i]), [i]) return circuit def state_vector(self, x): """ The encoding of a state via angle encoding, operating a rotation around the ``rotation`` axis. Args: x (np.array): The input data to encode Returns: np.array: The state vector representation of x after angle encoding """ qubit_states = [] for x_i in x: qubit_state = self.gate(2 * self.scaling * x_i).to_matrix()[:, 0] qubit_states.append(qubit_state) return reduce(lambda a, b: np.kron(a, b), qubit_states)
https://github.com/mspronesti/qlearnkit
mspronesti
from .encoding_map import EncodingMap from qiskit import QuantumCircuit import numpy as np class BasisEncoding(EncodingMap): def __init__(self, n_features: int = 2): """ Initializes Basis Encoding Map """ super().__init__(n_features) # basis encoding requires 1 qubit # for each feature self._num_qubits = n_features def construct_circuit(self, x) -> QuantumCircuit: """ Retrieves the quantum circuit encoding via Basis Encoding Args: x: the data vector to encode Returns: the quantum encoding circuit Note: All data values must be either 1s or 0s """ if isinstance(x, list): x = np.array(x) self._check_feature_vector(x) x = np.array(x) x_reversed = x[::-1] # match Qiskit qubit ordering qc = QuantumCircuit(self.num_qubits) one_indices = np.where(x_reversed == 1)[0] for i in one_indices: qc.x(i) return qc def _check_feature_vector(self, x): if np.count_nonzero(x == 0) + np.count_nonzero(x == 1) != len(x): raise ValueError("All features must be either 0 or 1 for Basis Encoding.") super()._check_feature_vector(x)
https://github.com/mspronesti/qlearnkit
mspronesti
import numbers from abc import ABC, abstractmethod from qiskit import QuantumCircuit class EncodingMap(ABC): """ Abstract Base class for qlearnkit encoding maps """ def __init__(self, n_features: int = 2) -> None: """ Creates a generic Encoding Map for classical data of size `n_features` Args: n_features: number of features (default: 2) """ if n_features <= 0: raise ValueError(f"Expected n_features > 0. Got {n_features}") elif not isinstance(n_features, numbers.Integral): raise TypeError( "n_features does not take %s value, enter integer value" % type(n_features) ) self._num_features = n_features self._num_qubits = 0 @abstractmethod def construct_circuit(self, x) -> QuantumCircuit: """construct and return quantum circuit encoding data""" raise NotImplementedError("Must have implemented this.") @property def num_qubits(self): """getter for number of qubits""" return self._num_qubits @property def num_features(self): """getter for number of features""" return self._num_features def _check_feature_vector(self, x): if len(x) != self.num_features: raise ValueError(f"Expected features dimension " f"{self.num_features}, but {len(x)} was passed")
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
from qiskit import IBMQ, QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram import numpy as np from numpy import pi import math from math import sqrt import matplotlib as mpl %matplotlib inline qc1 = QuantumCircuit(4) qc1.draw(output = 'mpl') qc2 = QuantumCircuit(QuantumRegister(4)) qc2.draw(output = 'mpl') qc3 = QuantumCircuit(4,3) qc3.draw(output = 'mpl') qc4 = QuantumCircuit(QuantumRegister(4),ClassicalRegister(3)) qc4.draw(output = 'mpl') qc5 = QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1')) qc5.draw(output = 'mpl') qr = QuantumRegister(3, 'q') anc = QuantumRegister(2, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.draw(output = 'mpl') qcA = QuantumCircuit(4,4) qcA.draw(output = 'mpl') qcB = QuantumCircuit(4) qcB.draw(output = 'mpl') qcC = QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(4, 'cr1')) qcC.draw(output = 'mpl') qcD = QuantumCircuit([4,4])
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
from qiskit import IBMQ, QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram import numpy as np from numpy import pi import math from math import sqrt import matplotlib as mpl %matplotlib inline qc = QuantumCircuit(1) qc.draw(output="mpl") # Bloch Sphere simulator_statevector = Aer.get_backend('statevector_simulator') job_statevector = execute(qc, simulator_statevector) result_statevector = job_statevector.result() outputstate = result_statevector.get_statevector(qc) plot_bloch_multivector(outputstate) qc.ry(3 * math.pi/4, 0) qc.draw(output="mpl") qc = QuantumCircuit(2) qc.ry(3 * math.pi/4, 1) qc.draw(output="mpl") # Bloch Sphere simulator_statevector = Aer.get_backend('statevector_simulator') job_statevector = execute(qc, simulator_statevector) result_statevector = job_statevector.result() outputstate = result_statevector.get_statevector(qc) plot_bloch_multivector(outputstate) qc_rotate = QuantumCircuit(1, 1) qc_rotate.ry(3 * math.pi/4, 0) qc_rotate.measure([0], [0]) qc_rotate.draw(output="mpl") # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(qc_rotate, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(qc_rotate) print("\nTotal count for 0 and 1 are:",counts) # Plot a histogram plot_histogram(counts) qc_rotate = QuantumCircuit(1, 1) qc_rotate.ry(math.pi/4, 0) qc_rotate.measure([0], [0]) qc_rotate.draw(output="mpl") # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(qc_rotate, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(qc_rotate) print("\nTotal count for 0 and 1 are:",counts) # Plot a histogram plot_histogram(counts) qc_rotate = QuantumCircuit(1, 1) qc_rotate.ry(math.pi/2, 0) qc_rotate.measure([0], [0]) qc_rotate.draw(output="mpl") # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(qc_rotate, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(qc_rotate) print("\nTotal count for 0 and 1 are:",counts) # Plot a histogram plot_histogram(counts) qc_rotate = QuantumCircuit(1, 1) qc_rotate.ry(3 * math.pi/4, 0) qc_rotate.measure([0], [0]) qc_rotate.draw(output="mpl") # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(qc_rotate, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(qc_rotate) print("\nTotal count for 0 and 1 are:",counts) # Plot a histogram plot_histogram(counts) qc_rotate = QuantumCircuit(1, 1) qc_rotate.ry(math.pi, 0) qc_rotate.measure([0], [0]) qc_rotate.draw(output="mpl") # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(qc_rotate, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(qc_rotate) print("\nTotal count for 0 and 1 are:",counts) # Plot a histogram plot_histogram(counts)
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram import numpy as np from numpy import pi import math from math import sqrt import matplotlib as mpl %matplotlib inline inp_reg = QuantumRegister(2, name='inp') ancilla = QuantumRegister(1, name='anc') qcA = QuantumCircuit(inp_reg, ancilla) qcA.h(inp_reg) qcA.x(ancilla) qcA.draw() inp_reg = QuantumRegister(2, name='inp') ancilla = QuantumRegister(1, name='anc') qcB = QuantumCircuit(inp_reg, ancilla) qcB.h(inp_reg[0:2]) qcB.x(ancilla[0]) qcB.draw() inp_reg = QuantumRegister(2, name='inp') ancilla = QuantumRegister(1, name='anc') qcC = QuantumCircuit(inp_reg, ancilla) qcC.h(inp_reg[0:1]) qcC.x(ancilla[0]) qcC.draw() inp_reg = QuantumRegister(2, name='inp') ancilla = QuantumRegister(1, name='anc') qcD = QuantumCircuit(inp_reg, ancilla) qcD.h(inp_reg[0]) qcD.h(inp_reg[1]) qcD.x(ancilla[0]) qcD.draw() inp_reg = QuantumRegister(2, name='inp') ancilla = QuantumRegister(1, name='anc') qcE = QuantumCircuit(inp_reg, ancilla) qcE.h(inp_reg[0]) qcE.h(inp_reg[1]) qcE.x(ancilla[0]) qcE.draw() inp_reg = QuantumRegister(2, name='inp') ancilla = QuantumRegister(1, name='anc') qcF = QuantumCircuit(inp_reg, ancilla) qcF.h(inp_reg) qcF.h(inp_reg) qcF.x(ancilla) qcF.draw()
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
#Import the required packages from qiskit import QuantumCircuit, Aer,execute from qiskit.visualization import * #Create a Quantum Circuit with 2 qubits and 2 classical bits qc_bell=QuantumCircuit(2,2) qc_bell.h(0) qc_bell.cx(0,1) #Measurement qc_bell.measure([0,1],[0,1]) qc_bell.draw('mpl') #Get the qasm simulator from Aer backend=Aer.get_backend('qasm_simulator') #Execute the circuit #shots= number of times the experiment/circuit is run job=execute(qc_bell,backend,shots=1024) #Get the job result: result() result=job.result() #Get the histogram data of the experiement counts=result.get_counts() print(counts) plot_histogram(counts,title="Bell State without noise") qc1_bell=QuantumCircuit(2) qc1_bell.h(0) qc1_bell.cx(0,1) qc1_bell.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc1_bell,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc2_bell=QuantumCircuit(2) qc2_bell.x(0) qc2_bell.h(0) qc2_bell.cx(0,1) qc2_bell.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc2_bell,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) qc3_bell=QuantumCircuit(2) qc3_bell.x(1) qc3_bell.h(0) qc3_bell.cx(0,1) qc3_bell.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc3_bell,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc4_bell=QuantumCircuit(2) qc4_bell.x(0) qc4_bell.x(1) qc4_bell.h(0) qc4_bell.cx(0,1) qc4_bell.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc4_bell,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) bell_1=QuantumCircuit(2) bell_1.h(0) bell_1.x(1) bell_1.cx(0,1) bell_1.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(bell_1,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") bell_2=QuantumCircuit(2) bell_2.cx(0,1) bell_2.h(0) bell_2.x(1) bell_2.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(bell_2,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") bell_3=QuantumCircuit(2) bell_3.h(0) bell_3.x(1) bell_3.cz(0,1) bell_3.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(bell_2,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") bell_4=QuantumCircuit(2) bell_4.h(0) bell_4.h(1) bell_4.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(bell_4,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc3=QuantumCircuit(3) qc3.h(0) qc3.cx(0,1) qc3.cx(0,2) qc3.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc3,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex")
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram import numpy as np from numpy import pi import math from math import sqrt import matplotlib as mpl %matplotlib inline qc = QuantumCircuit(1,1) qc.h(0) simulator = Aer.get_backend('statevector_simulator') job = execute(qc, simulator) result = job.result() outputstate = result.get_statevector(qc) plot_bloch_multivector(outputstate) qc = QuantumCircuit(1,1) # Insert code fragment here qc.ry(math.pi / 2, 0) simulator = Aer.get_backend('statevector_simulator') job = execute(qc, simulator) result = job.result() outputstate = result.get_statevector(qc) plot_bloch_multivector(outputstate) qc = QuantumCircuit(1,1) # Insert code fragment here qc.rx(math.pi / 2, 0) simulator = Aer.get_backend('statevector_simulator') job = execute(qc, simulator) result = job.result() outputstate = result.get_statevector(qc) plot_bloch_multivector(outputstate) qc = QuantumCircuit(1,1) # Insert code fragment here qc.rx(math.pi / 2, 0) qc.rz(-math.pi / 2, 0) simulator = Aer.get_backend('statevector_simulator') job = execute(qc, simulator) result = job.result() outputstate = result.get_statevector(qc) plot_bloch_multivector(outputstate) qc = QuantumCircuit(1,1) # Insert code fragment here qc.ry(math.pi, 0) simulator = Aer.get_backend('statevector_simulator') job = execute(qc, simulator) result = job.result() outputstate = result.get_statevector(qc) plot_bloch_multivector(outputstate)
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute from qiskit.quantum_info import Statevector # the state vector of the required qubits is generated from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_qsphere # plot the qubits in a qsphere import numpy as np from numpy import pi import math from math import sqrt import matplotlib as mpl %matplotlib inline import qiskit qiskit.__version__ qiskit.__qiskit_version__ qc = QuantumCircuit(3) qc.z(0) qc.s(1) qc.s(1) qc.t(2) qc.t(2) qc.t(2) qc.t(2) qc.draw() simulator = Aer.get_backend('statevector_simulator') sv = Statevector.from_label('0') plot_state_qsphere(sv.data) plot_bloch_multivector(sv) #job = execute(qc, simulator) #result = job.result() #outputstate = result.get_statevector(qc) #plot_bloch_multivector(outputstate)
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
import qiskit qiskit.__version__ qiskit.__qiskit_version__ #Import the required packages from qiskit import QuantumCircuit, QuantumRegister,ClassicalRegister,Aer,execute from qiskit.visualization import * qc1=QuantumCircuit(3) ## also comment the 2 NOT gates on qubit 0 and 1 and check the third qubit qc1.x(0) qc1.x(1) qc1.ccx(0,1,2) qc1.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc1,backend) result=job.result() sv=result.get_statevector() sv.draw(output="latex") # We create 3-qubit mct gate # We have a list of control qubits :0,1 and a target qubit 2. qc2=QuantumCircuit(3) ## also comment the 2 NOT gates on qubit 0 and 1 and check the third qubit qc2.x(0) qc2.x(1) qc2.mct([0,1],2) qc2.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc2,backend) result=job.result() sv=result.get_statevector() sv.draw(output="latex") # We simply create a user-defined object cx from CXGate class # Another way of accessing a CX or NOT gate from qiskit.circuit.library import CXGate qc3=QuantumCircuit(3) cx=CXGate() qc3.append(cx,[0,1]) qc3.draw('mpl') from qiskit.circuit.library import CXGate qc4=QuantumCircuit(3) ccx=CXGate().control() qc4.append(ccx,[0,1,2]) qc4.draw('mpl') from math import pi qc5=QuantumCircuit(2) qc5.cry(pi/2,0,1) qc5.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc5,backend) result=job.result() sv=result.get_statevector() sv.draw(output="latex") #Let's apply a X on the control qubit qc6=QuantumCircuit(2) qc6.x(0) qc6.cry(pi/2,0,1) qc6.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc6,backend) result=job.result() sv=result.get_statevector() print("statevector:", sv) sv.draw(output="latex")
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
import qiskit qiskit.__version__ qiskit.__qiskit_version__ #Import the required packages from qiskit import QuantumCircuit, QuantumRegister,ClassicalRegister,Aer,execute from qiskit.visualization import * from math import sqrt v=[1/sqrt(2),0,0,1/sqrt(2)] v qc_bell=QuantumCircuit(2) v=[1/sqrt(2),0,0,1/sqrt(2)] qc_bell.initialize(v,[0,1]) qc_bell.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_bell,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") #Create a Quantum Circuit with 2 qubits qc_bell=QuantumCircuit(2) qc_bell.h(0) qc_bell.cx(0,1) qc_bell.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_bell,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") qc_2=QuantumCircuit(2) v1, v2=[0,1],[1,0] qc_2.initialize(v1,0) qc_2.initialize(v2,1) qc_2.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_2,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") #Create a Quantum Circuit with 2 qubits qc_3=QuantumCircuit(2) qc_3.x(0) qc_3.draw('mpl',initial_state=True) backend=Aer.get_backend('statevector_simulator') job=execute(qc_3,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") #Create a Quantum Circuit with 2 qubits qc_4=QuantumCircuit(2) qc_4.cx(0,1) qc_4.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_4,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex") #Create a Quantum Circuit with 2 qubits qc_5=QuantumCircuit(2) qc_5.h(0) qc_5.h(1) qc_5.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc_5,backend) result=job.result() sv=result.get_statevector() print("Statvector :",sv) sv.draw(output="latex")
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
import qiskit qiskit.__version__ qiskit.__qiskit_version__ #Import the required packages from qiskit import QuantumCircuit, QuantumRegister,ClassicalRegister,Aer,execute from qiskit.visualization import * qc1=QuantumCircuit(2) qc1.x(0) qc1.cx(0,1) qc1.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc1,backend) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc2=QuantumCircuit(2) qc2.x(0) qc2.cnot(0,1) qc2.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc2,backend) result=job.result() sv=result.get_statevector() sv.draw(output="latex") # We create 5-qubit mct gate # We have a list of control qubits :0,1,2,3 and a target qubit 4. qc3=QuantumCircuit(5) qc3.x(range(4)) qc3.mct([0,1,2,3],4) qc3.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc3,backend) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc4=QuantumCircuit(2) qc4.cz(0,1) qc4.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc4,backend) result=job.result() sv=result.get_statevector() print("statevector:", sv) sv.draw(output="latex") backend=Aer.get_backend('unitary_simulator') job=execute(qc4,backend) result=job.result() sv=result.get_unitary() print(sv) #Let's apply a X on the control qubit qc4=QuantumCircuit(2) qc4.x(0) qc4.cz(0,1) qc4.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc4,backend) result=job.result() sv=result.get_statevector() print("statevector:", sv) sv.draw(output="latex") backend=Aer.get_backend('unitary_simulator') job=execute(qc4,backend) result=job.result() sv=result.get_unitary() print(sv) plot_state_qsphere(sv,show_state_phases=True)
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
from qiskit import QuantumCircuit # imports only QuantumCircuit function from qiskit # from qiskit import * --> import all the fuction defined under qiskit library including QuantumCircuit # Creating an empty quantum circuit object with 3 qubits and 3 classical bits qc = QuantumCircuit(3,3) qc.draw() # For better visualization use matplotlib as 'mpl' qc.draw(output = "mpl") qc_trial = QuantumCircuit(3,3) qc_trial.draw(output = "mpl") qc_trial.measure_all() qc_trial.draw(output = "mpl") qc_trial2 = QuantumCircuit(3) qc_trial2.draw(output = "mpl") qc_trial2.measure_all() qc_trial2.draw(output = "mpl") qc_trial3 = QuantumCircuit(3,3) # if you get bored typing QuantumCircuit all the time try this: from qiskit import QuantumCircuit as qc qc_trial3.draw(output = "mpl") qc_trial3.measure(0,0) # measure(qubit,clbit) qc_trial3.draw(output = "mpl") # alternative to give a command to measure multiple qubits at the same time qc_trial3 = QuantumCircuit(3,3) qc_trial3.measure([0,2],[0,2])# measure([qubits],[clbits]), order matters,here qubit0-->clbit0,qubit2 --> clbit2 qc_trial3.draw( output = "mpl") #To demonstrate significance of order qc_trial3 = QuantumCircuit(3,3) qc_trial3.measure([0,1],[0,2])# measure([qubits],[clbits]), order here qubit0-->clbit0,qubit1 --> clbit2 qc_trial3.draw( output = "mpl") # To measure all the qubits qc_trial3 = QuantumCircuit(3,3) qc_trial3.measure([0,1,2],[0,1,2])# measure([qubits],[clbits]), order here qubit0-->clbit0,qubit1 --> clbit1,qubit2 --> clbit2 qc_trial3.draw( output = "mpl") #measure() requires pre-written classical register qc_trial4 = QuantumCircuit(3) qc_trial4.measure([0,1,2],[0,1,2]) qc_trial4.draw(output = "mpl") qc_trial5 = QuantumCircuit(3,3) qc_trial5.measure(0,1,2) qc_trial5.draw(output = "mpl") # We can also use"range" function qc_trial5 = QuantumCircuit(3,3) qc_trial5.measure(range(3),range(3)) qc_trial5.draw(output = "mpl") qc.draw(output = "mpl") qc.measure([0,1,2], [0,1,2]) qc.draw(output = "mpl") qc_op2 = QuantumCircuit(3,3) qc_op2.measure([0,0], [1,1], [2,2]) qc_op2.measure([0,0], [1,1]) qc_op2.draw(output = "mpl") # It just implemented 2 measurements on the same qubit as the instruction read [(qubit0,qubit0),(clbit1,clbit1)] # so qubit0 --> clbit0, and again qubit0--> clbit1 qc_op3 = QuantumCircuit(3,3) qc_op3.measure_all() qc_op3.draw(output = "mpl") # Two classical registers('c' and 'meas') qc_op4 = QuantumCircuit(3,3) qc_op4.measure(0,1,2) qc_op4.draw(output = "mpl")
https://github.com/CynthiaRios/quantum_orchestra
CynthiaRios
!(./jupyter_images/header.png "Header") #Will redo on quentin's computer tomorrow (today) pip install ipywidgets #conda install -c conda-forge ipywidgets from IPython.display import clear_output pip install music21 pip install pydub pip install RISE from shutil import copyfile from qiskit.visualization import plot_histogram from qiskit import Aer, QuantumCircuit, execute from qiskit import IBMQ import qiskit.tools.jupyter import os %qiskit_job_watcher from IPython.display import Audio import wave import numpy as np ## Button Display Imports (Needs installations mentioned above) from IPython.display import display, Markdown, clear_output # widget packages import ipywidgets as widgets from pydub import AudioSegment from music21 import * ![alt text](./jupyter_images/quantumgates.png "Quantum Gates") #Will redo on quentin's computer tomorrow (today) piano_input = [None] * 5 piano = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([piano, piano2, piano3, piano4, piano5]) box guitar_input = [None] * 5 guitar = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([guitar, guitar2, guitar3, guitar4, guitar5]) box trumpet_input = [None] * 5 trumpet = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([trumpet, trumpet2, trumpet3, trumpet4, trumpet5]) box bass_input = [None] * 5 bass = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([bass, bass2, bass3, bass4, bass5]) box def GetGates(piano_input, guitar_input, bass_input, trumpet_input): if (piano.value == 'No Gate'): piano_input[0] = 'n' if (piano.value == 'X-Gate'): piano_input[0] = 'x' if (piano.value == 'Y-Gate'): piano_input[0] = 'y' if (piano.value == 'Z-Gate'): piano_input[0] = 'z' if (piano2.value == 'No Gate'): piano_input[1] = 'n' if (piano2.value == 'X-Gate'): piano_input[1] = 'x' if (piano2.value == 'Y-Gate'): piano_input[1] = 'y' if (piano2.value == 'Z-Gate'): piano_input[1] = 'z' if (piano3.value == 'No Gate'): piano_input[2] = 'n' if (piano3.value == 'X-Gate'): piano_input[2] = 'x' if (piano3.value == 'Y-Gate'): piano_input[2] = 'y' if (piano3.value == 'Z-Gate'): piano_input[2] = 'z' if (piano4.value == 'No Gate'): piano_input[3] = 'n' if (piano4.value == 'X-Gate'): piano_input[3] = 'x' if (piano4.value == 'Y-Gate'): piano_input[3] = 'y' if (piano4.value == 'Z-Gate'): piano_input[3] = 'z' if (piano5.value == 'No Gate'): piano_input[4] = 'n' if (piano5.value == 'X-Gate'): piano_input[4] = 'x' if (piano5.value == 'Y-Gate'): piano_input[4] = 'y' if (piano5.value == 'Z-Gate'): piano_input[4] = 'z' if (guitar.value == 'No Gate'): guitar_input[0] = 'n' if (guitar.value == 'X-Gate'): guitar_input[0] = 'x' if (guitar.value == 'Y-Gate'): guitar_input[0] = 'y' if (guitar.value == 'Z-Gate'): guitar_input[0] = 'z' if (guitar2.value == 'No Gate'): guitar_input[1] = 'n' if (guitar2.value == 'X-Gate'): guitar_input[1] = 'x' if (guitar2.value == 'Y-Gate'): guitar_input[1] = 'y' if (guitar2.value == 'Z-Gate'): guitar_input[1] = 'z' if (guitar3.value == 'No Gate'): guitar_input[2] = 'n' if (guitar3.value == 'X-Gate'): guitar_input[2] = 'x' if (guitar3.value == 'Y-Gate'): guitar_input[2] = 'y' if (guitar3.value == 'Z-Gate'): guitar_input[2] = 'z' if (guitar4.value == 'No Gate'): guitar_input[3] = 'n' if (guitar4.value == 'X-Gate'): guitar_input[3] = 'x' if (guitar4.value == 'Y-Gate'): guitar_input[3] = 'y' if (guitar4.value == 'Z-Gate'): guitar_input[3] = 'z' if (guitar5.value == 'No Gate'): guitar_input[4] = 'n' if (guitar5.value == 'X-Gate'): guitar_input[4] = 'x' if (guitar5.value == 'Y-Gate'): guitar_input[4] = 'y' if (guitar5.value == 'Z-Gate'): guitar_input[4] = 'z' if (bass.value == 'No Gate'): bass_input[0] = 'n' if (bass.value == 'X-Gate'): bass_input[0] = 'x' if (bass.value == 'Y-Gate'): bass_input[0] = 'y' if (bass.value == 'Z-Gate'): bass_input[0] = 'z' if (bass2.value == 'No Gate'): bass_input[1] = 'n' if (bass2.value == 'X-Gate'): bass_input[1] = 'x' if (bass2.value == 'Y-Gate'): bass_input[1] = 'y' if (bass2.value == 'Z-Gate'): bass_input[1] = 'z' if (bass3.value == 'No Gate'): bass_input[2] = 'n' if (bass3.value == 'X-Gate'): bass_input[2] = 'x' if (bass3.value == 'Y-Gate'): bass_input[2] = 'y' if (bass3.value == 'Z-Gate'): bass_input[2] = 'z' if (bass4.value == 'No Gate'): bass_input[3] = 'n' if (bass4.value == 'X-Gate'): bass_input[3] = 'x' if (bass4.value == 'Y-Gate'): bass_input[3] = 'y' if (bass4.value == 'Z-Gate'): bass_input[3] = 'z' if (bass5.value == 'No Gate'): bass_input[4] = 'n' if (bass5.value == 'X-Gate'): bass_input[4] = 'x' if (bass5.value == 'Y-Gate'): bass_input[4] = 'y' if (bass5.value == 'Z-Gate'): bass_input[4] = 'z' if (trumpet.value == 'No Gate'): trumpet_input[0] = 'n' if (trumpet.value == 'X-Gate'): trumpet_input[0] = 'x' if (trumpet.value == 'Y-Gate'): trumpet_input[0] = 'y' if (trumpet.value == 'Z-Gate'): trumpet_input[0] = 'z' if (trumpet2.value == 'No Gate'): trumpet_input[1] = 'n' if (trumpet2.value == 'X-Gate'): trumpet_input[1] = 'x' if (trumpet2.value == 'Y-Gate'): trumpet_input[1] = 'y' if (trumpet2.value == 'Z-Gate'): trumpet_input[1] = 'z' if (trumpet3.value == 'No Gate'): trumpet_input[2] = 'n' if (trumpet3.value == 'X-Gate'): trumpet_input[2] = 'x' if (trumpet3.value == 'Y-Gate'): trumpet_input[2] = 'y' if (trumpet3.value == 'Z-Gate'): trumpet_input[2] = 'z' if (trumpet4.value == 'No Gate'): trumpet_input[3] = 'n' if (trumpet4.value == 'X-Gate'): trumpet_input[3] = 'x' if (trumpet4.value == 'Y-Gate'): trumpet_input[3] = 'y' if (trumpet4.value == 'Z-Gate'): trumpet_input[3] = 'z' if (trumpet5.value == 'No Gate'): trumpet_input[4] = 'n' if (trumpet5.value == 'X-Gate'): trumpet_input[4] = 'x' if (trumpet5.value == 'Y-Gate'): trumpet_input[4] = 'y' if (trumpet5.value == 'Z-Gate'): trumpet_input[4] = 'z' return (piano_input, guitar_input, bass_input, trumpet_input) piano_input, guitar_input, bass_input, trumpet_input = GetGates(piano_input, guitar_input, bass_input, trumpet_input) from qiskit.test.mock import FakeVigo fake_vigo = FakeVigo() #minimum user input will just be for them to fill out the create quantum circuit function inthe backend n = 5 #number of gates s = 1024 piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] def CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input): cct1 = QuantumCircuit(1,1) cct2 = QuantumCircuit(1,1) cct3 = QuantumCircuit(1,1) cct4 = QuantumCircuit(1,1) piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] for i in range(n): cct1.h(0) cct1.barrier() if piano_input[i-1] == 'x': cct1.x(0) if piano_input[i-1] == 'y': cct1.y(0) if piano_input[i-1] == 'z': cct1.z(0) cct1.barrier() cct1.measure(0,0) #plot_histogram(c1) cct2.h(0) cct2.barrier() if guitar_input[i-1] == 'x': cct2.x(0) if guitar_input[i-1] == 'y': cct2.y(0) if guitar_input[i-1] == 'z': cct2.z(0) cct2.barrier() cct2.measure(0,0) #plot_histogram(c2) cct3.h(0) cct3.barrier() if bass_input[i-1] == 'x': cct3.x(0) if bass_input[i-1] == 'y': cct3.y(0) if bass_input[i-1] == 'z': cct3.z(0) cct3.barrier() cct3.measure(0,0) #plot_histogram(c3) cct4.h(0) cct4.barrier() if trumpet_input[i-1] == 'x': cct4.x(0) if trumpet_input[i-1] == 'y': cct4.y(0) if trumpet_input[i-1] == 'z': cct4.z(0) cct4.barrier() cct4.measure(0,0) c1 = execute(cct1, fake_vigo, shots=s).result().get_counts() piano_states.append(c1) c2 = execute(cct2, fake_vigo, shots=s).result().get_counts() guitar_states.append(c2) c3 = execute(cct3, fake_vigo, shots=s).result().get_counts() bass_states.append(c3) c4 = execute(cct4, fake_vigo, shots=s).result().get_counts() trumpet_states.append(c4) return c1,c2,c3,c4,piano_states, guitar_states, bass_states, trumpet_states, cct1, cct2, cct3, cct4 c1,c2,c3,c4,piano_states, guitar_states, bass_states, trumpet_states, cct1, cct2,cct3,cct4 = CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input) print(trumpet_states) def ins(states,s): res = [] for key in states[0].keys(): res.append(states[0][key]/s) return res s = 1024 piano_prob = ins(piano_states,s) guitar_prob = ins(guitar_states,s) bass_prob = ins(bass_states,s) trumpet_prob = ins(trumpet_states,s) print(trumpet_prob) def MusicalTransformation(probs): tune_array=[] for i in range(n+1): if((probs[0] > 0.4 and probs[0] < 0.5) and (probs[1] > 0.4 and probs[1] < 0.45)): tune_array.append('c') tune_array.append('g') tune_array.append('e') if((probs[0] > 0.4 and probs[0] < 0.5) and (probs[1] > 0.45 and probs[1] < 0.5)): tune_array.append('c') tune_array.append('f') tune_array.append('g') if((probs[0] > 0.4 and probs[0] < 0.5) and (probs[1] > 0.5 and probs[1] < 0.55)): tune_array.append('d') tune_array.append('f') tune_array.append('a') if((probs[0] > 0.4 and probs[0] < 0.5) and (probs[1] > 0.55 and probs[1] < 0.6)): tune_array.append('f') tune_array.append('a') tune_array.append('c') if((probs[0] > 0.5 and probs[0] < 0.6) and (probs[1] > 0.4 and probs[1] < 0.45)): tune_array.append('g') tune_array.append('b') tune_array.append('d') if((probs[0] > 0.5 and probs[0] < 0.6) and (probs[1] > 0.45 and probs[1] < 0.5)): tune_array.append('d') tune_array.append('f') tune_array.append('a') if((probs[0] > 0.5 and probs[0] < 0.6) and (probs[1] > 0.5 and probs[1] < 0.55)): tune_array.append('e') tune_array.append('g') tune_array.append('b') if((probs[0] > 0.5 and probs[0] < 0.6) and (probs[1] > 0.55 and probs[1] < 0.6)): tune_array.append('a') tune_array.append('c') tune_array.append('b') if(probs[0] < 0.4 or probs[0] > 0.6 or probs[1] < 0.4 or probs[1] > 0.6): tune_array.append('n') tune_array.append('n') tune_array.append('n') return tune_array tune_array_piano = MusicalTransformation(piano_prob) tune_array_guitar = MusicalTransformation(guitar_prob) tune_array_bass = MusicalTransformation(bass_prob) tune_array_trumpet = MusicalTransformation(trumpet_prob) def PlayPianoTune(character, songs): if character == 'a': sound_file = "./Audio/Piano/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Piano/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Piano/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Piano/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Piano/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Piano/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Piano/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayGuitarTune(character, songs): if character == 'a': sound_file = "./Audio/Guitar/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Guitar/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Guitar/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Guitar/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Guitar/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Guitar/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Guitar/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayBassTune(character, songs): if character == 'a': sound_file = "./Audio/Bass/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Bass/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Bass/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Bass/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Bass/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Bass/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Bass/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayTrumpetTune(character, songs): if character == 'a': sound_file = "./Audio/Trumpet/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Trumpet/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Trumpet/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Trumpet/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Trumpet/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Trumpet/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Trumpet/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs piano_song = [] for i in range(len(tune_array_piano)): character = tune_array_piano[i-1] piano_song = PlayPianoTune(character, piano_song) os.remove("./pianosounds.wav") copyfile('./Audio/blank.wav','./pianosounds.wav') for i in range(len(tune_array_piano)): infiles = [piano_song[i-1], "pianosounds.wav"] outfile = "pianosounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() guitar_song = [] for i in range(len(tune_array_guitar)): character = tune_array_piano[i-1] guitar_song = PlayGuitarTune(character, guitar_song) os.remove("./guitarsounds.wav") copyfile('./Audio/blank.wav','./guitarsounds.wav') for i in range(len(tune_array_guitar)): infiles = [guitar_song[i-1], "guitarsounds.wav"] outfile = "guitarsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() bass_song = [] for i in range(len(tune_array_bass)): character = tune_array_bass[i-1] bass_song = PlayBassTune(character, bass_song) os.remove("./basssounds.wav") copyfile('./Audio/blank.wav','./basssounds.wav') for i in range(len(tune_array_bass)): infiles = [bass_song[i-1], "basssounds.wav"] outfile = "basssounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() trumpet_song = [] for i in range(len(tune_array_trumpet)): character = tune_array_trumpet[i-1] trumpet_song = PlayTrumpetTune(character, trumpet_song) os.remove("./trumpetsounds.wav") copyfile('./Audio/blank.wav','./trumpetsounds.wav') for i in range(len(tune_array_trumpet)): infiles = [trumpet_song[i-1], "trumpetsounds.wav"] outfile = "trumpetsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() sound1 = AudioSegment.from_file("./trumpetsounds.wav") sound2 = AudioSegment.from_file("./basssounds.wav") combined = sound1.overlay(sound2) combined.export("./combined.wav", format='wav') sound3 = AudioSegment.from_file("./guitarsounds.wav") sound4 = AudioSegment.from_file("./pianosounds.wav") combined2 = sound3.overlay(sound4) combined2.export("./combined2.wav", format='wav') sound5 = AudioSegment.from_file("./combined.wav") sound6 = AudioSegment.from_file("./combined2.wav") output_song = sound5.overlay(sound6) output_song.export("./output_song.wav", format='wav') sound_file = "./output_song.wav" Audio(sound_file, autoplay=True) print(tune_array_piano) a = 64 b = 65 c = 66 d = 67 e = 68 f = 69 g = 70 print(tune_array_piano[0]) streamPiano = stream.Stream() instrumentPiano = [] for i in range(18): instrumentPiano.append(note.Note(tune_array_piano[i])) streamPiano.append(instrumentPiano) streamPiano.show() a = 57 b = 58 c = 59 d = 60 e = 61 f = 62 g = 63 print(tune_array_guitar) streamGuitar = stream.Stream() instrumentGuitar = [] for i in range(18): instrumentGuitar.append(note.Note(tune_array_guitar[i])) streamGuitar.append(instrumentGuitar) streamGuitar.show() a = 50 b = 51 c = 52 d = 53 e = 54 f = 55 g = 56 print(tune_array_trumpet) streamTrumpet = stream.Stream() streamBass = stream.Stream() instrumentTrumpet = [] for i in range(18): instrumentTrumpet.append(note.Note(tune_array_trumpet[i])) streamTrumpet.append(instrumentTrumpet) streamTrumpet.show() a = 43 b = 44 c = 45 d = 46 e = 47 f = 48 g = 49 print(tune_array_bass) streamBass = stream.Stream() instrumentBass = [] for i in range(18): instrumentBass.append(note.Note(tune_array_bass[i])) streamBass.append(instrumentBass) streamBass.show() excerpt = streamPiano.measures(1, 4) excerpt.show() streamPiano.getElementsByClass('Measure').insert(0.0, instrument.Piano()) streamGuitar.getElementsByClass('Measure').insert(1.0, instrument.Guitar()) streamTrumpet.getElementsByClass('Measure').insert(2.0, instrument.Trumpet()) streamBass.getElementsByClass('Measure').insert(3.0, instrument.Bass()) s = stream.Score() s.insert(0, streamPiano) s.insert(0, streamGuitar) s.insert(0, streamTrumpet) s.insert(0, streamBass) s.show() s.show('musicxml') #this show on musescore
https://github.com/CynthiaRios/quantum_orchestra
CynthiaRios
![header](./jupyter_images/header.png "Header") ## General Imports from qiskit import QuantumCircuit, execute from qiskit import Aer from shutil import copyfile from qiskit.visualization import plot_histogram from qiskit import IBMQ import qiskit.tools.jupyter import os %qiskit_job_watcher from IPython.display import Audio import wave import numpy as np ## Button Display Imports (Needs installations mentioned above) from IPython.display import display, Markdown, clear_output # widget packages import ipywidgets as widgets from pydub import AudioSegment ![QuantumGates](./jupyter_images/quantumgates.png "Quantum Gates") #Will redo on quentin's computer tomorrow (today) piano_input = [None] * 5 piano = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([piano, piano2, piano3, piano4, piano5]) box guitar_input = [None] * 5 guitar = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([guitar, guitar2, guitar3, guitar4, guitar5]) box bass_input = [None] * 5 bass = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([bass, bass2, bass3, bass4, bass5]) box trumpet_input = [None] * 5 trumpet = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([trumpet, trumpet2, trumpet3, trumpet4, trumpet5]) box def GetGates(piano_input, guitar_input, bass_input, trumpet_input): if (piano.value == 'No Gate'): piano_input[0] = 'n' if (piano.value == 'X-Gate'): piano_input[0] = 'x' if (piano.value == 'Y-Gate'): piano_input[0] = 'y' if (piano.value == 'Z-Gate'): piano_input[0] = 'z' if (piano2.value == 'No Gate'): piano_input[1] = 'n' if (piano2.value == 'X-Gate'): piano_input[1] = 'x' if (piano2.value == 'Y-Gate'): piano_input[1] = 'y' if (piano2.value == 'Z-Gate'): piano_input[1] = 'z' if (piano3.value == 'No Gate'): piano_input[2] = 'n' if (piano3.value == 'X-Gate'): piano_input[2] = 'x' if (piano3.value == 'Y-Gate'): piano_input[2] = 'y' if (piano3.value == 'Z-Gate'): piano_input[2] = 'z' if (piano4.value == 'No Gate'): piano_input[3] = 'n' if (piano4.value == 'X-Gate'): piano_input[3] = 'x' if (piano4.value == 'Y-Gate'): piano_input[3] = 'y' if (piano4.value == 'Z-Gate'): piano_input[3] = 'z' if (piano5.value == 'No Gate'): piano_input[4] = 'n' if (piano5.value == 'X-Gate'): piano_input[4] = 'x' if (piano5.value == 'Y-Gate'): piano_input[4] = 'y' if (piano5.value == 'Z-Gate'): piano_input[4] = 'z' if (guitar.value == 'No Gate'): guitar_input[0] = 'n' if (guitar.value == 'X-Gate'): guitar_input[0] = 'x' if (guitar.value == 'Y-Gate'): guitar_input[0] = 'y' if (guitar.value == 'Z-Gate'): guitar_input[0] = 'z' if (guitar2.value == 'No Gate'): guitar_input[1] = 'n' if (guitar2.value == 'X-Gate'): guitar_input[1] = 'x' if (guitar2.value == 'Y-Gate'): guitar_input[1] = 'y' if (guitar2.value == 'Z-Gate'): guitar_input[1] = 'z' if (guitar3.value == 'No Gate'): guitar_input[2] = 'n' if (guitar3.value == 'X-Gate'): guitar_input[2] = 'x' if (guitar3.value == 'Y-Gate'): guitar_input[2] = 'y' if (guitar3.value == 'Z-Gate'): guitar_input[2] = 'z' if (guitar4.value == 'No Gate'): guitar_input[3] = 'n' if (guitar4.value == 'X-Gate'): guitar_input[3] = 'x' if (guitar4.value == 'Y-Gate'): guitar_input[3] = 'y' if (guitar4.value == 'Z-Gate'): guitar_input[3] = 'z' if (guitar5.value == 'No Gate'): guitar_input[4] = 'n' if (guitar5.value == 'X-Gate'): guitar_input[4] = 'x' if (guitar5.value == 'Y-Gate'): guitar_input[4] = 'y' if (guitar5.value == 'Z-Gate'): guitar_input[4] = 'z' if (bass.value == 'No Gate'): bass_input[0] = 'n' if (bass.value == 'X-Gate'): bass_input[0] = 'x' if (bass.value == 'Y-Gate'): bass_input[0] = 'y' if (bass.value == 'Z-Gate'): bass_input[0] = 'z' if (bass2.value == 'No Gate'): bass_input[1] = 'n' if (bass2.value == 'X-Gate'): bass_input[1] = 'x' if (bass2.value == 'Y-Gate'): bass_input[1] = 'y' if (bass2.value == 'Z-Gate'): bass_input[1] = 'z' if (bass3.value == 'No Gate'): bass_input[2] = 'n' if (bass3.value == 'X-Gate'): bass_input[2] = 'x' if (bass3.value == 'Y-Gate'): bass_input[2] = 'y' if (bass3.value == 'Z-Gate'): bass_input[2] = 'z' if (bass4.value == 'No Gate'): bass_input[3] = 'n' if (bass4.value == 'X-Gate'): bass_input[3] = 'x' if (bass4.value == 'Y-Gate'): bass_input[3] = 'y' if (bass4.value == 'Z-Gate'): bass_input[3] = 'z' if (bass5.value == 'No Gate'): bass_input[4] = 'n' if (bass5.value == 'X-Gate'): bass_input[4] = 'x' if (bass5.value == 'Y-Gate'): bass_input[4] = 'y' if (bass5.value == 'Z-Gate'): bass_input[4] = 'z' if (trumpet.value == 'No Gate'): trumpet_input[0] = 'n' if (trumpet.value == 'X-Gate'): trumpet_input[0] = 'x' if (trumpet.value == 'Y-Gate'): trumpet_input[0] = 'y' if (trumpet.value == 'Z-Gate'): trumpet_input[0] = 'z' if (trumpet2.value == 'No Gate'): trumpet_input[1] = 'n' if (trumpet2.value == 'X-Gate'): trumpet_input[1] = 'x' if (trumpet2.value == 'Y-Gate'): trumpet_input[1] = 'y' if (trumpet2.value == 'Z-Gate'): trumpet_input[1] = 'z' if (trumpet3.value == 'No Gate'): trumpet_input[2] = 'n' if (trumpet3.value == 'X-Gate'): trumpet_input[2] = 'x' if (trumpet3.value == 'Y-Gate'): trumpet_input[2] = 'y' if (trumpet3.value == 'Z-Gate'): trumpet_input[2] = 'z' if (trumpet4.value == 'No Gate'): trumpet_input[3] = 'n' if (trumpet4.value == 'X-Gate'): trumpet_input[3] = 'x' if (trumpet4.value == 'Y-Gate'): trumpet_input[3] = 'y' if (trumpet4.value == 'Z-Gate'): trumpet_input[3] = 'z' if (trumpet5.value == 'No Gate'): trumpet_input[4] = 'n' if (trumpet5.value == 'X-Gate'): trumpet_input[4] = 'x' if (trumpet5.value == 'Y-Gate'): trumpet_input[4] = 'y' if (trumpet5.value == 'Z-Gate'): trumpet_input[4] = 'z' return (piano_input, guitar_input, bass_input, trumpet_input) piano_input, guitar_input, bass_input, trumpet_input = GetGates(piano_input, guitar_input, bass_input, trumpet_input) #minimum user input will just be for them to fill out the create quantum circuit function inthe backend n = 5 #number of gates backend = Aer.get_backend('statevector_simulator') piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] def CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input): cct = QuantumCircuit(4,1) piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] for i in range(n-1): cct.h(i-1) cct.barrier() for i in range(n): if piano_input[i-1] == 'x': cct.x(0) if piano_input[i-1] == 'y': cct.y(0) if piano_input[i-1] == 'z': cct.z(0) piano_states.append(execute(cct, backend).result().get_statevector()) if guitar_input[i-1] == 'x': cct.x(1) if guitar_input[i-1] == 'y': cct.y(1) if guitar_input[i-1] == 'z': cct.z(1) guitar_states.append(execute(cct, backend).result().get_statevector()) if bass_input[i-1] == 'x': cct.x(2) if bass_input[i-1] == 'y': cct.y(2) if bass_input[i-1] == 'z': cct.z(2) bass_states.append(execute(cct, backend).result().get_statevector()) if trumpet_input[i-1] == 'x': cct.x(3) if trumpet_input[i-1] == 'y': cct.y(3) if trumpet_input[i-1] == 'z': cct.z(3) trumpet_states.append(execute(cct, backend).result().get_statevector()) cct.barrier() cct.draw('mpl') return piano_states, guitar_states, bass_states, trumpet_states, cct piano_states, guitar_states, bass_states, trumpet_states, cct = CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input) cct.draw(output="mpl") def SeperateArrays(states, vals_real, vals_imaginary): vals = [] for i in range(n+1): vals.append(states[i-1][0]) for i in range(n+1): vals_real.append((states[i-1][0].real)) vals_imaginary.append((states[i-1][0]).imag) return vals_real, vals_imaginary piano_real = [] piano_imaginary = [] piano_vals = [] guitar_real = [] guitar_imaginary = [] guitar_vals = [] bass_real = [] bass_imaginary = [] bass_vals = [] trumpet_real = [] trumpet_imaginary = [] trumpet_vals = [] piano_real, piano_imaginary = SeperateArrays(piano_states, piano_real, piano_imaginary) guitar_real, guitar_imaginary = SeperateArrays(guitar_states, guitar_real, guitar_imaginary) bass_real, bass_imaginary = SeperateArrays(bass_states, bass_real, bass_imaginary) trumpet_real, trumpet_imaginary = SeperateArrays(trumpet_states, trumpet_real, trumpet_imaginary) def MusicalTransformation(real, imaginary): tune_array=[] for i in range(n+1): if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('c') tune_array.append('g') tune_array.append('e') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('c') tune_array.append('f') tune_array.append('g') if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('f') tune_array.append('a') tune_array.append('c') if(real[i-1] > 0 and imaginary[i-1] > 0): tune_array.append('g') tune_array.append('b') tune_array.append('d') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] > 0 and imaginary[i-1] >= 0): tune_array.append('e') tune_array.append('g') tune_array.append('b') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('a') tune_array.append('c') tune_array.append('b') if(real[i-1] == 0 and imaginary[i-1] == 0): tune_array.append('n') tune_array.append('n') tune_array.append('n') return tune_array tune_array_piano = MusicalTransformation(piano_real, piano_imaginary) tune_array_guitar = MusicalTransformation(guitar_real, guitar_imaginary) tune_array_bass = MusicalTransformation(bass_real, bass_imaginary) tune_array_trumpet = MusicalTransformation(trumpet_real, trumpet_imaginary) def PlayPianoTune(character, songs): if character == 'a': sound_file = "./Audio/Piano/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Piano/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Piano/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Piano/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Piano/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Piano/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Piano/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayGuitarTune(character, songs): if character == 'a': sound_file = "./Audio/Guitar/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Guitar/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Guitar/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Guitar/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Guitar/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Guitar/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Guitar/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayBassTune(character, songs): if character == 'a': sound_file = "./Audio/Bass/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Bass/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Bass/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Bass/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Bass/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Bass/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Bass/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayTrumpetTune(character, songs): if character == 'a': sound_file = "./Audio/Trumpet/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Trumpet/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Trumpet/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Trumpet/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Trumpet/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Trumpet/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Trumpet/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs piano_song = [] for i in range(len(tune_array_piano)): character = tune_array_piano[i-1] piano_song = PlayPianoTune(character, piano_song) os.remove("./pianosounds.wav") copyfile('./Audio/blank.wav','./pianosounds.wav') for i in range(len(tune_array_piano)): infiles = [piano_song[i-1], "pianosounds.wav"] outfile = "pianosounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() guitar_song = [] for i in range(len(tune_array_guitar)): character = tune_array_piano[i-1] guitar_song = PlayGuitarTune(character, guitar_song) os.remove("./guitarsounds.wav") copyfile('./Audio/blank.wav','./guitarsounds.wav') for i in range(len(tune_array_guitar)): infiles = [guitar_song[i-1], "guitarsounds.wav"] outfile = "guitarsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() bass_song = [] for i in range(len(tune_array_bass)): character = tune_array_bass[i-1] bass_song = PlayBassTune(character, bass_song) os.remove("./basssounds.wav") copyfile('./Audio/blank.wav','./basssounds.wav') for i in range(len(tune_array_bass)): infiles = [bass_song[i-1], "basssounds.wav"] outfile = "basssounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() trumpet_song = [] for i in range(len(tune_array_trumpet)): character = tune_array_trumpet[i-1] trumpet_song = PlayTrumpetTune(character, trumpet_song) os.remove("./trumpetsounds.wav") copyfile('./Audio/blank.wav','./trumpetsounds.wav') for i in range(len(tune_array_trumpet)): infiles = [trumpet_song[i-1], "trumpetsounds.wav"] outfile = "trumpetsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() os.remove("./combined.wav") copyfile('./Audio/blank.wav','./combined.wav') os.remove("./combined2.wav") copyfile('./Audio/blank.wav','./combined2.wav') copyfile('./Audio/blank.wav','./output_song.wav') sound1 = AudioSegment.from_file("./trumpetsounds.wav") sound2 = AudioSegment.from_file("./basssounds.wav") combined = sound1.overlay(sound2) combined.export("./combined.wav", format='wav') sound3 = AudioSegment.from_file("./guitarsounds.wav") sound4 = AudioSegment.from_file("./pianosounds.wav") combined2 = sound3.overlay(sound4) combined2.export("./combined2.wav", format='wav') sound5 = AudioSegment.from_file("./combined.wav") sound6 = AudioSegment.from_file("./combined2.wav") output_song = sound5.overlay(sound6) output_song.export("./outputsong.wav", format='wav') sound_file = "./outputsong.wav" Audio(sound_file, autoplay=True) #https://musescore.org/en/download/musescore.msi !pip install music21 !pip install RISE from music21 import * #for Windows OS error #us = environment.UserSettings() #C:\Program Files\MuseScore 3\bin\MuseScore3.exe #us['musicxmlPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe" #us['musescoreDirectPNGPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe" piano_stream = stream.Stream() guitar_stream = stream.Stream() bass_stream = stream.Stream() trumpet_stream = stream.Stream() note1 = note.Note("A") note2 = note.Note("B") note3 = note.Note("C") note4 = note.Note("D") note5 = note.Note("E") note6 = note.Note("F") note7 = note.Note("G") note8 = note.Rest() def append_stream(array, stream): for i in range(n+1): if array[i-1] == 'a': stream.append(note1) if array[i-1] == 'b': stream.append(note2) if array[i-1] == 'c': stream.append(note3) if array[i-1] == 'd': stream.append(note4) if array[i-1] == 'e': stream.append(note5) if array[i-1] == 'f': stream.append(note6) if array[i-1] == 'g': stream.append(note7) if array[i-1] == 'n': stream.append(note8) return stream piano_stream=append_stream(tune_array_piano, piano_stream) guitar_stream=append_stream(tune_array_guitar, guitar_stream) bass_stream=append_stream(tune_array_bass, bass_stream) trumpet_stream=append_stream(tune_array_trumpet, trumpet_stream) print("Piano") piano_stream.show() print("Guitar") guitar_stream.show() print("Bass") bass_stream.show() print("Trumpet") trumpet_stream.show()
https://github.com/CynthiaRios/quantum_orchestra
CynthiaRios
![alt text](./jupyter_images/header.png "Header") #Will redo on quentin's computer tomorrow (today) pip install ipywidgets #conda install -c conda-forge ipywidgets pip install music21 pip install pydub pip install RISE ## General Imports from qiskit import QuantumCircuit, execute from qiskit import Aer from shutil import copyfile from qiskit.visualization import plot_histogram from qiskit import IBMQ import qiskit.tools.jupyter import os %qiskit_job_watcher from IPython.display import Audio import wave import numpy as np ## Button Display Imports (Needs installations mentioned above) from IPython.display import display, Markdown, clear_output # widget packages import ipywidgets as widgets from pydub import AudioSegment from music21 import * ![alt text](./jupyter_images/quantumgates.png "Quantum Gates") #Will redo on quentin's computer tomorrow (today) piano_input = [None] * 5 piano = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([piano, piano2, piano3, piano4, piano5]) box guitar_input = [None] * 5 guitar = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([guitar, guitar2, guitar3, guitar4, guitar5]) box trumpet_input = [None] * 5 trumpet = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([trumpet, trumpet2, trumpet3, trumpet4, trumpet5]) box bass_input = [None] * 5 bass = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([bass, bass2, bass3, bass4, bass5]) box def GetGates(piano_input, guitar_input, bass_input, trumpet_input): if (piano.value == 'No Gate'): piano_input[0] = 'n' if (piano.value == 'X-Gate'): piano_input[0] = 'x' if (piano.value == 'Y-Gate'): piano_input[0] = 'y' if (piano.value == 'Z-Gate'): piano_input[0] = 'z' if (piano2.value == 'No Gate'): piano_input[1] = 'n' if (piano2.value == 'X-Gate'): piano_input[1] = 'x' if (piano2.value == 'Y-Gate'): piano_input[1] = 'y' if (piano2.value == 'Z-Gate'): piano_input[1] = 'z' if (piano3.value == 'No Gate'): piano_input[2] = 'n' if (piano3.value == 'X-Gate'): piano_input[2] = 'x' if (piano3.value == 'Y-Gate'): piano_input[2] = 'y' if (piano3.value == 'Z-Gate'): piano_input[2] = 'z' if (piano4.value == 'No Gate'): piano_input[3] = 'n' if (piano4.value == 'X-Gate'): piano_input[3] = 'x' if (piano4.value == 'Y-Gate'): piano_input[3] = 'y' if (piano4.value == 'Z-Gate'): piano_input[3] = 'z' if (piano5.value == 'No Gate'): piano_input[4] = 'n' if (piano5.value == 'X-Gate'): piano_input[4] = 'x' if (piano5.value == 'Y-Gate'): piano_input[4] = 'y' if (piano5.value == 'Z-Gate'): piano_input[4] = 'z' if (guitar.value == 'No Gate'): guitar_input[0] = 'n' if (guitar.value == 'X-Gate'): guitar_input[0] = 'x' if (guitar.value == 'Y-Gate'): guitar_input[0] = 'y' if (guitar.value == 'Z-Gate'): guitar_input[0] = 'z' if (guitar2.value == 'No Gate'): guitar_input[1] = 'n' if (guitar2.value == 'X-Gate'): guitar_input[1] = 'x' if (guitar2.value == 'Y-Gate'): guitar_input[1] = 'y' if (guitar2.value == 'Z-Gate'): guitar_input[1] = 'z' if (guitar3.value == 'No Gate'): guitar_input[2] = 'n' if (guitar3.value == 'X-Gate'): guitar_input[2] = 'x' if (guitar3.value == 'Y-Gate'): guitar_input[2] = 'y' if (guitar3.value == 'Z-Gate'): guitar_input[2] = 'z' if (guitar4.value == 'No Gate'): guitar_input[3] = 'n' if (guitar4.value == 'X-Gate'): guitar_input[3] = 'x' if (guitar4.value == 'Y-Gate'): guitar_input[3] = 'y' if (guitar4.value == 'Z-Gate'): guitar_input[3] = 'z' if (guitar5.value == 'No Gate'): guitar_input[4] = 'n' if (guitar5.value == 'X-Gate'): guitar_input[4] = 'x' if (guitar5.value == 'Y-Gate'): guitar_input[4] = 'y' if (guitar5.value == 'Z-Gate'): guitar_input[4] = 'z' if (bass.value == 'No Gate'): bass_input[0] = 'n' if (bass.value == 'X-Gate'): bass_input[0] = 'x' if (bass.value == 'Y-Gate'): bass_input[0] = 'y' if (bass.value == 'Z-Gate'): bass_input[0] = 'z' if (bass2.value == 'No Gate'): bass_input[1] = 'n' if (bass2.value == 'X-Gate'): bass_input[1] = 'x' if (bass2.value == 'Y-Gate'): bass_input[1] = 'y' if (bass2.value == 'Z-Gate'): bass_input[1] = 'z' if (bass3.value == 'No Gate'): bass_input[2] = 'n' if (bass3.value == 'X-Gate'): bass_input[2] = 'x' if (bass3.value == 'Y-Gate'): bass_input[2] = 'y' if (bass3.value == 'Z-Gate'): bass_input[2] = 'z' if (bass4.value == 'No Gate'): bass_input[3] = 'n' if (bass4.value == 'X-Gate'): bass_input[3] = 'x' if (bass4.value == 'Y-Gate'): bass_input[3] = 'y' if (bass4.value == 'Z-Gate'): bass_input[3] = 'z' if (bass5.value == 'No Gate'): bass_input[4] = 'n' if (bass5.value == 'X-Gate'): bass_input[4] = 'x' if (bass5.value == 'Y-Gate'): bass_input[4] = 'y' if (bass5.value == 'Z-Gate'): bass_input[4] = 'z' if (trumpet.value == 'No Gate'): trumpet_input[0] = 'n' if (trumpet.value == 'X-Gate'): trumpet_input[0] = 'x' if (trumpet.value == 'Y-Gate'): trumpet_input[0] = 'y' if (trumpet.value == 'Z-Gate'): trumpet_input[0] = 'z' if (trumpet2.value == 'No Gate'): trumpet_input[1] = 'n' if (trumpet2.value == 'X-Gate'): trumpet_input[1] = 'x' if (trumpet2.value == 'Y-Gate'): trumpet_input[1] = 'y' if (trumpet2.value == 'Z-Gate'): trumpet_input[1] = 'z' if (trumpet3.value == 'No Gate'): trumpet_input[2] = 'n' if (trumpet3.value == 'X-Gate'): trumpet_input[2] = 'x' if (trumpet3.value == 'Y-Gate'): trumpet_input[2] = 'y' if (trumpet3.value == 'Z-Gate'): trumpet_input[2] = 'z' if (trumpet4.value == 'No Gate'): trumpet_input[3] = 'n' if (trumpet4.value == 'X-Gate'): trumpet_input[3] = 'x' if (trumpet4.value == 'Y-Gate'): trumpet_input[3] = 'y' if (trumpet4.value == 'Z-Gate'): trumpet_input[3] = 'z' if (trumpet5.value == 'No Gate'): trumpet_input[4] = 'n' if (trumpet5.value == 'X-Gate'): trumpet_input[4] = 'x' if (trumpet5.value == 'Y-Gate'): trumpet_input[4] = 'y' if (trumpet5.value == 'Z-Gate'): trumpet_input[4] = 'z' return (piano_input, guitar_input, bass_input, trumpet_input) piano_input, guitar_input, bass_input, trumpet_input = GetGates(piano_input, guitar_input, bass_input, trumpet_input) #minimum user input will just be for them to fill out the create quantum circuit function inthe backend n = 5 #number of gates backend = Aer.get_backend('statevector_simulator') piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] def CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input): cct = QuantumCircuit(4,1) piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] for i in range(n-1): cct.h(i-1) cct.barrier() for i in range(n): if piano_input[i-1] == 'x': cct.x(0) if piano_input[i-1] == 'y': cct.y(0) if piano_input[i-1] == 'z': cct.z(0) piano_states.append(execute(cct, backend).result().get_statevector()) if guitar_input[i-1] == 'x': cct.x(1) if guitar_input[i-1] == 'y': cct.y(1) if guitar_input[i-1] == 'z': cct.z(1) guitar_states.append(execute(cct, backend).result().get_statevector()) if bass_input[i-1] == 'x': cct.x(2) if bass_input[i-1] == 'y': cct.y(2) if bass_input[i-1] == 'z': cct.z(2) bass_states.append(execute(cct, backend).result().get_statevector()) if trumpet_input[i-1] == 'x': cct.x(3) if trumpet_input[i-1] == 'y': cct.y(3) if trumpet_input[i-1] == 'z': cct.z(3) trumpet_states.append(execute(cct, backend).result().get_statevector()) cct.barrier() cct.draw('mpl') return piano_states, guitar_states, bass_states, trumpet_states, cct piano_states, guitar_states, bass_states, trumpet_states, cct = CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input) cct.draw(output="mpl") def SeperateArrays(states, vals_real, vals_imaginary): vals = [] for i in range(n+1): vals.append(states[i-1][0]) for i in range(n+1): vals_real.append((states[i-1][0].real)) vals_imaginary.append((states[i-1][0]).imag) return vals_real, vals_imaginary piano_real = [] piano_imaginary = [] piano_vals = [] guitar_real = [] guitar_imaginary = [] guitar_vals = [] bass_real = [] bass_imaginary = [] bass_vals = [] trumpet_real = [] trumpet_imaginary = [] trumpet_vals = [] piano_real, piano_imaginary = SeperateArrays(piano_states, piano_real, piano_imaginary) guitar_real, guitar_imaginary = SeperateArrays(guitar_states, guitar_real, guitar_imaginary) bass_real, bass_imaginary = SeperateArrays(bass_states, bass_real, bass_imaginary) trumpet_real, trumpet_imaginary = SeperateArrays(trumpet_states, trumpet_real, trumpet_imaginary) def MusicalTransformation(real, imaginary): tune_array=[] for i in range(n+1): if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('c') tune_array.append('g') tune_array.append('e') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('c') tune_array.append('f') tune_array.append('g') if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('f') tune_array.append('a') tune_array.append('c') if(real[i-1] > 0 and imaginary[i-1] > 0): tune_array.append('g') tune_array.append('b') tune_array.append('d') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] > 0 and imaginary[i-1] >= 0): tune_array.append('e') tune_array.append('g') tune_array.append('b') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('a') tune_array.append('c') tune_array.append('b') if(real[i-1] == 0 and imaginary[i-1] == 0): tune_array.append('n') tune_array.append('n') tune_array.append('n') return tune_array tune_array_piano = MusicalTransformation(piano_real, piano_imaginary) tune_array_guitar = MusicalTransformation(guitar_real, guitar_imaginary) tune_array_bass = MusicalTransformation(bass_real, bass_imaginary) tune_array_trumpet = MusicalTransformation(trumpet_real, trumpet_imaginary) def PlayPianoTune(character, songs): if character == 'a': sound_file = "./Audio/Piano/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Piano/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Piano/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Piano/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Piano/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Piano/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Piano/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayGuitarTune(character, songs): if character == 'a': sound_file = "./Audio/Guitar/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Guitar/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Guitar/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Guitar/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Guitar/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Guitar/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Guitar/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayBassTune(character, songs): if character == 'a': sound_file = "./Audio/Bass/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Bass/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Bass/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Bass/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Bass/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Bass/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Bass/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayTrumpetTune(character, songs): if character == 'a': sound_file = "./Audio/Trumpet/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Trumpet/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Trumpet/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Trumpet/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Trumpet/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Trumpet/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Trumpet/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs piano_song = [] for i in range(len(tune_array_piano)): character = tune_array_piano[i-1] piano_song = PlayPianoTune(character, piano_song) os.remove("./pianosounds.wav") copyfile('./Audio/blank.wav','./pianosounds.wav') for i in range(len(tune_array_piano)): infiles = [piano_song[i-1], "pianosounds.wav"] outfile = "pianosounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() guitar_song = [] for i in range(len(tune_array_guitar)): character = tune_array_piano[i-1] guitar_song = PlayGuitarTune(character, guitar_song) os.remove("./guitarsounds.wav") copyfile('./Audio/blank.wav','./guitarsounds.wav') for i in range(len(tune_array_guitar)): infiles = [guitar_song[i-1], "guitarsounds.wav"] outfile = "guitarsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() bass_song = [] for i in range(len(tune_array_bass)): character = tune_array_bass[i-1] bass_song = PlayBassTune(character, bass_song) os.remove("./basssounds.wav") copyfile('./Audio/blank.wav','./basssounds.wav') for i in range(len(tune_array_bass)): infiles = [bass_song[i-1], "basssounds.wav"] outfile = "basssounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() trumpet_song = [] for i in range(len(tune_array_trumpet)): character = tune_array_trumpet[i-1] trumpet_song = PlayTrumpetTune(character, trumpet_song) os.remove("./trumpetsounds.wav") copyfile('./Audio/blank.wav','./trumpetsounds.wav') for i in range(len(tune_array_trumpet)): infiles = [trumpet_song[i-1], "trumpetsounds.wav"] outfile = "trumpetsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() sound1 = AudioSegment.from_file("./trumpetsounds.wav") sound2 = AudioSegment.from_file("./basssounds.wav") combined = sound1.overlay(sound2) combined.export("./combined.wav", format='wav') sound3 = AudioSegment.from_file("./guitarsounds.wav") sound4 = AudioSegment.from_file("./pianosounds.wav") combined2 = sound3.overlay(sound4) combined2.export("./combined2.wav", format='wav') sound5 = AudioSegment.from_file("./combined.wav") sound6 = AudioSegment.from_file("./combined2.wav") output_song = sound5.overlay(sound6) output_song.export("./output_song.wav", format='wav') sound_file = "./output_song.wav" Audio(sound_file, autoplay=True) print(tune_array_piano) a = 64 b = 65 c = 66 d = 67 e = 68 f = 69 g = 70 print(tune_array_piano[0]) streamPiano = stream.Stream() instrumentPiano = [] for i in range(18): instrumentPiano.append(note.Note(tune_array_piano[i])) streamPiano.append(instrumentPiano) streamPiano.show() a = 57 b = 58 c = 59 d = 60 e = 61 f = 62 g = 63 print(tune_array_guitar) streamGuitar = stream.Stream() instrumentGuitar = [] for i in range(18): instrumentGuitar.append(note.Note(tune_array_guitar[i])) streamGuitar.append(instrumentGuitar) streamGuitar.show() a = 50 b = 51 c = 52 d = 53 e = 54 f = 55 g = 56 print(tune_array_trumpet) streamTrumpet = stream.Stream() streamBass = stream.Stream() instrumentTrumpet = [] for i in range(18): instrumentTrumpet.append(note.Note(tune_array_trumpet[i])) streamTrumpet.append(instrumentTrumpet) streamTrumpet.show() a = 43 b = 44 c = 45 d = 46 e = 47 f = 48 g = 49 print(tune_array_bass) streamBass = stream.Stream() instrumentBass = [] for i in range(18): instrumentBass.append(note.Note(tune_array_bass[i])) streamBass.append(instrumentBass) streamBass.show() excerpt = streamPiano.measures(1, 4) excerpt.show() streamPiano.getElementsByClass('Measure').insert(0.0, instrument.Piano()) streamGuitar.getElementsByClass('Measure').insert(1.0, instrument.Guitar()) streamTrumpet.getElementsByClass('Measure').insert(2.0, instrument.Trumpet()) streamBass.getElementsByClass('Measure').insert(3.0, instrument.Bass()) s = stream.Score() s.insert(0, streamPiano) s.insert(0, streamGuitar) s.insert(0, streamTrumpet) s.insert(0, streamBass) s.show() s.show('musicxml') #this show on musescore
https://github.com/CynthiaRios/quantum_orchestra
CynthiaRios
![header](./jupyter_images/header.png "Header") ## General Imports from qiskit import QuantumCircuit, execute from qiskit import Aer from shutil import copyfile from qiskit.visualization import plot_histogram from qiskit import IBMQ import qiskit.tools.jupyter import os %qiskit_job_watcher from IPython.display import Audio import wave import numpy as np ## Button Display Imports (Needs installations mentioned above) from IPython.display import display, Markdown, clear_output # widget packages import ipywidgets as widgets from pydub import AudioSegment ![QuantumGates](./jupyter_images/quantumgates.png "Quantum Gates") #Will redo on quentin's computer tomorrow (today) piano_input = [None] * 5 piano = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([piano, piano2, piano3, piano4, piano5]) box guitar_input = [None] * 5 guitar = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([guitar, guitar2, guitar3, guitar4, guitar5]) box bass_input = [None] * 5 bass = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([bass, bass2, bass3, bass4, bass5]) box trumpet_input = [None] * 5 trumpet = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([trumpet, trumpet2, trumpet3, trumpet4, trumpet5]) box def GetGates(piano_input, guitar_input, bass_input, trumpet_input): if (piano.value == 'No Gate'): piano_input[0] = 'n' if (piano.value == 'X-Gate'): piano_input[0] = 'x' if (piano.value == 'Y-Gate'): piano_input[0] = 'y' if (piano.value == 'Z-Gate'): piano_input[0] = 'z' if (piano2.value == 'No Gate'): piano_input[1] = 'n' if (piano2.value == 'X-Gate'): piano_input[1] = 'x' if (piano2.value == 'Y-Gate'): piano_input[1] = 'y' if (piano2.value == 'Z-Gate'): piano_input[1] = 'z' if (piano3.value == 'No Gate'): piano_input[2] = 'n' if (piano3.value == 'X-Gate'): piano_input[2] = 'x' if (piano3.value == 'Y-Gate'): piano_input[2] = 'y' if (piano3.value == 'Z-Gate'): piano_input[2] = 'z' if (piano4.value == 'No Gate'): piano_input[3] = 'n' if (piano4.value == 'X-Gate'): piano_input[3] = 'x' if (piano4.value == 'Y-Gate'): piano_input[3] = 'y' if (piano4.value == 'Z-Gate'): piano_input[3] = 'z' if (piano5.value == 'No Gate'): piano_input[4] = 'n' if (piano5.value == 'X-Gate'): piano_input[4] = 'x' if (piano5.value == 'Y-Gate'): piano_input[4] = 'y' if (piano5.value == 'Z-Gate'): piano_input[4] = 'z' if (guitar.value == 'No Gate'): guitar_input[0] = 'n' if (guitar.value == 'X-Gate'): guitar_input[0] = 'x' if (guitar.value == 'Y-Gate'): guitar_input[0] = 'y' if (guitar.value == 'Z-Gate'): guitar_input[0] = 'z' if (guitar2.value == 'No Gate'): guitar_input[1] = 'n' if (guitar2.value == 'X-Gate'): guitar_input[1] = 'x' if (guitar2.value == 'Y-Gate'): guitar_input[1] = 'y' if (guitar2.value == 'Z-Gate'): guitar_input[1] = 'z' if (guitar3.value == 'No Gate'): guitar_input[2] = 'n' if (guitar3.value == 'X-Gate'): guitar_input[2] = 'x' if (guitar3.value == 'Y-Gate'): guitar_input[2] = 'y' if (guitar3.value == 'Z-Gate'): guitar_input[2] = 'z' if (guitar4.value == 'No Gate'): guitar_input[3] = 'n' if (guitar4.value == 'X-Gate'): guitar_input[3] = 'x' if (guitar4.value == 'Y-Gate'): guitar_input[3] = 'y' if (guitar4.value == 'Z-Gate'): guitar_input[3] = 'z' if (guitar5.value == 'No Gate'): guitar_input[4] = 'n' if (guitar5.value == 'X-Gate'): guitar_input[4] = 'x' if (guitar5.value == 'Y-Gate'): guitar_input[4] = 'y' if (guitar5.value == 'Z-Gate'): guitar_input[4] = 'z' if (bass.value == 'No Gate'): bass_input[0] = 'n' if (bass.value == 'X-Gate'): bass_input[0] = 'x' if (bass.value == 'Y-Gate'): bass_input[0] = 'y' if (bass.value == 'Z-Gate'): bass_input[0] = 'z' if (bass2.value == 'No Gate'): bass_input[1] = 'n' if (bass2.value == 'X-Gate'): bass_input[1] = 'x' if (bass2.value == 'Y-Gate'): bass_input[1] = 'y' if (bass2.value == 'Z-Gate'): bass_input[1] = 'z' if (bass3.value == 'No Gate'): bass_input[2] = 'n' if (bass3.value == 'X-Gate'): bass_input[2] = 'x' if (bass3.value == 'Y-Gate'): bass_input[2] = 'y' if (bass3.value == 'Z-Gate'): bass_input[2] = 'z' if (bass4.value == 'No Gate'): bass_input[3] = 'n' if (bass4.value == 'X-Gate'): bass_input[3] = 'x' if (bass4.value == 'Y-Gate'): bass_input[3] = 'y' if (bass4.value == 'Z-Gate'): bass_input[3] = 'z' if (bass5.value == 'No Gate'): bass_input[4] = 'n' if (bass5.value == 'X-Gate'): bass_input[4] = 'x' if (bass5.value == 'Y-Gate'): bass_input[4] = 'y' if (bass5.value == 'Z-Gate'): bass_input[4] = 'z' if (trumpet.value == 'No Gate'): trumpet_input[0] = 'n' if (trumpet.value == 'X-Gate'): trumpet_input[0] = 'x' if (trumpet.value == 'Y-Gate'): trumpet_input[0] = 'y' if (trumpet.value == 'Z-Gate'): trumpet_input[0] = 'z' if (trumpet2.value == 'No Gate'): trumpet_input[1] = 'n' if (trumpet2.value == 'X-Gate'): trumpet_input[1] = 'x' if (trumpet2.value == 'Y-Gate'): trumpet_input[1] = 'y' if (trumpet2.value == 'Z-Gate'): trumpet_input[1] = 'z' if (trumpet3.value == 'No Gate'): trumpet_input[2] = 'n' if (trumpet3.value == 'X-Gate'): trumpet_input[2] = 'x' if (trumpet3.value == 'Y-Gate'): trumpet_input[2] = 'y' if (trumpet3.value == 'Z-Gate'): trumpet_input[2] = 'z' if (trumpet4.value == 'No Gate'): trumpet_input[3] = 'n' if (trumpet4.value == 'X-Gate'): trumpet_input[3] = 'x' if (trumpet4.value == 'Y-Gate'): trumpet_input[3] = 'y' if (trumpet4.value == 'Z-Gate'): trumpet_input[3] = 'z' if (trumpet5.value == 'No Gate'): trumpet_input[4] = 'n' if (trumpet5.value == 'X-Gate'): trumpet_input[4] = 'x' if (trumpet5.value == 'Y-Gate'): trumpet_input[4] = 'y' if (trumpet5.value == 'Z-Gate'): trumpet_input[4] = 'z' return (piano_input, guitar_input, bass_input, trumpet_input) piano_input, guitar_input, bass_input, trumpet_input = GetGates(piano_input, guitar_input, bass_input, trumpet_input) #minimum user input will just be for them to fill out the create quantum circuit function inthe backend n = 5 #number of gates backend = Aer.get_backend('statevector_simulator') piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] def CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input): cct = QuantumCircuit(4,1) piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] for i in range(n-1): cct.h(i-1) cct.barrier() for i in range(n): if piano_input[i-1] == 'x': cct.x(0) if piano_input[i-1] == 'y': cct.y(0) if piano_input[i-1] == 'z': cct.z(0) piano_states.append(execute(cct, backend).result().get_statevector()) if guitar_input[i-1] == 'x': cct.x(1) if guitar_input[i-1] == 'y': cct.y(1) if guitar_input[i-1] == 'z': cct.z(1) guitar_states.append(execute(cct, backend).result().get_statevector()) if bass_input[i-1] == 'x': cct.x(2) if bass_input[i-1] == 'y': cct.y(2) if bass_input[i-1] == 'z': cct.z(2) bass_states.append(execute(cct, backend).result().get_statevector()) if trumpet_input[i-1] == 'x': cct.x(3) if trumpet_input[i-1] == 'y': cct.y(3) if trumpet_input[i-1] == 'z': cct.z(3) trumpet_states.append(execute(cct, backend).result().get_statevector()) cct.barrier() cct.draw('mpl') return piano_states, guitar_states, bass_states, trumpet_states, cct piano_states, guitar_states, bass_states, trumpet_states, cct = CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input) cct.draw(output="mpl") def SeperateArrays(states, vals_real, vals_imaginary): vals = [] for i in range(n+1): vals.append(states[i-1][0]) for i in range(n+1): vals_real.append((states[i-1][0].real)) vals_imaginary.append((states[i-1][0]).imag) return vals_real, vals_imaginary piano_real = [] piano_imaginary = [] piano_vals = [] guitar_real = [] guitar_imaginary = [] guitar_vals = [] bass_real = [] bass_imaginary = [] bass_vals = [] trumpet_real = [] trumpet_imaginary = [] trumpet_vals = [] piano_real, piano_imaginary = SeperateArrays(piano_states, piano_real, piano_imaginary) guitar_real, guitar_imaginary = SeperateArrays(guitar_states, guitar_real, guitar_imaginary) bass_real, bass_imaginary = SeperateArrays(bass_states, bass_real, bass_imaginary) trumpet_real, trumpet_imaginary = SeperateArrays(trumpet_states, trumpet_real, trumpet_imaginary) def MusicalTransformation(real, imaginary): tune_array=[] for i in range(n+1): if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('c') tune_array.append('g') tune_array.append('e') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('c') tune_array.append('f') tune_array.append('g') if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('f') tune_array.append('a') tune_array.append('c') if(real[i-1] > 0 and imaginary[i-1] > 0): tune_array.append('g') tune_array.append('b') tune_array.append('d') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] > 0 and imaginary[i-1] >= 0): tune_array.append('e') tune_array.append('g') tune_array.append('b') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('a') tune_array.append('c') tune_array.append('b') if(real[i-1] == 0 and imaginary[i-1] == 0): tune_array.append('n') tune_array.append('n') tune_array.append('n') return tune_array tune_array_piano = MusicalTransformation(piano_real, piano_imaginary) tune_array_guitar = MusicalTransformation(guitar_real, guitar_imaginary) tune_array_bass = MusicalTransformation(bass_real, bass_imaginary) tune_array_trumpet = MusicalTransformation(trumpet_real, trumpet_imaginary) def PlayPianoTune(character, songs): if character == 'a': sound_file = "./Audio/Piano/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Piano/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Piano/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Piano/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Piano/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Piano/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Piano/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayGuitarTune(character, songs): if character == 'a': sound_file = "./Audio/Guitar/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Guitar/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Guitar/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Guitar/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Guitar/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Guitar/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Guitar/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayBassTune(character, songs): if character == 'a': sound_file = "./Audio/Bass/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Bass/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Bass/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Bass/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Bass/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Bass/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Bass/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayTrumpetTune(character, songs): if character == 'a': sound_file = "./Audio/Trumpet/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Trumpet/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Trumpet/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Trumpet/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Trumpet/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Trumpet/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Trumpet/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs piano_song = [] for i in range(len(tune_array_piano)): character = tune_array_piano[i-1] piano_song = PlayPianoTune(character, piano_song) os.remove("./pianosounds.wav") copyfile('./Audio/blank.wav','./pianosounds.wav') for i in range(len(tune_array_piano)): infiles = [piano_song[i-1], "pianosounds.wav"] outfile = "pianosounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() guitar_song = [] for i in range(len(tune_array_guitar)): character = tune_array_piano[i-1] guitar_song = PlayGuitarTune(character, guitar_song) os.remove("./guitarsounds.wav") copyfile('./Audio/blank.wav','./guitarsounds.wav') for i in range(len(tune_array_guitar)): infiles = [guitar_song[i-1], "guitarsounds.wav"] outfile = "guitarsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() bass_song = [] for i in range(len(tune_array_bass)): character = tune_array_bass[i-1] bass_song = PlayBassTune(character, bass_song) os.remove("./basssounds.wav") copyfile('./Audio/blank.wav','./basssounds.wav') for i in range(len(tune_array_bass)): infiles = [bass_song[i-1], "basssounds.wav"] outfile = "basssounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() trumpet_song = [] for i in range(len(tune_array_trumpet)): character = tune_array_trumpet[i-1] trumpet_song = PlayTrumpetTune(character, trumpet_song) os.remove("./trumpetsounds.wav") copyfile('./Audio/blank.wav','./trumpetsounds.wav') for i in range(len(tune_array_trumpet)): infiles = [trumpet_song[i-1], "trumpetsounds.wav"] outfile = "trumpetsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() os.remove("./combined.wav") copyfile('./Audio/blank.wav','./combined.wav') os.remove("./combined2.wav") copyfile('./Audio/blank.wav','./combined2.wav') copyfile('./Audio/blank.wav','./output_song.wav') sound1 = AudioSegment.from_file("./trumpetsounds.wav") sound2 = AudioSegment.from_file("./basssounds.wav") combined = sound1.overlay(sound2) combined.export("./combined.wav", format='wav') sound3 = AudioSegment.from_file("./guitarsounds.wav") sound4 = AudioSegment.from_file("./pianosounds.wav") combined2 = sound3.overlay(sound4) combined2.export("./combined2.wav", format='wav') sound5 = AudioSegment.from_file("./combined.wav") sound6 = AudioSegment.from_file("./combined2.wav") output_song = sound5.overlay(sound6) output_song.export("./outputsong.wav", format='wav') sound_file = "./outputsong.wav" Audio(sound_file, autoplay=True) #https://musescore.org/en/download/musescore.msi !pip install music21 !pip install RISE from music21 import * #for Windows OS error #us = environment.UserSettings() #C:\Program Files\MuseScore 3\bin\MuseScore3.exe #us['musicxmlPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe" #us['musescoreDirectPNGPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe" piano_stream = stream.Stream() guitar_stream = stream.Stream() bass_stream = stream.Stream() trumpet_stream = stream.Stream() note1 = note.Note("A") note2 = note.Note("B") note3 = note.Note("C") note4 = note.Note("D") note5 = note.Note("E") note6 = note.Note("F") note7 = note.Note("G") def append_stream(array, stream): for i in range(n+1): if array[i-1] == 'a': stream.append(note1) if array[i-1] == 'b': stream.append(note2) if array[i-1] == 'c': stream.append(note3) if array[i-1] == 'd': stream.append(note4) if array[i-1] == 'e': stream.append(note5) if array[i-1] == 'f': stream.append(note6) if array[i-1] == 'g': stream.append(note7) return stream piano_stream=append_stream(tune_array_piano, piano_stream) guitar_stream=append_stream(tune_array_guitar, guitar_stream) bass_stream=append_stream(tune_array_bass, bass_stream) trumpet_stream=append_stream(tune_array_trumpet, trumpet_stream) piano_stream.show() guitar_stream.show() bass_stream.show() trumpet_stream.show()
https://github.com/CynthiaRios/quantum_orchestra
CynthiaRios
#pip install music21 #pip install RISE from qiskit import QuantumCircuit, execute from qiskit import Aer from qiskit.visualization import plot_histogram from qiskit import IBMQ import qiskit.tools.jupyter %qiskit_job_watcher from IPython.display import Audio import wave import numpy as np #start for the project # import from music21 import * #minimum user input will just be for them to fill out the create quantum circuit function inthe backend n = 1 #insert number of qubits def CreateQuantumCircuit(n): cct = QuantumCircuit(n,1) cct.h(0) return cct cct = CreateQuantumCircuit(n) cct.draw(output="mpl") def Measurement(cct): backend = Aer.get_backend('statevector_simulator') sv = execute(cct, backend).result().get_statevector() return sv sv = Measurement(cct) print(sv) #from qiskit.visualization import plot_state_city #plot_state_city(sv) def MusicalTransformation(): note = 'a'; return note tune_array = ['c','d'] #collect notes #for i in range(n+1): # note = MusicalTransformation() # tune_array.append(note) print(tune_array) def PlayPianoTune(character, song): if character == 'c': sound_file = "./Audio/Piano/1-st.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Piano/2-st.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Piano/3-st.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Piano/4-st.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Piano/5-st.wav" songs.append(sound_file) def PlayGuitarTune(character, song): if character == 'c': sound_file = "./Audio/Guitar/1-ag.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Guitar/2-ag.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Guitar/3-ag.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Guitar/4-ag.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Guitar/5-ag.wav" songs.append(sound_file) def PlayBassTune(character, song): if character == 'c': sound_file = "./Audio/Bass/1.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Bass/2.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Bass/3.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Bass/4.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Bass/5.wav" songs.append(sound_file) def PlayTrumpetTune(character, song): if character == 'c': sound_file = "./Audio/Trumpet/1.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Trumpet/2.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Trumpet/3.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Trumpet/4.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Trumpet/5.wav" songs.append(sound_file) songs = [] for i in range(n+1): character = tune_array[i-1] PlayPianoTune(character, songs) print(songs) outfile = "pianosounds.wav" data= [] for song in songs: w = wave.open(song, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() songs = [] for i in range(n+1): character = tune_array[i-1] PlayGuitarTune(character, songs) print(songs) outfile = "guitarsounds.wav" data= [] for song in songs: w = wave.open(song, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() songs = [] for i in range(n+1): character = tune_array[i-1] PlayTrumpetTune(character, songs) print(songs) outfile = "trumpetsounds.wav" data= [] for song in songs: w = wave.open(song, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() songs = [] for i in range(n+1): character = tune_array[i-1] PlayBassTune(character, songs) print(songs) outfile = "basssounds.wav" data= [] for song in songs: w = wave.open(song, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() sound_file = "./pianosounds.wav" Audio(sound_file, autoplay=True) sound_file = "./guitarsounds.wav" Audio(sound_file, autoplay=True) sound_file = "./basssounds.wav" Audio(sound_file, autoplay=True) sound_file = "./trumpetsounds.wav" Audio(sound_file, autoplay=True) up1 = note.Unpitched() up1.storedInstrument = instrument.BassDrum() upUnknownInstrument = note.Unpitched() up2 = note.Unpitched() up2.storedInstrument = instrument.Cowbell() s = stream.Stream() s.append(up1) s.append(upUnknownInstrument) s.append(up2) s2 = instrument.unbundleInstruments(s) s3 = instrument.bundleInstruments(s2) for test in s3: print(test.storedInstrument) instrument.ensembleNameBySize(4) instrument.ensembleNameBySize(1) instrument.ensembleNameBySize(83) t1 = instrument.fromString('Clarinet 2 in A') t1 t1.transposition t2 = instrument.fromString('Clarinetto 3') t2 t3 = instrument.fromString('flauto 2') t3 t4 = instrument.fromString('I <3 music saxofono tenor go beavers') t4 t5 = instrument.fromString('Bb Clarinet') t5 t5.transposition t6 = instrument.fromString('Clarinet in B-flat') t5.__class__ == t6.__class__ t5.transposition == t6.transposition t7 = instrument.fromString('B-flat Clarinet.') t5.__class__ == t7.__class__ and t5.transposition == t7.transposition t8 = instrument.fromString('Eb Clarinet') t5.__class__ == t8.__class__ t8.transposition t9 = instrument.fromString('Klarinette in B.') t9 t9.transposition instrument.instrumentFromMidiProgram(0) instrument.instrumentFromMidiProgram(21) p1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1") p2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1") p1.getElementsByClass('Measure')[0].insert(0.0, instrument.Piccolo()) p1.getElementsByClass('Measure')[0].insert(2.0, instrument.AltoSaxophone()) p1.getElementsByClass('Measure')[1].insert(3.0, instrument.Piccolo()) p2.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone()) p2.getElementsByClass('Measure')[0].insert(3.0, instrument.Piccolo()) # not likely... p2.getElementsByClass('Measure')[1].insert(1.0, instrument.Trombone()) s = stream.Score() s.insert(0, p1) s.insert(0, p2) s.show('musicxml') #this show on musicscore s2 = instrument.partitionByInstrument(s) len(s2.parts) for p in s2.parts: unused = p.makeRests(fillGaps=True, inPlace=True) for p in s2.parts: p.makeMeasures(inPlace=True) p.makeTies(inPlace=True) s2.show('musicxml') up1 = note.Unpitched() up1.storedInstrument = instrument.BassDrum() up2 = note.Unpitched() up2.storedInstrument = instrument.Cowbell() s = stream.Stream() s.append(up1) s.append(up2) s2 = instrument.unbundleInstruments(s) s2.show('musicxml') instrument1 = 60 instrument2 = 65 instrument3 = 70 instrument4 = 75 instrument1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1") instrument2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1") instrument3 = converter.parse("tinynotation: 4/4 e f g a b c d e f") #instrument4 = converter.parse("tinynotation: 4/4 g a b c d e f g a") note1 = note.Note("C4") note2 = note.Note("F#4") note3 = note.Note("F#4") note4 = note.Note("F#4") note5 = note.Note("F#4") note6 = note.Note("F#4") note7 = note.Note("F#4") note8 = note.Note("F#4") note9 = note.Note("F#4") instrument4 = [note1, note2, note3, note4, note5, note6, note7, note8, note9] print(instrument4) stream2 = stream.Stream() stream2.append(instrument4) stream2.getElementsByClass('Measure')[0].insert(0.0, instrument.Tuba()) #This creates a stream of a single part #Add an instrument to the part instrument1.getElementsByClass('Measure')[0].insert(0.0, instrument.Trumpet()) instrument2.getElementsByClass('Measure')[0].insert(0.0, instrument.EnglishHorn()) instrument3.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone()) instrument4.getElementsByClass('Measure')[0].insert(0.0, instrument.Tuba()) s = stream.Score() s.insert(0, instrument1) s.insert(0, instrument2) s.insert(0, instrument3) s.insert(0, instrument4) s.show() s.show('midi') s.show('musicxml') #this show on musicscore stream1 = stream.Stream() stream1.addGroupForElements('flute') stream1.append(midiChordType1) stream1.append(midiChordType2) stream1.append(midiChordType3) stream1.append(midiChordType4) stream1.show('midi') stream1.show('musicxml') #this show on musicscore #c = converter.parse('musicxml') stream1.show() midiChordType1 = chord.Chord([instrument1, instrument2, instrument3, instrument4]) midiChordType2 = chord.Chord([55, 60, 65, 70]) midiChordType2.getElementsByClass('Measure')[0].insert(2.0, instrument.Bass()) midiChordType3 = chord.Chord([50, 55, 60, 70]) midiChordType3.getElementsByClass('Measure')[1].insert(3.0, instrument.Guitar()) midiChordType4 = chord.Chord([65, 70, 75, 80]) midiChordType4.getElementsByClass('Measure')[1].insert(3.0, instrument.Trombone()) note1 = note.Note("C4") note2 = note.Note("F#4") note3 = note.Note("B-2") stream1 = stream.Stream() stream1.append(note1) stream1.append(note2) stream1.append(note3) stream1.show('midi') note1 = midiChordType midiChordType1 = chord.Chord([60, 65, 70, 75]) midiChordType2 = chord.Chord([55, 60, 65, 70]) midiChordType3 = chord.Chord([50, 55, 60, 70]) midiChordType4 = chord.Chord([65, 70, 75, 80]) stream1 = stream.Stream() stream1.append(midiChordType1) stream1.append(midiChordType2) stream1.append(midiChordType3) stream1.append(midiChordType4) stream1.show('midi') p1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1") p2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1") p1.show('midi') p2.show('midi') p1.getElementsByClass('Measure')[0].insert(0.0, instrument.Piccolo()) p1.getElementsByClass('Measure')[0].insert(2.0, instrument.AltoSaxophone()) p1.getElementsByClass('Measure')[1].insert(3.0, instrument.Piccolo()) p2.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone()) p2.getElementsByClass('Measure')[0].insert(3.0, instrument.Piccolo()) # not likely... p2.getElementsByClass('Measure')[1].insert(1.0, instrument.Trombone()) s.show() s = corpus.parse('bach/bwv65.2.xml')
https://github.com/CynthiaRios/quantum_orchestra
CynthiaRios
#pip install music21 #pip install RISE from qiskit import QuantumCircuit, execute from qiskit import Aer from qiskit.visualization import plot_histogram from qiskit import IBMQ import qiskit.tools.jupyter %qiskit_job_watcher from IPython.display import Audio import wave import numpy as np #start for the project # import from music21 import * #minimum user input will just be for them to fill out the create quantum circuit function inthe backend n = 1 #insert number of qubits def CreateQuantumCircuit(n): cct = QuantumCircuit(n,1) cct.h(0) return cct cct = CreateQuantumCircuit(n) cct.draw(output="mpl") def Measurement(cct): backend = Aer.get_backend('statevector_simulator') sv = execute(cct, backend).result().get_statevector() return sv sv = Measurement(cct) print(sv) #from qiskit.visualization import plot_state_city #plot_state_city(sv) def MusicalTransformation(): note = 'a'; return note tune_array = ['c','d'] #collect notes #for i in range(n+1): # note = MusicalTransformation() # tune_array.append(note) print(tune_array) def PlayPianoTune(character, song): if character == 'c': sound_file = "./Audio/Piano/1-st.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Piano/2-st.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Piano/3-st.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Piano/4-st.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Piano/5-st.wav" songs.append(sound_file) def PlayGuitarTune(character, song): if character == 'c': sound_file = "./Audio/Guitar/1-ag.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Guitar/2-ag.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Guitar/3-ag.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Guitar/4-ag.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Guitar/5-ag.wav" songs.append(sound_file) def PlayBassTune(character, song): if character == 'c': sound_file = "./Audio/Bass/1.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Bass/2.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Bass/3.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Bass/4.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Bass/5.wav" songs.append(sound_file) def PlayTrumpetTune(character, song): if character == 'c': sound_file = "./Audio/Trumpet/1.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Trumpet/2.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Trumpet/3.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Trumpet/4.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Trumpet/5.wav" songs.append(sound_file) songs = [] for i in range(n+1): character = tune_array[i-1] PlayPianoTune(character, songs) print(songs) outfile = "pianosounds.wav" data= [] for song in songs: w = wave.open(song, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() songs = [] for i in range(n+1): character = tune_array[i-1] PlayGuitarTune(character, songs) print(songs) outfile = "guitarsounds.wav" data= [] for song in songs: w = wave.open(song, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() songs = [] for i in range(n+1): character = tune_array[i-1] PlayTrumpetTune(character, songs) print(songs) outfile = "trumpetsounds.wav" data= [] for song in songs: w = wave.open(song, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() songs = [] for i in range(n+1): character = tune_array[i-1] PlayBassTune(character, songs) print(songs) outfile = "basssounds.wav" data= [] for song in songs: w = wave.open(song, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) output.writeframes(data[0][1]) output.writeframes(data[1][1]) output.close() sound_file = "./pianosounds.wav" Audio(sound_file, autoplay=True) sound_file = "./guitarsounds.wav" Audio(sound_file, autoplay=True) sound_file = "./basssounds.wav" Audio(sound_file, autoplay=True) sound_file = "./trumpetsounds.wav" Audio(sound_file, autoplay=True) up1 = note.Unpitched() up1.storedInstrument = instrument.BassDrum() upUnknownInstrument = note.Unpitched() up2 = note.Unpitched() up2.storedInstrument = instrument.Cowbell() s = stream.Stream() s.append(up1) s.append(upUnknownInstrument) s.append(up2) s2 = instrument.unbundleInstruments(s) s3 = instrument.bundleInstruments(s2) for test in s3: print(test.storedInstrument) instrument.ensembleNameBySize(4) instrument.ensembleNameBySize(1) instrument.ensembleNameBySize(83) t1 = instrument.fromString('Clarinet 2 in A') t1 t1.transposition t2 = instrument.fromString('Clarinetto 3') t2 t3 = instrument.fromString('flauto 2') t3 t4 = instrument.fromString('I <3 music saxofono tenor go beavers') t4 t5 = instrument.fromString('Bb Clarinet') t5 t5.transposition t6 = instrument.fromString('Clarinet in B-flat') t5.__class__ == t6.__class__ t5.transposition == t6.transposition t7 = instrument.fromString('B-flat Clarinet.') t5.__class__ == t7.__class__ and t5.transposition == t7.transposition t8 = instrument.fromString('Eb Clarinet') t5.__class__ == t8.__class__ t8.transposition t9 = instrument.fromString('Klarinette in B.') t9 t9.transposition instrument.instrumentFromMidiProgram(0) instrument.instrumentFromMidiProgram(21) p1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1") p2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1") p1.getElementsByClass('Measure')[0].insert(0.0, instrument.Piccolo()) p1.getElementsByClass('Measure')[0].insert(2.0, instrument.AltoSaxophone()) p1.getElementsByClass('Measure')[1].insert(3.0, instrument.Piccolo()) p2.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone()) p2.getElementsByClass('Measure')[0].insert(3.0, instrument.Piccolo()) # not likely... p2.getElementsByClass('Measure')[1].insert(1.0, instrument.Trombone()) s = stream.Score() s.insert(0, p1) s.insert(0, p2) s.show('musicxml') #this show on musicscore s2 = instrument.partitionByInstrument(s) len(s2.parts) for p in s2.parts: unused = p.makeRests(fillGaps=True, inPlace=True) for p in s2.parts: p.makeMeasures(inPlace=True) p.makeTies(inPlace=True) s2.show('musicxml') up1 = note.Unpitched() up1.storedInstrument = instrument.BassDrum() up2 = note.Unpitched() up2.storedInstrument = instrument.Cowbell() s = stream.Stream() s.append(up1) s.append(up2) s2 = instrument.unbundleInstruments(s) s2.show('musicxml') us = environment.UserSettings() #C:\Program Files\MuseScore 3\bin\MuseScore3.exe us['musicxmlPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe" us['musescoreDirectPNGPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe" print(us) instrument1 = 60 instrument2 = 65 instrument3 = 70 instrument4 = 75 instrument1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1") instrument2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1") instrument3 = converter.parse("tinynotation: 4/4 e f g a b c d e f") #instrument4 = converter.parse("tinynotation: 4/4 g a b c d e f g a") note1 = note.Note("C4") note2 = note.Note("F#4") note3 = note.Note("F#4") note4 = note.Note("F#4") note5 = note.Note("F#4") note6 = note.Note("F#4") note7 = note.Note("F#4") note8 = note.Note("F#4") note9 = note.Note("F#4") instrument4 = [note1, note2, note3, note4, note5, note6, note7, note8, note9] print(instrument4) stream2 = stream.Stream() stream2.append(instrument4) stream2.getElementsByClass('Measure')[0].insert(0.0, instrument.Tuba()) #This creates a stream of a single part #Add an instrument to the part instrument1.getElementsByClass('Measure')[0].insert(0.0, instrument.Trumpet()) instrument2.getElementsByClass('Measure')[0].insert(0.0, instrument.EnglishHorn()) instrument3.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone()) instrument4.getElementsByClass('Measure')[0].insert(0.0, instrument.Tuba()) s = stream.Score() s.insert(0, instrument1) s.insert(0, instrument2) s.insert(0, instrument3) s.insert(0, instrument4) s.show() s.show('midi') s.show('musicxml') #this show on musicscore stream1 = stream.Stream() stream1.addGroupForElements('flute') stream1.append(midiChordType1) stream1.append(midiChordType2) stream1.append(midiChordType3) stream1.append(midiChordType4) stream1.show('midi') stream1.show('musicxml') #this show on musicscore #c = converter.parse('musicxml') stream1.show() midiChordType1 = chord.Chord([instrument1, instrument2, instrument3, instrument4]) midiChordType2 = chord.Chord([55, 60, 65, 70]) midiChordType2.getElementsByClass('Measure')[0].insert(2.0, instrument.Bass()) midiChordType3 = chord.Chord([50, 55, 60, 70]) midiChordType3.getElementsByClass('Measure')[1].insert(3.0, instrument.Guitar()) midiChordType4 = chord.Chord([65, 70, 75, 80]) midiChordType4.getElementsByClass('Measure')[1].insert(3.0, instrument.Trombone()) note1 = note.Note("C4") note2 = note.Note("F#4") note3 = note.Note("B-2") stream1 = stream.Stream() stream1.append(note1) stream1.append(note2) stream1.append(note3) stream1.show('midi') note1 = midiChordType midiChordType1 = chord.Chord([60, 65, 70, 75]) midiChordType2 = chord.Chord([55, 60, 65, 70]) midiChordType3 = chord.Chord([50, 55, 60, 70]) midiChordType4 = chord.Chord([65, 70, 75, 80]) stream1 = stream.Stream() stream1.append(midiChordType1) stream1.append(midiChordType2) stream1.append(midiChordType3) stream1.append(midiChordType4) stream1.show('midi') p1 = converter.parse("tinynotation: 4/4 c4 d e f g a b c' c1") p2 = converter.parse("tinynotation: 4/4 C#4 D# E# F# G# A# B# c# C#1") p1.show('midi') p2.show('midi') p1.getElementsByClass('Measure')[0].insert(0.0, instrument.Piccolo()) p1.getElementsByClass('Measure')[0].insert(2.0, instrument.AltoSaxophone()) p1.getElementsByClass('Measure')[1].insert(3.0, instrument.Piccolo()) p2.getElementsByClass('Measure')[0].insert(0.0, instrument.Trombone()) p2.getElementsByClass('Measure')[0].insert(3.0, instrument.Piccolo()) # not likely... p2.getElementsByClass('Measure')[1].insert(1.0, instrument.Trombone()) s.show() s = corpus.parse('bach/bwv65.2.xml')
https://github.com/qcware/qusetta
qcware
import sys; sys.path.append("..") import qusetta as qs # The first element of the circuit is a column of Hadamards circuit = "H(0); H(1); H(2); " # next we have exp(-i z_0 z_1 gamma / 2) circuit += "CX(0, 1); RZ({gamma})(1); CX(0, 1); " # now the same for exp(-i z_1 z_2 gamma / 2) circuit += "CX(1, 2); RZ({gamma})(2); CX(1, 2); " # now we have a row of x rotations by beta circuit += "RX({beta})(0); RX({beta})(1); RX({beta})(2)" def qusetta_qaoa_circuit(beta, gamma): return circuit.format(beta=beta, gamma=gamma).split("; ") print(qusetta_qaoa_circuit("beta", "gamma")) c = qusetta_qaoa_circuit("PI/2", "PI/4") print(c) print(qs.Cirq.from_qusetta(c)) print(qs.Quasar.from_qusetta(c)) print(qs.Qiskit.from_qusetta(c))
https://github.com/qcware/qusetta
qcware
import numpy as np from qiskit.optimization.applications.ising.common import random_graph np.random.seed(123) num_nodes = 22 w = random_graph(num_nodes, edge_prob=0.8, weight_range=10) from qiskit.optimization.applications.ising import vertex_cover from qiskit.aqua.algorithms import QAOA qubit_op, offset = vertex_cover.get_operator(w) p = 10 qaoa = QAOA(qubit_op, p=p) import qiskit from typing import List def create_qiskit_circuit(params: List[float]) -> qiskit.QuantumCircuit: assert len(params) == 2 * p, "invalid number of angles" return qaoa.var_form.construct_circuit(params) import qusetta as qs import cirq def create_cirq_circuit(params: List[float]) -> cirq.Circuit: qiskit_circuit = create_qiskit_circuit(params) return qs.Qiskit.to_cirq(qiskit_circuit) import quasar def create_quasar_circuit(params: List[float]) -> quasar.Circuit: qiskit_circuit = create_qiskit_circuit(params) return qs.Qiskit.to_quasar(qiskit_circuit) c = create_quasar_circuit([0.] * (2*p)) print("Number of qubits :", c.nqubit) print("Number of gates :", c.ngate) def expectation_value(statevector: np.ndarray) -> float: # note that the second element (eg [1]) is the standard deviation return offset + qubit_op.evaluate_with_statevector(statevector)[0].real from qiskit.optimization.applications.ising.common import sample_most_likely def get_size_cover(statevector: np.ndarray) -> int: return int(sum( vertex_cover.get_graph_solution(sample_most_likely(statevector)) )) from typing import Callable import time f_type = Callable[[List[float]], np.ndarray] def info_decorator(function: f_type) -> f_type: # `function` will be one of statevector_from_qiskit, # statevector_from_quasar, statevector_from_cirq, or statevector_from_vulcan. def f(params: List[float]) -> np.ndarray: print('='*40) print("Simulating with", function.__name__) print('-'*40) t0 = time.time() statevector = function(params) print("Time to completion : ", round(time.time() - t0, 2), "seconds") print("Expectation value : ", round(expectation_value(statevector), 2)) print("Size of cover : ", get_size_cover(statevector)) print('='*40, "\n") return statevector return f @info_decorator def statevector_from_qiskit(params: List[float]) -> np.ndarray: return qiskit.execute( create_qiskit_circuit(params), qiskit.BasicAer.get_backend('statevector_simulator') ).result().get_statevector() @info_decorator def statevector_from_cirq(params: List[float]) -> np.ndarray: return cirq.Simulator(dtype=np.complex128).simulate( create_cirq_circuit(params) ).final_state @info_decorator def statevector_from_quasar(params: List[float]) -> np.ndarray: return quasar.QuasarSimulatorBackend().run_statevector( circuit=create_quasar_circuit(params) ) import qcware from qcware.circuits.quasar_backend import QuasarBackend qcware.config.set_api_key('Put your API key here!') @info_decorator def statevector_from_vulcan(params: List[float]) -> np.ndarray: return QuasarBackend("vulcan/simulator").run_statevector( circuit=create_quasar_circuit(params) ) params = list(np.random.random(2*p) * np.pi) qiskit_statevector = statevector_from_qiskit(params) cirq_statevector = statevector_from_cirq(params) quasar_statevector = statevector_from_quasar(params) vulcan_statevector = statev ector_from_vulcan(params) # check that probability vectors are the same np.testing.assert_allclose(np.abs(qiskit_statevector)**2, np.abs(quasar_statevector)**2) np.testing.assert_allclose(np.abs(cirq_statevector)**2, np.abs(quasar_statevector)**2) np.testing.assert_allclose(np.abs(vulcan_statevector)**2, np.abs(quasar_statevector)**2)
https://github.com/qcware/qusetta
qcware
"""Translating circuits to and from ``qiskit``.""" import qiskit import qusetta as qs from typing import List __all__ = "Qiskit", class Qiskit(qs.Conversions): """Translation methods for qiskit's representation of a circuit. Example -------- Create a qiskit circuit. >>> import qiskit >>> circuit = qiskit.QuantumCircuit(2) >>> circuit.h(0) >>> circuit.cx(0, 1) Convert the qiskit circuit to a cirq circuit. >>> from qusetta import Qiskit >>> cirq_circuit = Qiskit.to_cirq(circuit) Notes ----- As we all know, qiskit is weird in the way that they index their qubits. In particular, they index qubits in reverse order compared to everyone else. Therefore, in order to ensure that the first bullet point is true, qusetta reverses the qubits of a qiskit circuit. Thus, as an example, a qusetta (or cirq, quasar) circuit ``["H(0)", "CX(0, 1)"]`` becomes a qiskit circuit ``["H(1)", "CX(1, 0)"]``. This is how we guarantee that the probability vectors are the same. """ @staticmethod def from_qusetta(circuit: List[str]) -> qiskit.QuantumCircuit: """Convert a qusetta circuit to a qiskit circuit. Parameters ---------- circuit : list of strings. See ``help(qusetta)`` for more details on how the list of strings should be formatted. Returns ------- qiskit_circuit : qiskit.QuantumCircuit. Examples -------- >>> from qusetta import Qiskit >>> >>> circuit = ["H(0)", "CX(0, 1)", "RX(PI/2)(0)", "SWAP(1, 2)"] >>> qiskit_circuit = Qiskit.from_qusetta(circuit) See the ``Qiskit`` class docstring for info on how the bit ordering is changed. """ n, new_circuit = -1, [] for gate in circuit: g, params, qubits = qs.gate_info(gate) n = max(max(qubits), n) new_circuit.append((g.lower(), params, qubits)) qiskit_circuit = qiskit.QuantumCircuit(n + 1) for g, params, qubits in new_circuit: # ibm is weird and reversed their qubits from everyone else. # So we reverse them here. qubits = tuple(n - q for q in qubits) getattr(qiskit_circuit, g)(*(params + qubits)) return qiskit_circuit @staticmethod def to_qusetta(circuit: qiskit.QuantumCircuit) -> List[str]: """Convert a qiskit circuit to a qusetta circuit. Parameters ---------- circuit : qiskit.QuantumCircuit object. Returns ------- qs_circuit : list of strings. See ``help(qusetta)`` for more details on how the list of strings should be formatted. Examples -------- >>> from qusetta import Qiskit >>> import qiskit >>> >>> circuit = qiskit.QuantumCircuit(3) >>> circuit.h(0) >>> circuit.cx(0, 1) >>> circuit.rx(1/2, 0) >>> circuit.swap(1, 2) >>> >>> print(Qiskit.to_qusetta(circuit)) ["H(2)", "CX(2, 1)", "RX(0.5)(2)", "SWAP(1, 0)"] Notice how the bits are reversed. See the ``Qiskit`` class docstring for more info. """ qs_circuit = [] for gate, qubits, _ in circuit: # _ refers to classical bits g = gate.name.upper() if g == "MEASURE": # ignore measure gates continue elif g == "ID": g = "I" elif g == "U1": g = "RZ" # same up to a phase factor elif g == "U2": # see below for why we reverse the qubits r = circuit.num_qubits - qubits[0].index - 1 qs_circuit.extend([ "RZ(%g - PI/2)(%d)" % (gate.params[1], r), "RX(PI/2)(%d)" % r, "RZ(%g + PI/2)(%d)" % (gate.params[0], r) ]) continue elif g == "U3": # see below for why we reverse the qubits r = circuit.num_qubits - qubits[0].index - 1 qs_circuit.extend([ "RZ(%g - PI/2)(%d)" % (gate.params[2], r), "RX(%g)(%d)" % (gate.params[0], r), "RZ(%g + PI/2)(%d)" % (gate.params[1], r) ]) continue if gate.params: g += "(" + ", ".join(str(x) for x in gate.params) + ")" # ibm is weird and reversed their qubits from everyone else. # So we reverse them here. g += "(" + ", ".join( str(circuit.num_qubits - q.index - 1) for q in qubits ) + ")" qs_circuit.append(g) return qs_circuit
https://github.com/qcware/qusetta
qcware
"""Test the translation functionality. Phases and exact gates may be different in the circuit, but the resulting probability distribution is the same; that's all we care about. """ import cirq import qiskit import quasar import qusetta as qs from math import pi import numpy as np import random class Simulator: cirq_backend = cirq.Simulator(dtype=np.complex128) qiskit_backend = qiskit.BasicAer.get_backend('statevector_simulator') quasar_backend = quasar.QuasarSimulatorBackend() @staticmethod def cirq(circuit: cirq.Circuit) -> np.ndarray: return Simulator.cirq_backend.simulate(circuit).final_state @staticmethod def qiskit(circuit: qiskit.QuantumCircuit) -> np.ndarray: return qiskit.execute( circuit, Simulator.qiskit_backend ).result().get_statevector() @staticmethod def quasar(circuit: quasar.Circuit) -> np.ndarray: return Simulator.quasar_backend.run_statevector(circuit) def assert_equal(c0, c1, simulator0, simulator1=None): simulator1 = simulator1 or simulator0 np.testing.assert_allclose( np.abs(simulator0(c0)) ** 2, np.abs(simulator1(c1)) ** 2 ) # begin test functions that work on arbitrary circuits def cirq_vs_qusetta(cirq_circuit, qusetta_circuit): assert_equal( cirq_circuit, qs.Cirq.from_qusetta(qusetta_circuit), Simulator.cirq ) assert_equal( cirq_circuit, qs.Cirq.from_qusetta(qs.Cirq.to_qusetta(cirq_circuit)), Simulator.cirq ) def qiskit_vs_qusetta(qiskit_circuit, qusetta_circuit): assert_equal( qiskit_circuit, qs.Qiskit.from_qusetta(qusetta_circuit), Simulator.qiskit ) assert_equal( qiskit_circuit, qs.Qiskit.from_qusetta(qs.Qiskit.to_qusetta(qiskit_circuit)), Simulator.qiskit ) def quasar_vs_qusetta(quasar_circuit, qusetta_circuit): assert_equal( quasar_circuit, qs.Quasar.from_qusetta(qusetta_circuit), Simulator.quasar ) assert_equal( quasar_circuit, qs.Quasar.from_qusetta(qs.Quasar.to_qusetta(quasar_circuit)), Simulator.quasar ) def cirq_vs_qiskit(cirq_circuit, qiskit_circuit): assert_equal( cirq_circuit, qiskit_circuit, Simulator.cirq, Simulator.qiskit ) assert_equal( cirq_circuit, qs.Qiskit.to_cirq(qiskit_circuit), Simulator.cirq ) assert_equal( cirq_circuit, qs.Cirq.from_qiskit(qiskit_circuit), Simulator.cirq ) assert_equal( qs.Qiskit.from_cirq(cirq_circuit), qiskit_circuit, Simulator.qiskit ) assert_equal( qs.Cirq.to_qiskit(cirq_circuit), qiskit_circuit, Simulator.qiskit ) assert_equal( qiskit_circuit, qs.Qiskit.from_cirq(qs.Qiskit.to_cirq(qiskit_circuit)), Simulator.qiskit ) assert_equal( cirq_circuit, qs.Cirq.from_qiskit(qs.Cirq.to_qiskit(cirq_circuit)), Simulator.cirq ) def cirq_vs_quasar(cirq_circuit, quasar_circuit): assert_equal( cirq_circuit, quasar_circuit, Simulator.cirq, Simulator.quasar ) assert_equal( cirq_circuit, qs.Quasar.to_cirq(quasar_circuit), Simulator.cirq ) assert_equal( cirq_circuit, qs.Cirq.from_quasar(quasar_circuit), Simulator.cirq ) assert_equal( qs.Quasar.from_cirq(cirq_circuit), quasar_circuit, Simulator.quasar ) assert_equal( qs.Cirq.to_quasar(cirq_circuit), quasar_circuit, Simulator.quasar ) assert_equal( quasar_circuit, qs.Quasar.from_cirq(qs.Quasar.to_cirq(quasar_circuit)), Simulator.quasar ) assert_equal( cirq_circuit, qs.Cirq.from_quasar(qs.Cirq.to_quasar(cirq_circuit)), Simulator.cirq ) def qiskit_vs_quasar(qiskit_circuit, quasar_circuit): assert_equal( qiskit_circuit, quasar_circuit, Simulator.qiskit, Simulator.quasar ) assert_equal( qiskit_circuit, qs.Quasar.to_qiskit(quasar_circuit), Simulator.qiskit ) assert_equal( qiskit_circuit, qs.Qiskit.from_quasar(quasar_circuit), Simulator.qiskit ) assert_equal( qs.Quasar.from_qiskit(qiskit_circuit), quasar_circuit, Simulator.quasar ) assert_equal( qs.Qiskit.to_quasar(qiskit_circuit), quasar_circuit, Simulator.quasar ) assert_equal( quasar_circuit, qs.Quasar.from_qiskit(qs.Quasar.to_qiskit(quasar_circuit)), Simulator.quasar ) assert_equal( qiskit_circuit, qs.Qiskit.from_quasar(qs.Qiskit.to_quasar(qiskit_circuit)), Simulator.qiskit ) # begin explicit tests with explicit circuits def all_tests(qusetta_circuit, cirq_circuit, qiskit_circuit, quasar_circuit): cirq_vs_qusetta(cirq_circuit, qusetta_circuit) qiskit_vs_qusetta(qiskit_circuit, qusetta_circuit) quasar_vs_qusetta(quasar_circuit, qusetta_circuit) cirq_vs_qiskit(cirq_circuit, qiskit_circuit) cirq_vs_quasar(cirq_circuit, quasar_circuit) qiskit_vs_quasar(qiskit_circuit, quasar_circuit) def test_circuit_0(): qusetta_circuit = [ "H(0)", "H(1)", "CX(0, 1)", "CX(1, 0)", "CZ(2, 0)", "I(1)", "SWAP(0, 3)", "RY(PI)(1)", "X(2)", "S(0)", "Z(2)", "Y(3)", "RX(0.4*PI)(0)", "T(2)", "RZ(-0.3*PI)(2)", "CCX(0, 1, 2)" ] cirq_circuit = cirq.Circuit() q = [cirq.LineQubit(i) for i in range(4)] cirq_circuit.append(cirq.H(q[0])) cirq_circuit.append(cirq.H(q[1])) cirq_circuit.append(cirq.CX(q[0], q[1])) cirq_circuit.append(cirq.CX(q[1], q[0])) cirq_circuit.append(cirq.CZ(q[2], q[0])) cirq_circuit.append(cirq.I(q[1])) cirq_circuit.append(cirq.SWAP(q[0], q[3])) cirq_circuit.append(cirq.ry(pi)(q[1])) cirq_circuit.append(cirq.X(q[2])) cirq_circuit.append(cirq.S(q[0])) cirq_circuit.append(cirq.Z(q[2])) cirq_circuit.append(cirq.Y(q[3])) cirq_circuit.append(cirq.rx(.4*pi)(q[0])) cirq_circuit.append(cirq.T(q[2])) cirq_circuit.append(cirq.rz(-.3*pi)(q[2])) cirq_circuit.append(cirq.CCX(q[0], q[1], q[2])) # ibm is weird so we flip all of the qubits here qiskit_circuit = qiskit.QuantumCircuit(4) qiskit_circuit.h(3-0) qiskit_circuit.h(3-1) qiskit_circuit.cx(3-0, 3-1) qiskit_circuit.cx(3-1, 3-0) qiskit_circuit.cz(3-2, 3-0) qiskit_circuit.i(3-1) qiskit_circuit.swap(3-0, 3-3) qiskit_circuit.ry(pi, 3-1) qiskit_circuit.x(3-2) qiskit_circuit.s(3-0) qiskit_circuit.z(3-2) qiskit_circuit.y(3-3) qiskit_circuit.rx(.4*pi, 3-0) qiskit_circuit.t(3-2) qiskit_circuit.rz(-.3*pi, 3-2) qiskit_circuit.ccx(3-0, 3-1, 3-2) quasar_circuit = quasar.Circuit() quasar_circuit.H(0) quasar_circuit.H(1) quasar_circuit.CX(0, 1) quasar_circuit.CX(1, 0) quasar_circuit.CZ(2, 0) quasar_circuit.I(1) quasar_circuit.SWAP(0, 3) quasar_circuit.Ry(1, pi) quasar_circuit.X(2) quasar_circuit.S(0) quasar_circuit.Z(2) quasar_circuit.Y(3) quasar_circuit.Rx(0, .2*pi) quasar_circuit.T(2) quasar_circuit.Rz(2, -.15*pi) quasar_circuit.CCX(0, 1, 2) # tests all_tests(qusetta_circuit, cirq_circuit, qiskit_circuit, quasar_circuit) def test_circuit_1(): # test qiskit's u1, u2, and u3 gates qiskit_circuit = qiskit.QuantumCircuit(4) qiskit_circuit.h(0) qiskit_circuit.h(2) qiskit_circuit.u1(pi/6, 1) qiskit_circuit.u2(1, 2, 0) qiskit_circuit.ccx(1, 0, 3) qiskit_circuit.ccx(0, 1, 2) qiskit_circuit.u3(1, 2, 3, 1) qiskit_circuit.rx(pi/3, 1) qiskit_circuit.u3(1.56, 1.24, 1.69, 2) qiskit_circuit.u2(1.2, 5.1, 1) qiskit_circuit.u1(6.542, 0) qusetta_circuit = qs.Qiskit.to_qusetta(qiskit_circuit) cirq_circuit = qs.Cirq.from_qusetta(qusetta_circuit) quasar_circuit = qs.Quasar.from_qusetta(qusetta_circuit) # tests all_tests(qusetta_circuit, cirq_circuit, qiskit_circuit, quasar_circuit) def test_circuit_2(): # test that we ignore measurement gates qusetta_circuit = ["H(0)"] q = cirq.LineQubit(0) cirq_circuit = cirq.Circuit(cirq.H(q), cirq.measure(q)) cirq_circuit = qs.Cirq.from_qusetta(qs.Cirq.to_qusetta(cirq_circuit)) qiskit_circuit = qiskit.QuantumCircuit(1, 1) qiskit_circuit.h(0) qiskit_circuit.measure(0, 0) qiskit_circuit = qs.Qiskit.from_qusetta( qs.Qiskit.to_qusetta(qiskit_circuit) ) quasar_circuit = quasar.Circuit() quasar_circuit.H(0) quasar_circuit = qs.Quasar.from_qusetta( qs.Quasar.to_qusetta(quasar_circuit) ) # tests all_tests(qusetta_circuit, cirq_circuit, qiskit_circuit, quasar_circuit)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are on 3.10 > python < 3.12 %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U # Import all in one cell import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import RealAmplitudes from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.visualization import plot_gate_map, plot_circuit_layout, plot_distribution from qiskit.circuit import ParameterVector from qiskit_aer import AerSimulator from qiskit_ibm_runtime import ( QiskitRuntimeService, EstimatorV2 as Estimator, SamplerV2 as Sampler, EstimatorOptions ) import warnings warnings.filterwarnings('ignore') ### Save API Token, if needed %set_env QXToken=deleteThisAndPasteYourTokenHere # Set Grade only mode %set_env QC_GRADE_ONLY=true # Make sure there is no space between the equal sign # and the beginning of your token # qc-grader should be 0.18.13 (or higher) import qc_grader qc_grader.__version__ from qc_grader.challenges.iqc_2024 import grade_lab_bonus_ex1, grade_lab_bonus_ex2, grade_lab_bonus_ex3 def old_amplitude_embedding(num_qubits, bird_index): """Create amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ def generate_GHZ(qc): qc.h(0) for i, j in zip(range(num_qubits-1), range(1,num_qubits)): qc.cx(i, j) ### Write your code below here ### def generate_binary(qc, number): position=0 bit=1 while number >= bit: if number & bit: qc.x(position) bit <<= 1 position=position+1 qc = QuantumCircuit(num_qubits) if bird_index < 5: generate_GHZ(qc) generate_binary(qc, bird_index) ### Don't change any code past this line ### return qc num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_osaka") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 # You can check different birds by changing the index qc = old_amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) source_list= [1 , 1 , 2 , 2 , 3 , 3 , 4 , 5 , 6, 7, 8, 9, 10, 8, 9, 10, 11, 12, 13, 14, 11, 15, 16, 17, 18, 19, 20, 21, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 38, 39, 40, 31, 33, 34, 35, 36, 37, 23, 25, 26] target_list=[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52] layer_list=[1, 2, 2, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] premade_layout= [63, 64, 62, 65, 54, 61, 72, 66, 45, 60, 81, 73, 46, 53, 67, 44, 59, 80, 85, 47, 41, 82, 68, 43, 58, 79, 86, 35, 40, 84, 48, 42, 83, 69, 34, 71, 91, 87, 28, 39, 93, 29, 33, 49, 92, 70, 24, 77, 98, 55, 57, 78] def new_amplitude_embedding(num_qubits, bird_index): """Create efficient amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ ### Write your code below here ### def generate_GHZ(qubits): qc = QuantumCircuit(qubits) qc.h(0) for i in range(qubits-1): qc.cx(source_list[i]-1, target_list[i]-1) return qc def generate_shifted_encoding(qubits, number, shift=0): qc = QuantumCircuit(qubits) position=shift bit=1 while number >= bit: if number & bit: qc.x(position) bit <<= 1 position=position+1 return qc def generate_normal_bird(qubits, number): return generate_shifted_encoding(qubits, number, 0) def generate_quantum_bird(qubits, number): return (generate_GHZ(qubits)).compose(generate_shifted_encoding(qubits, number, 0)) if bird_index < 5: qc = generate_quantum_bird(num_qubits,bird_index) else: qc = generate_normal_bird(num_qubits,bird_index) ### Don't change any code past this line ### return qc num_qubits = 50 index = 0 # Change to different values for testing qc = new_amplitude_embedding(num_qubits, index) qc.measure_all() # Define the backend and the pass manager aer_sim = AerSimulator(method='matrix_product_state') pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(qc) # Define the sampler with the number of shots sampler = Sampler(backend=aer_sim) result = sampler.run([isa_circuit]).result() samp_dist = result[0].data.meas.get_counts() plot_distribution(samp_dist, figsize=(10, 3)) num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_kyoto") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 #You can check different birds by changing the index qc = new_amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab_bonus_ex1(new_amplitude_embedding(50,3)) # Expected answer type: QuantumCircuit def generate_old_ansatz(qubits): qc = RealAmplitudes(qubits, reps=1, entanglement='pairwise') return qc num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_kyoto") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 # You can check different birds by changing the index qc = new_amplitude_embedding(num_qubits, index_bird) ansatz = generate_old_ansatz(num_qubits) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) transpiled_qc = pm.run(qc.compose(ansatz)) print('Depth new mapping + old ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) # transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) def generate_ansatz(num_qubits): """Generate a `RealAmplitudes` ansatz where all qubits are entangled with each other Parameters: num_qubits (int): Number of qubits for the ansatz Returns: qc (QuantumCircuit): Quantum circuit with the generated ansatz """ ### Write your code below here ### qc = QuantumCircuit(num_qubits) params=ParameterVector("x",num_qubits*2) for i in range(num_qubits): qc.ry(params[i],i) for n in range(3): for i in range(num_qubits-1): if layer_list[i] == n+1: qc.cx(source_list[i]-1, target_list[i]-1) for i in range(num_qubits): qc.ry(params[i+num_qubits],i) ### Don't change any code past this line ### return qc index_bird = 0 # You can check different birds by changing the index new_mapping_qc = new_amplitude_embedding(num_qubits, index_bird) ansatz = generate_ansatz(num_qubits) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) transpiled_qc = pm.run(new_mapping_qc.compose(ansatz)) print('Depth new mapping + new ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) # transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab_bonus_ex2(transpiled_qc) # Expected answer type: QuantumCircuit # Generate this to match your ansatz source_list= [1 , 1 , 2 , 2 , 3 , 3 , 4 , 5 , 6, 7, 8, 9, 10, 8, 9, 10, 11, 12, 13, 14, 11, 15, 16, 17, 18, 19, 20, 21, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 38, 39, 40, 31, 33, 34, 35, 36, 37, 23, 25, 26] def generalize_optimal_params(num_qubits, ansatz, source_list): """Generate a `list of optimal parameters for N qubits Parameters: num_qubits (int): Number of qubits for the ansatz ansatz (QuantumCircuit): Ansatz for our VQC source_list (list): List of qubits used as source to entangle other qubits Returns: opt_params (list): List of optimal parameters generated for N qubits """ opt_params = np.zeros(ansatz.num_parameters) for i in range(ansatz.num_parameters//2): if i in source_list: opt_params[i] = np.pi return opt_params def test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend): """Tests the shallow VQC on a QPU Parameters: num_qubits (int): Number of qubits for the ansatz list_labels (list): List of labels obs: (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Options for Estimator primitive backend (Backend): Real backend from IBM Quantum to run the job Returns: job_id (str): Job ID for Quantum job """ ### Write your code below here ### results_test = [] estimator = Estimator(backend=backend, options=options) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) pubs = [] for bird, label in enumerate(list_labels): new_mapping_qc = new_amplitude_embedding(num_qubits, bird) #ansatz = generate_old_ansatz(num_qubits) ansatz = generate_ansatz(num_qubits) classifier = new_mapping_qc.compose(ansatz) transpiled_classifier = pm.run(classifier) transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) pub = (transpiled_classifier, transpiled_obs, opt_params) pubs.append(pub) job = estimator.run(pubs) job_id = job.job_id() print(f"Job ID: {job_id}") print(f"Status: {job.status()}") ### Don't change any code past this line ### return job_id def retrieve_job(job_id): """Retrieve test results from job id Parameters: job_id (str): Job ID Returns: results_test (list): List of test results errors_test (list): List of test errors """ job = service.job(job_id) results_test = [] errors_test = [] for result in job.result(): results_test.append(abs(abs(result.data.evs)-1)) #COST FUNCTION HAS A -1 NOW!!! errors_test.append(abs(result.data.stds)) return results_test, errors_test def test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, backend): """Tests the shallow VQC on a QPU Parameters: num_qubits (int): Number of qubits for the ansatz list_labels (list): List of labels obs: (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Options for Estimator primitive backend (Backend): AerSimulator backend to run the job Returns: results_test (list): List of test results """ results_test = [] ### Write your code below here ### estimator = Estimator(backend=backend) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) results_test = [] for bird, label in enumerate(list_labels): new_mapping_qc = new_amplitude_embedding(num_qubits, bird) #ansatz = generate_old_ansatz(num_qubits) ansatz = generate_ansatz(num_qubits) classifier = new_mapping_qc.compose(ansatz) transpiled_classifier = pm.run(classifier) transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) pub = (transpiled_classifier, transpiled_obs, opt_params) job = estimator.run([pub]) ### Don't change any code past this line ### result = job.result()[0].data.evs results_test.append(abs(abs(result)-1)) # COST FUNCTION NOW HAS A -1!!! return results_test def compute_performance(result_list, list_labels): """Return the performance of the classifier Parameters: result_list (list): List of results list_labels (list): List of labels Returns: performance (float): Performance of the classifier """ ### Write your code below here ### performance = 100 for result, label in zip(result_list, list_labels): performance -= np.abs(abs(result) - label)/len(list_labels)*100 ### Don't change any code past this line ### return performance num_qubits = 50 aer_sim = AerSimulator(method='matrix_product_state') pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(new_mapping_qc) list_labels = np.append(np.ones(5), np.zeros(5)) obs = SparsePauliOp("Z"*num_qubits) opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list) options = EstimatorOptions() results_test_aer_sim = test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, aer_sim) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data MPS') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for resilience 0: {compute_performance(results_test_aer_sim, list_labels)}") ax.plot(results_test_aer_sim, 'o-', color='tab:red', label='MPS Num qubits = ' + str(num_qubits)) ax.plot(list_labels, 'k-', label='Labels') ax.legend() # Submit your answer using following code grade_lab_bonus_ex3(results_test_aer_sim) # Expected variable types: List service = QiskitRuntimeService() backend = service.backend("select_your_device") # RUN JOBS num_qubits = 50 obs = SparsePauliOp("Z"*num_qubits) opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list) for resilience in [0,1]: DD = True options = EstimatorOptions(default_shots = 5_000, optimization_level=0, resilience_level=resilience) options.dynamical_decoupling.enable = DD options.dynamical_decoupling.sequence_type = 'XpXm' # OPTIONAL # options.resilience.zne_mitigation = True # options.resilience.zne.noise_factors = (1, 1.2, 1.5) # options.resilience.zne.extrapolator = ('exponential', 'linear', 'polynomial_degree_2') #order matters job_id = test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend) results_test_0_DD, errors_test_0_DD = retrieve_job('Enter your JobID for resilience level 0') results_test_1_DD, errors_test_1_DD = retrieve_job('Enter your JobID for resilience level 1') fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title(f'Test of a {num_qubits} qubit VQC on {backend.name}') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for no DD + no TREX: {compute_performance(results_test_0_DD, list_labels):.3f}") print(f"Performance for DD + TREX: {compute_performance(results_test_1_DD, list_labels):.3f}") ax.errorbar(range(10), results_test_0_DD, fmt='--o', yerr=errors_test_0_DD, color='tab:orange', label=f'{backend.name} RL=0 shots={options.default_shots} DD={options.dynamical_decoupling.enable}') ax.errorbar(range(10), results_test_1_DD, fmt='--o', yerr=errors_test_1_DD, color='tab:blue', label=f'{backend.name} RL=1 shots={options.default_shots} DD={options.dynamical_decoupling.enable}') ax.plot(list_labels, 'k-', label='Labels') ax.legend()
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit import QuantumCircuit # Create a new circuit with a single qubit qc = QuantumCircuit(1) # Add a Not gate to qubit 0 qc.x(0) # Return a drawing of the circuit using MatPlotLib ("mpl"). This is the # last line of the cell, so the drawing appears in the cell output. qc.draw("mpl") ### CHECK QISKIT VERSION import qiskit qiskit.__version__ ### CHECK OTHER DEPENDENCIES %pip show pylatexenc matplotlib qc_grader #qc-grader should be 0.18.8 (or higher) ### Imports from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import EstimatorV2 as Estimator from qiskit_aer import AerSimulator import matplotlib.pyplot as plt from qc_grader.challenges.iqc_2024 import grade_lab0_ex1 # Create a new circuit with two qubits qc = QuantumCircuit(2) # Add a Hadamard gate to qubit 0 qc.h(0) # Perform a CNOT gate on qubit 1, controlled by qubit 0 qc.cx(0, 1) # Return a drawing of the circuit using MatPlotLib ("mpl"). This is the # last line of the cell, so the drawing appears in the cell output. qc.draw("mpl") # The ZZ applies a Z operator on qubit 0, and a Z operator on qubit 1 ZZ = SparsePauliOp('ZZ') # The ZI applies a Z operator on qubit 0, and an Identity operator on qubit 1 ZI = SparsePauliOp('ZI') # The IX applies an Identity operator on qubit 0, and an X operator on qubit 1 IX = SparsePauliOp('IX') ### Write your code below here ### IZ = SparsePauliOp('IZ') XX = SparsePauliOp('XX') XI = SparsePauliOp('XI') ### Follow the same naming convention we used above ## Don't change any code past this line, but remember to run the cell. observables = [IZ, IX, ZI, XI, ZZ, XX] # Submit your answer using following code grade_lab0_ex1(observables) # Set up the Estimator estimator = Estimator(backend=AerSimulator()) # Submit the circuit to Estimator pub = (qc, observables) job = estimator.run(pubs=[pub]) # Collect the data data = ['IZ', 'IX', 'ZI', 'XI', 'ZZ', 'XX'] values = job.result()[0].data.evs # Set up our graph container = plt.plot(data, values, '-o') # Label each axis plt.xlabel('Observables') plt.ylabel('Values') # Draw the final graph plt.show() container = plt.bar(data, values, width=0.8) plt.xlabel('Observables') plt.ylabel('Values') plt.show()
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit_textbook.problems import dj_problem_oracle def lab1_ex1(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) return qc state = Statevector.from_instruction(lab1_ex1()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex1 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex1(lab1_ex1()) def lab1_ex2(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) return qc state = Statevector.from_instruction(lab1_ex2()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex2 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex2(lab1_ex2()) def lab1_ex3(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) qc.h(0) return qc state = Statevector.from_instruction(lab1_ex3()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex3 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex3(lab1_ex3()) def lab1_ex4(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.sdg(0) return qc state = Statevector.from_instruction(lab1_ex4()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex4 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex4(lab1_ex4()) def lab1_ex5(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.cx(0,1) qc.x(0) return qc qc = lab1_ex5() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex5 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex5(lab1_ex5()) qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0 qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1 backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def lab1_ex6(): # # # FILL YOUR CODE IN HERE # # qc = QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cx(1,2) qc.y(1) return qc qc = lab1_ex6() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex6 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex6(lab1_ex6()) oraclenr = 4 # determines the oracle (can range from 1 to 5) oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles oracle.name = "DJ-Oracle" def dj_classical(n, input_str): # build a quantum circuit with n qubits and 1 classical readout bit dj_circuit = QuantumCircuit(n+1,1) # Prepare the initial state corresponding to your input bit string for i in range(n): if input_str[i] == '1': dj_circuit.x(i) # append oracle dj_circuit.append(oracle, range(n+1)) # measure the fourth qubit dj_circuit.measure(n,0) return dj_circuit n = 4 # number of qubits input_str = '1111' dj_circuit = dj_classical(n, input_str) dj_circuit.draw() # draw the circuit input_str = '1111' dj_circuit = dj_classical(n, input_str) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit, qasm_sim) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) def lab1_ex7(): min_nr_inputs = 2 max_nr_inputs = 9 return [min_nr_inputs, max_nr_inputs] from qc_grader import grade_lab1_ex7 # Note that the grading function is expecting a list of two integers grade_lab1_ex7(lab1_ex7()) n=4 def psi_0(n): qc = QuantumCircuit(n+1,n) # Build the state (|00000> - |10000>)/sqrt(2) # # # FILL YOUR CODE IN HERE # # qc.x(4) qc.h(4) return qc dj_circuit = psi_0(n) dj_circuit.draw() def psi_1(n): # obtain the |psi_0> = |00001> state qc = psi_0(n) # create the superposition state |psi_1> # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # # qc.barrier() return qc dj_circuit = psi_1(n) dj_circuit.draw() def psi_2(oracle,n): # circuit to obtain psi_1 qc = psi_1(n) # append the oracle qc.append(oracle, range(n+1)) return qc dj_circuit = psi_2(oracle, n) dj_circuit.draw() def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25]) qc = psi_2(oracle, n) # apply n-fold hadamard gate # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # add the measurement by connecting qubits to classical bits # # qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) # # return qc dj_circuit = lab1_ex8(oracle, n) dj_circuit.draw() from qc_grader import grade_lab1_ex8 # Note that the grading function is expecting a quantum circuit with measurements grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n)) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
import networkx as nx import numpy as np import plotly.graph_objects as go import matplotlib as mpl import pandas as pd from IPython.display import clear_output from plotly.subplots import make_subplots from matplotlib import pyplot as plt from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_state_city from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM from time import time from copy import copy from typing import List from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs mpl.rcParams['figure.dpi'] = 300 from qiskit.circuit import Parameter, ParameterVector #Parameters are initialized with a simple string identifier parameter_0 = Parameter('θ[0]') parameter_1 = Parameter('θ[1]') circuit = QuantumCircuit(1) #We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates circuit.ry(theta = parameter_0, qubit = 0) circuit.rx(theta = parameter_1, qubit = 0) circuit.draw('mpl') parameter = Parameter('θ') circuit = QuantumCircuit(1) circuit.ry(theta = parameter, qubit = 0) circuit.rx(theta = parameter, qubit = 0) circuit.draw('mpl') #Set the number of layers and qubits n=3 num_layers = 2 #ParameterVectors are initialized with a string identifier and an integer specifying the vector length parameters = ParameterVector('θ', n*(num_layers+1)) circuit = QuantumCircuit(n, n) for layer in range(num_layers): #Appending the parameterized Ry gates using parameters from the vector constructed above for i in range(n): circuit.ry(parameters[n*layer+i], i) circuit.barrier() #Appending the entangling CNOT gates for i in range(n): for j in range(i): circuit.cx(j,i) circuit.barrier() #Appending one additional layer of parameterized Ry gates for i in range(n): circuit.ry(parameters[n*num_layers+i], i) circuit.barrier() circuit.draw('mpl') print(circuit.parameters) #Create parameter dictionary with random values to bind param_dict = {parameter: np.random.random() for parameter in parameters} print(param_dict) #Assign parameters using the assign_parameters method bound_circuit = circuit.assign_parameters(parameters = param_dict) bound_circuit.draw('mpl') new_parameters = ParameterVector('Ψ',9) new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)]) new_circuit.draw('mpl') #Run the circuit with assigned parameters on Aer's statevector simulator simulator = Aer.get_backend('statevector_simulator') result = simulator.run(bound_circuit).result() statevector = result.get_statevector(bound_circuit) plot_state_city(statevector) #The following line produces an error when run because 'circuit' still contains non-assigned parameters #result = simulator.run(circuit).result() for key in graphs.keys(): print(key) graph = nx.Graph() #Add nodes and edges graph.add_nodes_from(np.arange(0,6,1)) edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)] graph.add_weighted_edges_from(edges) graphs['custom'] = graph #Display widget display_maxcut_widget(graphs['custom']) def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float: """ Computes the maxcut cost function value for a given graph and cut represented by some bitstring Args: graph: The graph to compute cut values for bitstring: A list of integer values '0' or '1' specifying a cut of the graph Returns: The value of the cut """ #Get the weight matrix of the graph weight_matrix = nx.adjacency_matrix(graph).toarray() size = weight_matrix.shape[0] value = 0. #INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE for i in range(size): for j in range(size): value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j]) return value def plot_maxcut_histogram(graph: nx.Graph) -> None: """ Plots a bar diagram with the values for all possible cuts of a given graph. Args: graph: The graph to compute cut values for """ num_vars = graph.number_of_nodes() #Create list of bitstrings and corresponding cut values bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)] values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings] #Sort both lists by largest cut value values, bitstrings = zip(*sorted(zip(values, bitstrings))) #Plot bar diagram bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value'))) fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600)) fig.show() plot_maxcut_histogram(graph = graphs['custom']) from qc_grader import grade_lab2_ex1 bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE # Note that the grading function is expecting a list of integers '0' and '1' grade_lab2_ex1(bitstring) from qiskit_optimization import QuadraticProgram quadratic_program = QuadraticProgram('sample_problem') print(quadratic_program.export_as_lp_string()) quadratic_program.binary_var(name = 'x_0') quadratic_program.integer_var(name = 'x_1') quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8) quadratic = [[0,1,2],[3,4,5],[0,1,2]] linear = [10,20,30] quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5) print(quadratic_program.export_as_lp_string()) def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram: """Constructs a quadratic program from a given graph for a MaxCut problem instance. Args: graph: Underlying graph of the problem. Returns: QuadraticProgram """ #Get weight matrix of graph weight_matrix = nx.adjacency_matrix(graph) shape = weight_matrix.shape size = shape[0] #Build qubo matrix Q from weight matrix W qubo_matrix = np.zeros((size, size)) qubo_vector = np.zeros(size) for i in range(size): for j in range(size): qubo_matrix[i, j] -= weight_matrix[i, j] for i in range(size): for j in range(size): qubo_vector[i] += weight_matrix[i,j] #INSERT YOUR CODE HERE quadratic_program=QuadraticProgram('sample_problem') for i in range(size): quadratic_program.binary_var(name='x_{}'.format(i)) quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector) return quadratic_program quadratic_program = quadratic_program_from_graph(graphs['custom']) print(quadratic_program.export_as_lp_string()) from qc_grader import grade_lab2_ex2 # Note that the grading function is expecting a quadratic program grade_lab2_ex2(quadratic_program) def qaoa_circuit(qubo: QuadraticProgram, p: int = 1): """ Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers. Args: qubo: The quadratic program instance p: The number of layers in the QAOA circuit Returns: The parameterized QAOA circuit """ size = len(qubo.variables) qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True) qubo_linearity = qubo.objective.linear.to_array() #Prepare the quantum and classical registers qaoa_circuit = QuantumCircuit(size,size) #Apply the initial layer of Hadamard gates to all qubits qaoa_circuit.h(range(size)) #Create the parameters to be used in the circuit gammas = ParameterVector('gamma', p) betas = ParameterVector('beta', p) #Outer loop to create each layer for i in range(p): #Apply R_Z rotational gates from cost layer #INSERT YOUR CODE HERE for j in range(size): qubo_matrix_sum_of_col = 0 for k in range(size): qubo_matrix_sum_of_col+= qubo_matrix[j][k] qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j) #Apply R_ZZ rotational gates for entangled qubit rotations from cost layer #INSERT YOUR CODE HERE for j in range(size): for k in range(size): if j!=k: qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k) # Apply single qubit X - rotations with angle 2*beta_i to all qubits #INSERT YOUR CODE HERE for j in range(size): qaoa_circuit.rx(2*betas[i],j) return qaoa_circuit quadratic_program = quadratic_program_from_graph(graphs['custom']) custom_circuit = qaoa_circuit(qubo = quadratic_program) test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters)) from qc_grader import grade_lab2_ex3 # Note that the grading function is expecting a quantum circuit grade_lab2_ex3(test) from qiskit.algorithms import QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = Aer.get_backend('statevector_simulator') qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1]) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) quadratic_program = quadratic_program_from_graph(graphs['custom']) result = eigen_optimizer.solve(quadratic_program) print(result) def plot_samples(samples): """ Plots a bar diagram for the samples of a quantum algorithm Args: samples """ #Sort samples by probability samples = sorted(samples, key = lambda x: x.probability) #Get list of probabilities, function values and bitstrings probabilities = [sample.probability for sample in samples] values = [sample.fval for sample in samples] bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples] #Plot bar diagram sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value'))) fig = go.Figure( data=sample_plot, layout = dict( xaxis=dict( type = 'category' ) ) ) fig.show() plot_samples(result.samples) graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name]) trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]} offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum() def callback(eval_count, params, mean, std_dev): trajectory['beta_0'].append(params[1]) trajectory['gamma_0'].append(params[0]) trajectory['energy'].append(-mean + offset) optimizers = { 'cobyla': COBYLA(), 'slsqp': SLSQP(), 'adam': ADAM() } qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) result = eigen_optimizer.solve(quadratic_program) fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples) fig.show() graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graphs[graph_name]) #Create callback to record total number of evaluations max_evals = 0 def callback(eval_count, params, mean, std_dev): global max_evals max_evals = eval_count #Create empty lists to track values energies = [] runtimes = [] num_evals=[] #Run QAOA for different values of p for p in range(1,10): print(f'Evaluating for p = {p}...') qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) start = time() result = eigen_optimizer.solve(quadratic_program) runtimes.append(time()-start) num_evals.append(max_evals) #Calculate energy of final state from samples avg_value = 0. for sample in result.samples: avg_value += sample.probability*sample.fval energies.append(avg_value) #Create and display plots energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma')) runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma')) num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma')) fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations']) fig.update_layout(width=1800,height=600, showlegend=False) fig.add_trace(energy_plot, row=1, col=1) fig.add_trace(runtime_plot, row=1, col=2) fig.add_trace(num_evals_plot, row=1, col=3) clear_output() fig.show() def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None): num_shots = 1000 seed = 42 simulator = Aer.get_backend('qasm_simulator') simulator.set_options(seed_simulator = 42) #Generate circuit circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1) circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes())) #Create dictionary with precomputed cut values for all bitstrings cut_values = {} size = graph.number_of_nodes() for i in range(2**size): bitstr = '{:b}'.format(i).rjust(size, '0')[::-1] x = [int(bit) for bit in bitstr] cut_values[bitstr] = maxcut_cost_fn(graph, x) #Perform grid search over all parameters data_points = [] max_energy = None for beta in np.linspace(0,np.pi, 50): for gamma in np.linspace(0, 4*np.pi, 50): bound_circuit = circuit.assign_parameters([beta, gamma]) result = simulator.run(bound_circuit, shots = num_shots).result() statevector = result.get_counts(bound_circuit) energy = 0 measured_cuts = [] for bitstring, count in statevector.items(): measured_cuts = measured_cuts + [cut_values[bitstring]]*count if cvar is None: #Calculate the mean of all cut values energy = sum(measured_cuts)/num_shots else: #raise NotImplementedError() #INSERT YOUR CODE HERE measured_cuts = sorted(measured_cuts, reverse = True) for w in range(int(cvar*num_shots)): energy += measured_cuts[w]/int((cvar*num_shots)) #Update optimal parameters if max_energy is None or energy > max_energy: max_energy = energy optimum = {'beta': beta, 'gamma': gamma, 'energy': energy} #Update data data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy}) #Create and display surface plot from data_points df = pd.DataFrame(data_points) df = df.pivot(index='beta', columns='gamma', values='energy') matrix = df.to_numpy() beta_values = df.index.tolist() gamma_values = df.columns.tolist() surface_plot = go.Surface( x=gamma_values, y=beta_values, z=matrix, coloraxis = 'coloraxis' ) fig = go.Figure(data = surface_plot) fig.show() #Return optimum return optimum graph = graphs['custom'] optimal_parameters = plot_qaoa_energy_landscape(graph = graph) print('Optimal parameters:') print(optimal_parameters) optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2) print(optimal_parameters) from qc_grader import grade_lab2_ex4 # Note that the grading function is expecting a python dictionary # with the entries 'beta', 'gamma' and 'energy' grade_lab2_ex4(optimal_parameters)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are using python 3.10 or 3.11 for compatibility of the required packages %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-transpiler-service %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U ### Save API Token, if needed %set_env QXToken=deleteThisAndPasteYourTokenHere # Set Grade only mode %set_env QC_GRADE_ONLY=true # Make sure there is no space between the equal sign # and the beginning of your token # qc-grader should be 0.18.10 (or higher) import qc_grader qc_grader.__version__ # Imports import numpy as np import matplotlib.pyplot as plt from qiskit.circuit.library import EfficientSU2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import QiskitRuntimeService from qiskit_transpiler_service.transpiler_service import TranspilerService # Import for grader from qc_grader.challenges.iqc_2024 import grade_lab3_ait_ex1, grade_lab3_ait_ex2 NUM_QUBITS = 61 circuit = EfficientSU2(NUM_QUBITS, entanglement="circular", reps=1).decompose() print(f"Original circuit -> Depth: {circuit.depth()}, CNOTs: {circuit.num_nonlocal_gates()}") circuit.draw(fold=-1, output="mpl", style="iqp", scale=0.2) transpiler_ai_false = TranspilerService( backend_name="ibm_brisbane", ai=False, optimization_level=3 ) # Submit your answer using following code grade_lab3_ait_ex1(transpiler_ai_false) # Expected result type: TranspilerService circuit_ai_false = transpiler_ai_false.run(circuit) print(f"Transpiled without AI -> Depth: {circuit_ai_false.depth()}, CNOTs: {circuit_ai_false.num_nonlocal_gates()}") circuit_ai_false.draw(fold=-1, output="mpl", scale=0.2) transpiler_ai_true = TranspilerService( backend_name="ibm_brisbane", ai=True, optimization_level=3 ) # Submit your answer using following code grade_lab3_ait_ex2(transpiler_ai_true) # Expected result type: TranspilerService circuit_ai_true = transpiler_ai_true.run(circuit) print(f"Transpiled with AI -> Depth: {circuit_ai_true.depth()}, CNOTs: {circuit_ai_true.num_nonlocal_gates()}") circuit_ai_true.draw(fold=-1, output="mpl", scale=0.2) # Transpiling locally using Qiskit SDK service = QiskitRuntimeService() backend = service.backend("ibm_sherbrooke") pm = generate_preset_pass_manager(backend=backend, optimization_level=3) # Run and compile results num_qubits = [11, 21, 41, 61, 81] num_cnots_local = [] num_cnots_with_ai = [] num_cnots_without_ai = [] for nq in num_qubits: circuit = EfficientSU2(nq, entanglement="circular", reps=1).decompose() # Using the Transpiler locally on Qiskit circuit_local = pm.run(circuit) # Using the transpiler service without AI circuit_without_ai = transpiler_ai_false.run(circuit) # Using the transpiler service with AI circuit_with_ai = transpiler_ai_true.run(circuit) num_cnots_local.append(circuit_local.num_nonlocal_gates()) num_cnots_without_ai.append(circuit_without_ai.num_nonlocal_gates()) num_cnots_with_ai.append(circuit_with_ai.num_nonlocal_gates()) plt.plot(num_qubits, num_cnots_with_ai, '.-') plt.plot(num_qubits, num_cnots_without_ai, '.-') plt.plot(num_qubits, num_cnots_local, '--') plt.xlabel("Number of qubits") plt.ylabel("CNOT count") plt.legend(["Qiskit Transpiler Service with AI", "Qiskit Transpiler Service without AI", "Qiskit SDK"])
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are using python 3.10 or 3.11 for compatibility of the required packages %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install qiskit-transpiler-service %pip install graphviz %pip install circuit-knitting-toolbox %pip install qiskit-serverless -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U ### Save API Token, if needed %set_env QXToken=c5a303670922a83ac5699dc2fea334193919a9e2fe6943debde1ac52815df5e39c6a137e05136088f3a7715e8d6dbd10097baf193df1fa22206a85931166946f # Make sure there is no space between the equal sign # and the beginning of your token # qc-grader should be 0.18.11 (or higher) import qc_grader qc_grader.__version__ # Imports import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.visualization import plot_gate_map from qiskit.quantum_info import SparsePauliOp from qiskit_aer import AerSimulator from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2 as Sampler from circuit_knitting.cutting import generate_cutting_experiments, cut_gates # Setup the grader from qc_grader.challenges.iqc_2024 import grade_lab3_ckt_ex1, grade_lab3_ckt_ex2 # create a bell pair bell_state = QuantumCircuit(2) bell_state.h(0) bell_state.cx(0,1) bell_state.draw("mpl") ## If this is your first time accessing the backend ## remove # and fill your API key, and run the code #service = QiskitRuntimeService( # channel='ibm_quantum', # instance='ibm-q/open/main', # token='<IBM Quantum API key>' #) service = QiskitRuntimeService(channel="ibm_quantum") # Specify a system to use for transpilation, DO NOT change backend = service.backend("ibm_kyoto") layout=[122, 126] qubit_color = [] for i in range(127): if i in layout: qubit_color.append("#ff0066") else: qubit_color.append("#6600cc") plot_gate_map(backend, qubit_color=qubit_color, qubit_size=60, font_size=25, figsize=(8,8)) # transpile the circuit pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qc = pm.run(bell_state) # original circuit depth isa_qc_depth = isa_qc.depth() print(f"Transpiled circuit depth: ", isa_qc_depth) isa_qc.draw("mpl", scale=0.6, idle_wires=False, fold=False) # Find the indices of the distant gates cut_indices = [ i for i, instruction in enumerate(bell_state.data) if {bell_state.find_bit(q)[0] for q in instruction.qubits} == {0, 1} ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit, bases = cut_gates(bell_state, cut_indices) qpd_circuit.draw("mpl", scale=0.6) observable = SparsePauliOp(["ZI"]) # Generate the sub-experiments and sampling coefficients sub_experiments, coefficients = generate_cutting_experiments( circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf ) # Transpile the circuit pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qpd_circuit = pm.run(sub_experiments[5]) # depth using circuit cutting isa_qpd_depth = isa_qpd_circuit.depth() print(f"Original circuit depth after transpile: ", isa_qc_depth) print(f"QPD sub-experiment depth after transpile: ", isa_qpd_depth) print(f"Number of sub-experiments:", len(sub_experiments)) isa_qpd_circuit.draw("mpl", scale=0.6, idle_wires=False, fold=False) x = np.array([c.depth() for c in pm.run(sub_experiments)]) print(x) toffoli_layout = [122, 124, 126] toffoli = QuantumCircuit(3) toffoli.ccx(0, 1, 2) toffoli.draw("mpl") layout=[122,124, 126] qubit_color = [] for i in range(127): if i in layout: qubit_color.append("#ff0066") else: qubit_color.append("#6600cc") plot_gate_map(backend, qubit_color=qubit_color, qubit_size=60, font_size=25, figsize=(8,8)) # To know the original circuit depth ### Write your code below here ### # Transpile the circuit pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qc = pm.run(toffoli) # Calculate original circuit depth isa_toffoli_depth = isa_qc.depth() ### Don't change any code past this line ### print(f"Transpiled circuit depth: ", isa_toffoli_depth) isa_qc.draw("mpl", scale=0.6, idle_wires=False, fold=False) # To know the depth using circuit cutting # Decompose the toffoli circuit toffoli_ = toffoli.decompose() ### Write your code below here ### # Find the indices of the distant gates gates_connecting_to_cut = {0,2} # Hint: Expected type: set {int, int}. Docs: https://docs.python.org/3/tutorial/datastructures.html#sets cut_indices = [ i for i, instruction in enumerate(toffoli_.data) if {toffoli_.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit, bases = cut_gates(toffoli_, cut_indices) ### Don't change any code past this line ### qpd_circuit.draw("mpl", scale=0.6) # set the observables observable = SparsePauliOp(["ZZZ"]) ### Write your code below here ### # Generate the sub-experiments and sampling coefficients sub_experiments, coefficients = generate_cutting_experiments( circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf ) # Transpile the circuit # Note: Use optimization_level=1 and seed_transpiler=0 pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qpd_circuit = pm.run(sub_experiments[5]) # Depth using circuit cutting isa_qpd_toffoli_depth = isa_qpd_circuit.depth() ### Don't change any code past this line ### print(f"Transpiled circuit depth: ", isa_toffoli_depth) print(f"QPD sub-experiment depth after transpile: ", isa_qpd_toffoli_depth) print(f"Number of sub-experiments:", len(sub_experiments)) isa_qpd_circuit.draw("mpl", scale=0.6, idle_wires=False, fold=False) ### Write your code below here ### # mean of the depth of all sub-experiments depth_list = [c.depth() for c in pm.run(sub_experiments)] isa_qpd_toffoli_depth_mean = np.mean(depth_list) ### Don't change any code past this line ### print(isa_qpd_toffoli_depth_mean) # Submit your answer using following code grade_lab3_ckt_ex1(gates_connecting_to_cut, isa_toffoli_depth, depth_list) # Expected result type: set, int, numpy.ndarray ### Write your code below here ### # Find the indices of the distant gates gates_connecting_to_cut_1 = {1,2}# Hint: Expected type: set {int, int} gates_connecting_to_cut_2 = {0,2}# Hint: Expected type: set {int, int} cut_indices = [ i for i, instruction in enumerate(toffoli_.data) if {toffoli_.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut_1 or {toffoli_.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut_2 ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit_2, bases = cut_gates(toffoli_, cut_indices) ### Don't change any code past this line ### qpd_circuit_2.draw("mpl", scale=0.6) # set the observables observable = SparsePauliOp(["ZZZ"]) ### Write your code below here ### # Generate the sub-experiments and sampling coefficients sub_experiments_2, coefficients = generate_cutting_experiments( circuits=qpd_circuit_2, observables=observable.paulis, num_samples=np.inf ) # Transpile the circuit # Note: Use optimization_level=1 and seed_transpiler=0 pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qpd_circuit_2 = pm.run(sub_experiments_2[5]) # Depth using circuit cutting isa_qpd_toffoli_depth_2 = pm.run(sub_experiments_2[5]).depth() ### Don't change any code past this line ### print(f"QPD sub-experiment depth after transpile: ", isa_qpd_toffoli_depth_2) print(f"Number of sub-experiments:", len(sub_experiments_2)) isa_qpd_circuit_2.draw("mpl", scale=0.6, idle_wires=False, fold=False) # Submit your answer using following code grade_lab3_ckt_ex2(gates_connecting_to_cut_1, gates_connecting_to_cut_2, sub_experiments_2) # Expected result type: set, set, list[QuantumCircuit] ### Write your code below here ### # mean of the depth of all sub-experiments depth_list_2 = [c.depth() for c in pm.run(sub_experiments_2)] isa_qpd_toffoli_depth_2_mean = np.mean(depth_list_2) ### Don't change any code past this line ### print(isa_qpd_toffoli_depth_2_mean) # Number of sub-experiments num_sub_experiments_1_cut = len(sub_experiments) num_sub_experiments_2_cut = len(sub_experiments_2) # Data for plotting categories = ['Before Cutting', 'After 1 Cut', 'After 2 Cuts'] depth_values = [isa_toffoli_depth, isa_qpd_toffoli_depth_mean, isa_qpd_toffoli_depth_2_mean] num_sub_experiments = [1, num_sub_experiments_1_cut, num_sub_experiments_2_cut] # Create figure and axis fig, ax1 = plt.subplots() # Plot depth values color = 'tab:blue' ax1.set_xlabel('Number of Cuts') ax1.set_ylabel('Circuit Depth', color=color) bars = ax1.bar(categories, depth_values, color=color, alpha=0.6) ax1.tick_params(axis='y', labelcolor=color) # Add value labels on bars for bar in bars: yval = bar.get_height() ax1.text(bar.get_x() + bar.get_width() / 2, yval + 1, round(yval, 2), ha='center', color=color, fontsize=10) # Create a second y-axis to plot the number of subexperiments ax2 = ax1.twinx() color = 'tab:green' ax2.set_ylabel('Number of Sub-experiments', color=color) ax2.plot(categories, num_sub_experiments, color=color, marker='o') ax2.tick_params(axis='y', labelcolor=color) # Add value labels on points for i, num in enumerate(num_sub_experiments): ax2.text(i, num + 0.1, num, ha='center', color=color, fontsize=10) # Add titles and labels plt.title('Circuit Knitting Toolbox Results') fig.tight_layout() # Adjust layout to make room for both y-axes # Show plot plt.show()
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# please create a 3 qubit GHZ circuit # please create a 2 qubit ch gate with only cx and ry gate # Enter your prompt here - Delete this line
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are on 3.10 > python < 3.12 %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U ### Save API Token, if needed %set_env QXToken=deleteThisAndPasteYourTokenHere # Set Grade only mode %set_env QC_GRADE_ONLY=true # Make sure there is no space between the equal sign # and the beginning of your token # qc-grader should be 0.18.12 (or higher) import qc_grader qc_grader.__version__ # Import all in one cell import numpy as np import matplotlib.pyplot as plt from timeit import default_timer as timer import warnings from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import TwoLocal, EfficientSU2 from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options from qiskit_serverless import QiskitFunction, save_result, get_arguments, save_result, distribute_task, distribute_qiskit_function, IBMServerlessClient, QiskitFunction from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_transpiler_service.transpiler_service import TranspilerService from qiskit_aer import AerSimulator # Import for grader from qc_grader.challenges.iqc_2024 import grade_lab3_qs_ex1, grade_lab3_qs_ex2 # If needed setup your QiskitRuntimeService # QiskitRuntimeService.save_account( # channel="ibm_quantum", # token="Enter your IBM Quantum Token", # set_as_default=True, # # Use `overwrite=True` if you're updating your token. # overwrite=True, # ) service = QiskitRuntimeService(channel="ibm_quantum") # Specify a system to use for transpilation real_backend = service.backend("ibm_brisbane") # Qiskit Pattern Step 1: Map quantum circuits and operators (Define Ansatz and operators) num_qubits = 3 rotation_blocks = ['ry','rz'] entanglement_blocks = 'cz' entanglement = 'full' # Define Ansatz ansatz = TwoLocal(num_qubits, rotation_blocks, entanglement_blocks, entanglement, reps=1, insert_barriers=True) # Define parameters num_params = ansatz.num_parameters # Qiskit Pattern Step 2: Optimize the circuit for quantum execution optimization_level = 2 pm = generate_preset_pass_manager(backend=real_backend, optimization_level=optimization_level) isa_circuit = pm.run(ansatz) # Define Hamiltonian for VQE pauli_op = SparsePauliOp(['ZII', 'IZI', 'IIZ']) hamiltonian_isa = pauli_op.apply_layout(layout=isa_circuit.layout) # Setup Qiskit Serverless Client and Qiskit Runtime client client = IBMServerlessClient("YOUR_IBM_QUANTUM_TOKEN") # Add in your IBM Quantum Token to QiskitServerless Client # For the challenge, we will be using QiskitRuntime Local testing mode. Change to True only if you wish to use real backend. USE_RUNTIME_SERVICE = False if USE_RUNTIME_SERVICE: service = QiskitRuntimeService( channel='ibm_quantum', verify=False ) else: service = None # Define the Qiskit Function if USE_RUNTIME_SERVICE: function = QiskitFunction(title="vqe", entrypoint="vqe.py", working_dir="./vqe") else: function = QiskitFunction(title="vqe", entrypoint="vqe.py", working_dir="./vqe", dependencies=["qiskit_aer"]) # Upload the Qiskit Function using IBMServerlessClient client.upload(function) # Define input_arguments input_arguments = { "ansatz": isa_circuit, # Replace with your transpiled ansatz "operator": hamiltonian_isa, # Replace with the hamiltonian operator "method": "COBYLA", # Using COBYLA method for the optimizer "service": service, # Add your code here } # Qiskit Pattern Step 3: Run the payload on backend job = client.run("vqe", arguments=input_arguments) # Pass the arguments dict here) # Submit your answer using following code grade_lab3_qs_ex1(function, input_arguments, job) # Expected result type: QiskitFunction, dict, Job # Return jobid job # Check job completion status job.status() # Monitor log logs = job.logs() for log in logs.splitlines(): print(log) # Return result from QiskitFunction job job.result() # Qiskit Pattern Step 4: Postprocess and analyze the Estimator V2 results result = job.result() fig, ax = plt.subplots() plt.plot(range(result["iters"]), result["cost_history"]) plt.xlabel("Energy") plt.ylabel("Cost") plt.draw() # Setup 3 circuits with Efficient SU2 num_qubits = [41, 51, 61] circuits = [EfficientSU2(nq, su2_gates=["rz","ry"], entanglement="circular", reps=1).decompose() for nq in num_qubits] # Setup Qiskit Runtime Service backend # QiskitRuntimeService.save_account( # channel="ibm_quantum", # token="YOUR_IBM_QUANTUM_TOKEN", # set_as_default=True, # # Use 'overwrite=True' if you're updating your token. # overwrite=True, # ) service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend("ibm_brisbane") # Define Configs optimization_levels = [1, 2, 3] pass_managers = [{'pass_manager': generate_preset_pass_manager(optimization_level=level, backend=backend), 'optimization_level': level} for level in optimization_levels] transpiler_services = [ {'service': TranspilerService(backend_name=backend.name, ai=False, optimization_level=3), 'ai': False, 'optimization_level': 3}, {'service': TranspilerService(backend_name=backend.name, ai=True, optimization_level=3), 'ai': True, 'optimization_level': 3} ] configs = pass_managers + transpiler_services # Local transpilation setup def transpile_parallel_local(circuit: QuantumCircuit, config): """Transpilation for an abstract circuit into an ISA circuit for a given config.""" transpiled_circuit = config.run(circuit) return transpiled_circuit # Run local transpilation warnings.filterwarnings("ignore") start = timer() # Run transpilations locally for baseline results = [] for circuit in circuits: for config in configs: if 'pass_manager' in config: results.append(transpile_parallel_local(circuit, config['pass_manager'])) else: results.append(transpile_parallel_local(circuit, config['service'])) end = timer() # Record local execution time execution_time_local = end - start print("Execution time locally: ", execution_time_local) # Authenticate to the remote cluster and submit the pattern for remote execution if not done in previous exercise serverless = IBMServerlessClient("YOUR_IBM_QUANTUM_TOKEN") transpile_parallel_circuit = QiskitFunction( title="transpile_parallel", entrypoint="transpile_parallel.py", working_dir="./transpile_parallel", dependencies=["qiskit-transpiler-service"] ) serverless.upload(transpile_parallel_circuit) # Get list of functions serverless.list() # Fetch the specific function titled "transpile_parallel" transpile_parallel_serverless = serverless.get("transpile_parallel") # Add your code here # Run the "transpile_parallel" function in the serverless environment job = transpile_parallel_serverless.run(circuits=circuits, backend_name=backend.name) # Submit your answer using following code grade_lab3_qs_ex2(optimization_levels, transpiler_services, transpile_parallel_function, transpile_parallel_serverless, job) # Expected result type: list, list, QiskitFunction, QiskitFunction, Job job.status() logs = job.logs() for log in logs.splitlines(): print(log) result = job.result() result_transpiled = result["transpiled_circuits"] # Compare execution times: execution_time_serverless = result["execution_time"] from utils import plot_execution_times plot_execution_times(execution_time_serverless, execution_time_local) from utils import process_transpiled_circuits best_circuits, best_depths, best_methods = process_transpiled_circuits(configs, result_transpiled) # Display the best circuits, depths, and methods for i, (circuit, depth, method) in enumerate(zip(best_circuits, best_depths, best_methods)): print(f"Best result for circuit {i + 1}:") print(f" Depth: {depth}") print(f" Method: {method}") # Display or process the best circuit as needed # e.g., circuit.draw(output="mpl")
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are on 3.10 > python < 3.12 %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U # Import all in one cell import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import minimize from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import RealAmplitudes from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler import InstructionProperties from qiskit.visualization import plot_distribution from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.primitives import StatevectorEstimator from qiskit_aer import AerSimulator from qiskit_ibm_runtime import ( QiskitRuntimeService, EstimatorV2 as Estimator, SamplerV2 as Sampler, EstimatorOptions ) ### Save API Token, if needed %set_env QXToken=deleteThisAndPasteYourTokenHere # Set Grade only mode %set_env QC_GRADE_ONLY=true # Make sure there is no space between the equal sign # and the beginning of your token # qc-grader should be 0.18.12 (or higher) import qc_grader qc_grader.__version__ from qc_grader.challenges.iqc_2024 import ( grade_lab4_ex1, grade_lab4_ex2, grade_lab4_ex3, grade_lab4_ex4, grade_lab4_ex5, grade_lab4_ex6, grade_lab4_ex7 ) # Define num_qubits, the number of qubits, for the rest of the Lab num_qubits = 5 # Load the dictionary birds_dataset = pd.read_csv('birds_dataset.csv') # Check if the dataset is loaded correctly - coefficients should be complex numbers for i in range(2**num_qubits): key = 'c%.0f' %i birds_dataset[key] = birds_dataset[key].astype(np.complex128) # Print the dataset birds_dataset ### Write your code below here ### list_coefficients = [] list_labels = [] for i in range(10): amplitude_state = [] if i < 5: list_labels.append(1) else: list_labels.append(0) for j in range(2**num_qubits): key = 'c%.0f' %j amplitude_state.append(birds_dataset[key][i]) list_coefficients.append(amplitude_state) ### Don't change any code past this line ### # Submit your answer using following code grade_lab4_ex1(list_coefficients, list_labels) index_bird = 2 # You can check different birds by changing the index amplitudes = list_coefficients[index_bird] # Build the amplitude embedding qc = QuantumCircuit(5) qc.initialize(amplitudes, range(num_qubits)) qc.measure_all() # Draw the amplitude embedding circuit qc.draw(output="mpl") # Draw the decomposition of the amplitude embedding circuit qc.decompose(reps=8).draw(output="mpl", fold=40) ### Write your code below here ### num_qubits = 5 reps = 1 entanglement = 'full' ansatz = RealAmplitudes(num_qubits, reps=reps, entanglement=entanglement, insert_barriers=True) ansatz.decompose(reps=1).draw(output="mpl") ### Don't change any code past this line ### # Submit your answer using following code grade_lab4_ex2(num_qubits, reps, entanglement) # Define the observable obs = SparsePauliOp("ZZZZZ") # Define the estimator and pass manager estimator = StatevectorEstimator() #To train we use StatevectorEstimator to get the exact simulation pm = generate_preset_pass_manager(backend=AerSimulator(), optimization_level=3, seed_transpiler=0) # Define the cost function def cost_func(params, list_coefficients, list_labels, ansatz, obs, estimator, pm, callback_dict): """Return cost function for optimization Parameters: params (ndarray): Array of ansatz parameters list_coefficients (list): List of arrays of complex coefficients list_labels (list): List of labels ansatz (QuantumCircuit): Parameterized ansatz circuit obs (SparsePauliOp): Observable estimator (EstimatorV2): Statevector estimator primitive instance pm (PassManager): Pass manager callback_dict (dict): Dictionary to store callback information Returns: float: Cost function estimate """ cost = 0 for amplitudes,label in zip(list_coefficients, list_labels): qc = QuantumCircuit(num_qubits) # Amplitude embedding qc.initialize(amplitudes) # Compose initial state + ansatz classifier = qc.compose(ansatz) # Transpile classifier transpiled_classifier = pm.run(classifier) # Transpile observable transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) # Run estimator pub = (transpiled_classifier, transpiled_obs, params) job = estimator.run([pub]) # Get result result = job.result()[0].data.evs # Compute cost function (cumulative) cost += np.abs(result - label) callback_dict["iters"] += 1 callback_dict["prev_vector"] = params callback_dict["cost_history"].append(cost) # Print the iterations to screen on a single line print( "Iters. done: {} [Current cost: {}]".format(callback_dict["iters"], cost), end="\r", flush=True, ) return cost # Intialize the lists to store the results from different runs cost_history_list = [] res_list = [] # Retrieve the initial parameters params_0_list = np.load("params_0_list.npy") for it, params_0 in enumerate(params_0_list): print('Iteration number: ', it) # Initialize a callback dictionary callback_dict = { "prev_vector": None, "iters": 0, "cost_history": [], } # Minimize the cost function using scipy res = minimize( cost_func, params_0, args=(list_coefficients, list_labels, ansatz, obs, estimator, pm, callback_dict), method="cobyla", # Classical optimizer options={'maxiter': 200}) # Maximum number of iterations # Print the results after convergence print(res) # Save the results from different runs res_list.append(res) cost_history_list.append(callback_dict["cost_history"]) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost history') ax.set_ylabel('Cost') ax.set_xlabel('Iterations') ### Write your code below here ### #np.save('res_list.npy', res_list) for it, cost_history in enumerate(cost_history_list): ax.plot(cost_history, label='Trial '+str(it)) ax.legend() ### Don't change any code past this line ### def test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm): """Return the performance of the classifier Parameters: list_coefficients (list): List of arrays of complex coefficients list_labels (list): List of labels ansatz (QuantumCircuit): Parameterized ansatz circuit obs (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters estimator (EstimatorV2): Statevector estimator pm (PassManager): Pass manager for transpilation Returns: list: List of test results """ ### Write your code below here ### results_test = [] for amplitudes,label in zip(list_coefficients, list_labels): qc = QuantumCircuit(num_qubits) qc.initialize(amplitudes) classifier = qc.compose(ansatz) transpiled_classifier = pm.run(classifier) pub = (transpiled_classifier, obs, opt_params) job = estimator.run([pub]) result = job.result()[0].data.evs results_test.append(abs(result)) ### Don't change any code past this line ### return results_test def compute_performance(result_list, list_labels): """Return the performance of the classifier Parameters: result_list (list): List of results list_labels (list): List of labels Returns: float: Performance of the classifier """ ### Write your code below here ### performance = 100 for result, label in zip(result_list, list_labels): performance -= np.abs(abs(result) - label)/len(list_coefficients)*100 ### Don't change any code past this line ### return performance fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data') ax.set_ylabel('Cost') ax.set_xlabel('State index') ax.plot(list_labels, 'k-', linewidth=3, alpha=0.6, label='Labels') for index in range(len(res_list)): opt_params = res_list[index].x results_test = test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm) print(f"Performance for trial {index}: {compute_performance(results_test, list_labels)}") ax.plot(results_test, 'o--', label='Predictions trial '+str(index)) ax.legend() # Submit your answer using following code best_result_index = 4 # Choose the index with the best result grade_lab4_ex3(res_list[best_result_index]) # Expected result type: OptimizeResult fake_backend = GenericBackendV2( num_qubits=5, basis_gates=["id", "rz", "sx", "x", "cx"] ) def update_error_rate(backend, error_rates): """Updates the error rates of the backend Parameters: backend (BackendV2): Backend to update error_rates (dict): Dictionary of error rates Returns: None """ default_duration=1e-8 if "default_duration" in error_rates: default_duration = error_rates["default_duration"] # Update the 1-qubit gate properties for i in range(backend.num_qubits): qarg = (i,) if "rz_error" in error_rates: backend.target.update_instruction_properties('rz', qarg, InstructionProperties(error=error_rates["rz_error"], duration=default_duration)) if "x_error" in error_rates: backend.target.update_instruction_properties('x', qarg, InstructionProperties(error=error_rates["x_error"], duration=default_duration)) if "sx_error" in error_rates: backend.target.update_instruction_properties('sx', qarg, InstructionProperties(error=error_rates["sx_error"], duration=default_duration)) if "measure_error" in error_rates: backend.target.update_instruction_properties('measure', qarg, InstructionProperties(error=error_rates["measure_error"], duration=default_duration)) # Update the 2-qubit gate properties (CX gate) for all edges in the chosen coupling map if "cx_error" in error_rates: for edge in backend.coupling_map: backend.target.update_instruction_properties('cx', tuple(edge), InstructionProperties(error=error_rates["cx_error"], duration=default_duration)) error_rates = { "default_duration": 1e-8, "rz_error": 1e-8, "x_error": 1e-8, "sx_error": 1e-8, "measure_error": 1e-8, "cx_error": 1e-8 } update_error_rate(fake_backend, error_rates) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data') ax.set_ylabel('Cost') ax.set_xlabel('State index') ax.plot(list_labels, 'k-', linewidth=3, alpha=0.6, label='Labels') error_rate_list = [1e-1, 1e-2, 1e-3, 1e-4] fake_backend = GenericBackendV2( num_qubits=5, basis_gates=["id", "rz", "sx", "x", "cx"] ) for error_rate_value in error_rate_list: ### Write your code below here ### error_rates = { "default_duration": 1e-8, "rz_error": error_rate_value, "x_error": 1e-8, "sx_error": 1e-8, "measure_error": 1e-8, "cx_error": error_rate_value } update_error_rate(fake_backend, error_rates) estimator = Estimator(backend=fake_backend) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) opt_params = res_list[best_result_index].x ### Don't change any code past this line ### results_test = test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm) print(f"Performance for run {index}: {compute_performance(results_test, list_labels)}") ax.plot(results_test, 'o--', label='Predictions error rate '+str(error_rate_value)) ax.legend() # Submit your answer using following code grade_lab4_ex4(fake_backend) # Expected answer type: BackendV2 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_osaka") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 #you can check different birds by changing the index qc = QuantumCircuit(num_qubits) qc.initialize(list_coefficients[index_bird]) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", idle_wires=False, fold=40) def amplitude_embedding(num_qubits, bird_index): """Create amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ def generate_GHZ(qc): qc.h(0) for i, j in zip(range(num_qubits-1), range(1,num_qubits)): qc.cx(i, j) ### Write your code below here ### def generate_binary(qc, number): position=0 bit=1 while number >= bit: if number & bit: qc.x(position) bit <<= 1 position=position+1 qc = QuantumCircuit(num_qubits) if bird_index < 5: generate_GHZ(qc) generate_binary(qc, bird_index) ### Don't change any code past this line ### return qc index_bird = 0 # You can check different birds by changing the index # Build the amplitude embedding qc = amplitude_embedding(num_qubits, index_bird) qc.measure_all() # Define the backend and the pass manager aer_sim = AerSimulator() pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(qc) # Define the sampler with the number of shots sampler = Sampler(backend=aer_sim) result = sampler.run([isa_circuit]).result() samp_dist = result[0].data.meas.get_counts() plot_distribution(samp_dist, figsize=(15, 5)) index_bird = 0 #You can check different birds by changing the index qc = amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab4_ex5(amplitude_embedding) # Expected answer type Callable old_ansatz = RealAmplitudes(num_qubits, reps=1, entanglement='full', insert_barriers=True) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_ansatz = pm.run(old_ansatz) print('Depth of two-qubit gates: ', transpiled_ansatz.depth(lambda x: len(x.qubits) == 2)) transpiled_ansatz.draw(output="mpl", idle_wires=False, fold=40) ### Write your code below here ### ansatz = RealAmplitudes(num_qubits, reps=1, entanglement='pairwise', insert_barriers=True) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_ansatz = pm.run(ansatz) ### Don't change any code past this line ### print('Depth of two-qubit gates: ', transpiled_ansatz.depth(lambda x: len(x.qubits) == 2)) transpiled_ansatz.draw(output="mpl", fold=False, idle_wires=False) old_mapping = QuantumCircuit(num_qubits) old_mapping.initialize(list_coefficients[index_bird]) old_classifier = old_mapping.compose(old_ansatz) new_mapping = amplitude_embedding(num_qubits, index_bird) new_classifier = new_mapping.compose(ansatz) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) old_transpiled_classifier = pm.run(old_classifier) new_transpiled_classifier = pm.run(new_classifier) print('Old depth of two-qubit gates: ', old_transpiled_classifier.depth(lambda x: len(x.qubits) == 2)) print('Current depth of two-qubit gates: ', new_transpiled_classifier.depth(lambda x: len(x.qubits) == 2)) def test_shallow_VQC(list_labels, ansatz, obs, opt_params, estimator, pm): """Return the performance of the classifier Parameters: list_labels (list): List of labels ansatz (QuantumCircuit): Parameterized ansatz circuit obs (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters estimator (EstimatorV2): Statevector estimator pm (PassManager): Pass manager for transpilation Returns: results_test (list): List of test results """ ### Write your code below here ### results_test = [] for bird, label in enumerate(list_labels): qc = amplitude_embedding(num_qubits, bird) classifier = qc.compose(ansatz) transpiled_classifier = pm.run(classifier) transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) pub = (transpiled_classifier, transpiled_obs, opt_params) job = estimator.run([pub]) result = job.result()[0].data.evs results_test.append(abs(result)) ### Don't change any code past this line ### return results_test estimator = Estimator(backend=fake_backend) estimator.options.default_shots = 5000 pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) opt_params = np.load('opt_params_shallow_VQC.npy') # Load optimal parameters results_test = test_shallow_VQC(list_labels, ansatz, obs, opt_params, estimator, pm) print(f"Performance: {compute_performance(results_test, list_labels)}") fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data') ax.set_ylabel('Cost') ax.set_xlabel('State index') ax.plot(list_labels, 'k-', linewidth=3, alpha=0.6, label='Labels') ax.plot(results_test, 'o--', label='Fake Backend') ax.legend() # Submit your answer using following code grade_lab4_ex6(results_test) # Expected answer type: list[float] service = QiskitRuntimeService() backend = service.backend("ibm_osaka") def test_shallow_VQC_QPU(list_labels, anstaz, obs, opt_params, options, backend): """Return the performance of the classifier Parameters: list_labels (list): List of labels ansatz (QuantumCircuit): Parameterized ansatz circuit obs (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Estimator options backend (service.backend): Backend to run the job Returns: job_id (str): Job ID """ estimator = Estimator(backend=backend, options=options) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) pubs = [] for bird, label in enumerate(list_labels): ### Write your code below here ### qc = QuantumCircuit(num_qubits) amplitude_embedding(qc, bird) classifier = qc.compose(ansatz) transpiled_classifier = pm.run(classifier) transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) ### Don't change any code past this line ### pub = (transpiled_classifier, transpiled_obs, opt_params) pubs.append(pub) job = estimator.run(pubs) job_id = job.job_id() print(f"Job ID: {job_id}") print(f"Status: {job.status()}") return job_id ## SOLUTIONS ## No DD, no TREX (no ZNE) resilience = 0 DD = False options_0 = EstimatorOptions(default_shots = 5000, optimization_level=0, resilience_level=resilience) options_0.dynamical_decoupling.enable = DD options_0.dynamical_decoupling.sequence_type = 'XpXm' ## DD + TREX (no ZNE) resilience = 1 DD = True options_1 = EstimatorOptions(default_shots = 5000, optimization_level=0, resilience_level=resilience) options_1.dynamical_decoupling.enable = DD options_1.dynamical_decoupling.sequence_type = 'XpXm' # Submit your answer using following code grade_lab4_ex7(options_0, options_1) # Expected answer type: EstimatorOptions, EstimatorOptions def retrieve_job(job_id): ''' Retrieve results from job_id ''' job = service.job(job_id) results_test = [] errors_test = [] for result in job.result(): results_test.append(abs(result.data.evs)) errors_test.append(abs(result.data.stds)) return results_test, errors_test ## No DD, no TREX (no ZNE) job_id_0 = test_shallow_VQC_QPU(list_labels, ansatz, obs, opt_params, options_0, backend) ## DD + TREX (no ZNE) job_id_1 = test_shallow_VQC_QPU(list_labels, ansatz, obs, opt_params, options_1, backend) results_test_0_DD, errors_test_0_DD = retrieve_job() #(Add job_id 0 here) results_test_1_DD, errors_test_1_DD = retrieve_job() #(Add job_id 1 here) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for no DD + no TREX: {compute_performance(results_test_0_DD, list_labels):.3f}") print(f"Performance for DD + TREX: {compute_performance(results_test_1_DD, list_labels):.3f}") ax.errorbar(range(10), results_test_0_DD, fmt='-o', yerr=errors_test_0_DD, color='tab:orange', label='Osaka no EM') ax.errorbar(range(10), results_test_1_DD, fmt='-o', yerr=errors_test_1_DD, color='tab:blue', label='Osaka TREX + DD') ax.plot(list_labels, 'k-', label='Labels') ax.legend()
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# transpile_parallel.py from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_transpiler_service.transpiler_service import TranspilerService from qiskit_serverless import get_arguments, save_result, distribute_task, get from qiskit_ibm_runtime import QiskitRuntimeService from timeit import default_timer as timer @distribute_task(target={"cpu": 2}) def transpile_parallel(circuit: QuantumCircuit, config): """Distributed transpilation for an abstract circuit into an ISA circuit for a given backend.""" transpiled_circuit = config.run(circuit) return transpiled_circuit # Get program arguments arguments = get_arguments() circuits = arguments.get("circuits") backend_name = arguments.get("backend_name") # Get backend service = QiskitRuntimeService(channel="ibm_quantum") backend = service.get_backend(backend_name) # Define Configs optimization_levels = [1,2,3] pass_managers = [generate_preset_pass_manager(optimization_level=level, backend=backend) for level in optimization_levels] transpiler_services = [ {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': False, 'optimization_level': 3}, {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': True, 'optimization_level': 3} ] configs = pass_managers + transpiler_services # Start process print("Starting timer") start = timer() # run distributed tasks as async function # we get task references as a return type sample_task_references = [] for circuit in circuits: sample_task_references.append([transpile_parallel(circuit, config) for config in configs]) # now we need to collect results from task references results = get([task for subtasks in sample_task_references for task in subtasks]) end = timer() # Record execution time execution_time_serverless = end-start print("Execution time: ", execution_time_serverless) save_result({ "transpiled_circuits": results, "execution_time" : execution_time_serverless })
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
import json import logging import numpy as np import warnings from functools import wraps from typing import Any, Callable, Optional, Tuple, Union from qiskit import IBMQ, QuantumCircuit, assemble from qiskit.circuit import Barrier, Gate, Instruction, Measure from qiskit.circuit.library import UGate, U3Gate, CXGate from qiskit.providers.ibmq import AccountProvider, IBMQProviderError from qiskit.providers.ibmq.job import IBMQJob def get_provider() -> AccountProvider: with warnings.catch_warnings(): warnings.simplefilter('ignore') ibmq_logger = logging.getLogger('qiskit.providers.ibmq') current_level = ibmq_logger.level ibmq_logger.setLevel(logging.ERROR) # get provider try: provider = IBMQ.get_provider() except IBMQProviderError: provider = IBMQ.load_account() ibmq_logger.setLevel(current_level) return provider def get_job(job_id: str) -> Optional[IBMQJob]: try: job = get_provider().backends.retrieve_job(job_id) return job except Exception: pass return None def circuit_to_json(qc: QuantumCircuit) -> str: class _QobjEncoder(json.encoder.JSONEncoder): def default(self, obj: Any) -> Any: if isinstance(obj, np.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder) def circuit_to_dict(qc: QuantumCircuit) -> dict: qobj = assemble(qc) return qobj.to_dict() def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]: try: job_id = job.job_id() if isinstance(job, IBMQJob) else job download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url'] result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url'] return download_url, result_url except Exception: return None, None def cached(key_function: Callable) -> Callable: def _decorator(f: Any) -> Callable: f.__cache = {} @wraps(f) def _decorated(*args: Any, **kwargs: Any) -> int: key = key_function(*args, **kwargs) if key not in f.__cache: f.__cache[key] = f(*args, **kwargs) return f.__cache[key] return _decorated return _decorator def gate_key(gate: Gate) -> Tuple[str, int]: return gate.name, gate.num_qubits @cached(gate_key) def gate_cost(gate: Gate) -> int: if isinstance(gate, (UGate, U3Gate)): return 1 elif isinstance(gate, CXGate): return 10 elif isinstance(gate, (Measure, Barrier)): return 0 return sum(map(gate_cost, (g for g, _, _ in gate.definition.data))) def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int: print('Computing cost...') circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction): circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') return sum(map(gate_cost, (g for g, _, _ in circuit_data))) def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool: circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction) and circuit.definition is not None: circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') for g, _, _ in circuit_data: if isinstance(g, (Barrier, Measure)): continue elif isinstance(g, Gate): if g.num_qubits > 1: return True elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g): return True return False
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ import logging import functools import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.utils.backend_utils import is_aer_statevector_backend from qiskit.aqua.utils import find_regs_by_name logger = logging.getLogger(__name__) class VQE(VQAlgorithm): """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ CONFIGURATION = { 'name': 'VQE', 'description': 'VQE Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'vqe_schema', 'type': 'object', 'properties': { 'operator_mode': { 'type': 'string', 'default': 'matrix', 'oneOf': [ {'enum': ['matrix', 'paulis', 'grouped_paulis']} ] }, 'initial_point': { 'type': ['array', 'null'], "items": { "type": "number" }, 'default': None }, 'max_evals_grouped': { 'type': 'integer', 'default': 1 } }, 'additionalProperties': False }, 'problems': ['energy', 'ising'], 'depends': [ {'pluggable_type': 'optimizer', 'default': { 'name': 'L_BFGS_B' } }, {'pluggable_type': 'variational_form', 'default': { 'name': 'RYRZ' } }, ], } def __init__(self, operator, var_form, optimizer, operator_mode='matrix', initial_point=None, max_evals_grouped=1, aux_operators=None, callback=None): """Constructor. Args: operator (Operator): Qubit operator operator_mode (str): operator mode, used for eval of operator var_form (VariationalForm): parametrized variational form. optimizer (Optimizer): the classical optimization algorithm. initial_point (numpy.ndarray): optimizer initial point. max_evals_grouped (int): max number of evaluations performed simultaneously aux_operators (list of Operator): Auxiliary operators to be evaluated at each eigenvalue callback (Callable): a callback that can access the intermediate data during the optimization. Internally, four arguments are provided as follows the index of evaluation, parameters of variational form, evaluated mean, evaluated standard devation. """ self.validate(locals()) super().__init__(var_form=var_form, optimizer=optimizer, cost_fn=self._energy_evaluation, initial_point=initial_point) self._optimizer.set_max_evals_grouped(max_evals_grouped) self._callback = callback if initial_point is None: self._initial_point = var_form.preferred_init_points self._operator = operator self._operator_mode = operator_mode self._eval_count = 0 if aux_operators is None: self._aux_operators = [] else: self._aux_operators = [aux_operators] if not isinstance(aux_operators, list) else aux_operators logger.info(self.print_settings()) @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance Returns: VQE: vqe object """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op vqe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) operator_mode = vqe_params.get('operator_mode') initial_point = vqe_params.get('initial_point') max_evals_grouped = vqe_params.get('max_evals_grouped') # Set up variational form, we need to add computed num qubits # Pass all parameters so that Variational Form can create its dependents var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM) var_form_params['num_qubits'] = operator.num_qubits var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params) # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) return cls(operator, var_form, optimizer, operator_mode=operator_mode, initial_point=initial_point, max_evals_grouped=max_evals_grouped, aux_operators=algo_input.aux_ops) @property def setting(self): """Prepare the setting of VQE as a string.""" ret = "Algorithm: {}\n".format(self._configuration['name']) params = "" for key, value in self.__dict__.items(): if key != "_configuration" and key[0] == "_": if "initial_point" in key and value is None: params += "-- {}: {}\n".format(key[1:], "Random seed") else: params += "-- {}: {}\n".format(key[1:], value) ret += "{}".format(params) return ret def print_settings(self): """ Preparing the setting of VQE into a string. Returns: str: the formatted setting of VQE """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}".format(self.setting) ret += "===============================================================\n" ret += "{}".format(self._var_form.setting) ret += "===============================================================\n" ret += "{}".format(self._optimizer.setting) ret += "===============================================================\n" return ret def construct_circuit(self, parameter, backend=None, use_simulator_operator_mode=False): """Generate the circuits. Args: parameters (numpy.ndarray): parameters for variational form. backend (qiskit.BaseBackend): backend object. use_simulator_operator_mode (bool): is backend from AerProvider, if True and mode is paulis, single circuit is generated. Returns: [QuantumCircuit]: the generated circuits with Hamiltonian. """ input_circuit = self._var_form.construct_circuit(parameter) if backend is None: warning_msg = "Circuits used in VQE depends on the backend type, " from qiskit import BasicAer if self._operator_mode == 'matrix': temp_backend_name = 'statevector_simulator' else: temp_backend_name = 'qasm_simulator' backend = BasicAer.get_backend(temp_backend_name) warning_msg += "since operator_mode is '{}', '{}' backend is used.".format( self._operator_mode, temp_backend_name) logger.warning(warning_msg) circuit = self._operator.construct_evaluation_circuit(self._operator_mode, input_circuit, backend, use_simulator_operator_mode) return circuit def _eval_aux_ops(self, threshold=1e-12, params=None): if params is None: params = self.optimal_params wavefn_circuit = self._var_form.construct_circuit(params) circuits = [] values = [] params = [] for operator in self._aux_operators: if not operator.is_empty(): temp_circuit = QuantumCircuit() + wavefn_circuit circuit = operator.construct_evaluation_circuit(self._operator_mode, temp_circuit, self._quantum_instance.backend, self._use_simulator_operator_mode) params.append(operator.aer_paulis) else: circuit = None circuits.append(circuit) if len(circuits) > 0: to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, [c for c in circuits if c is not None]) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': params, 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for operator, circuit in zip(self._aux_operators, circuits): if circuit is None: mean, std = 0.0, 0.0 else: mean, std = operator.evaluate_with_result(self._operator_mode, circuit, self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean = mean.real if abs(mean.real) > threshold else 0.0 std = std.real if abs(std.real) > threshold else 0.0 values.append((mean, std)) if len(values) > 0: aux_op_vals = np.empty([1, len(self._aux_operators), 2]) aux_op_vals[0, :] = np.asarray(values) self._ret['aux_ops'] = aux_op_vals def _run(self): """ Run the algorithm to compute the minimum eigenvalue. Returns: Dictionary of results """ if not self._quantum_instance.is_statevector and self._operator_mode == 'matrix': logger.warning('Qasm simulation does not work on {} mode, changing ' 'the operator_mode to "paulis"'.format(self._operator_mode)) self._operator_mode = 'paulis' self._use_simulator_operator_mode = \ is_aer_statevector_backend(self._quantum_instance.backend) \ and self._operator_mode != 'matrix' self._quantum_instance.circuit_summary = True self._eval_count = 0 self._ret = self.find_minimum(initial_point=self.initial_point, var_form=self.var_form, cost_fn=self._energy_evaluation, optimizer=self.optimizer) if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']: self._eval_count = self._ret['num_optimizer_evals'] self._eval_time = self._ret['eval_time'] logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format( self._eval_time, self._ret['opt_params'], self._eval_count)) self._ret['eval_count'] = self._eval_count self._ret['energy'] = self.get_optimal_cost() self._ret['eigvals'] = np.asarray([self.get_optimal_cost()]) self._ret['eigvecs'] = np.asarray([self.get_optimal_vector()]) self._eval_aux_ops() return self._ret # This is the objective function to be passed to the optimizer that is uses for evaluation def _energy_evaluation(self, parameters): """ Evaluate energy at given parameters for the variational form. Args: parameters (numpy.ndarray): parameters for variational form. Returns: float or list of float: energy of the hamiltonian of each parameter. """ num_parameter_sets = len(parameters) // self._var_form.num_parameters circuits = [] parameter_sets = np.split(parameters, num_parameter_sets) mean_energy = [] std_energy = [] for idx in range(len(parameter_sets)): parameter = parameter_sets[idx] circuit = self.construct_circuit(parameter, self._quantum_instance.backend, self._use_simulator_operator_mode) circuits.append(circuit) to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, circuits) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': [self._operator.aer_paulis], 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for idx in range(len(parameter_sets)): mean, std = self._operator.evaluate_with_result( self._operator_mode, circuits[idx], self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean_energy.append(np.real(mean)) std_energy.append(np.real(std)) self._eval_count += 1 if self._callback is not None: self._callback(self._eval_count, parameter_sets[idx], np.real(mean), np.real(std)) logger.info('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean))) return mean_energy if len(mean_energy) > 1 else mean_energy[0] def get_optimal_cost(self): if 'opt_params' not in self._ret: raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.") return self._ret['min_val'] def get_optimal_circuit(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.") return self._var_form.construct_circuit(self._ret['opt_params']) def get_optimal_vector(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.") qc = self.get_optimal_circuit() if self._quantum_instance.is_statevector: ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_statevector(qc, decimals=16) else: c = ClassicalRegister(qc.width(), name='c') q = find_regs_by_name(qc, 'q') qc.add_register(c) qc.barrier(q) qc.measure(q, c) ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_counts(qc) return self._ret['min_vector'] @property def optimal_params(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal params before running the algorithm.") return self._ret['opt_params']
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit import * from qiskit.visualization import plot_histogram import numpy as np def NOT(inp): """An NOT gate. Parameters: inp (str): Input, encoded in qubit 0. Returns: QuantumCircuit: Output NOT circuit. str: Output value measured from qubit 0. """ qc = QuantumCircuit(1, 1) # A quantum circuit with a single qubit and a single classical bit qc.reset(0) # We encode '0' as the qubit state |0⟩, and '1' as |1⟩ # Since the qubit is initially |0⟩, we don't need to do anything for an input of '0' # For an input of '1', we do an x to rotate the |0⟩ to |1⟩ if inp=='1': qc.x(0) # barrier between input state and gate operation qc.barrier() # Now we've encoded the input, we can do a NOT on it using x qc.x(0) #barrier between gate operation and measurement qc.barrier() # Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0] qc.measure(0,0) qc.draw() # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc, shots=1, memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp in ['0', '1']: qc, out = NOT(inp) print('NOT with input',inp,'gives output',out) display(qc.draw()) print('\n') def XOR(inp1,inp2): """An XOR gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output XOR circuit. str: Output value measured from qubit 1. """ qc = QuantumCircuit(2, 1) qc.reset(range(2)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) # barrier between input state and gate operation qc.barrier() # this is where your program for quantum XOR gate goes qc.cx(0, 1) # barrier between input state and gate operation qc.barrier() qc.measure(1,0) # output from qubit 1 is measured #We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') #Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc, shots=1, memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = XOR(inp1, inp2) print('XOR with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') def AND(inp1,inp2): """An AND gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output XOR circuit. str: Output value measured from qubit 2. """ qc = QuantumCircuit(3, 1) qc.reset(range(2)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() # this is where your program for quantum AND gate goes qc.ccx(0,1,2) qc.barrier() qc.measure(2, 0) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc, shots=1, memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = AND(inp1, inp2) print('AND with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') def NAND(inp1,inp2): """An NAND gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output NAND circuit. str: Output value measured from qubit 2. """ qc = QuantumCircuit(3, 1) qc.reset(range(3)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() # this is where your program for quantum NAND gate goes qc.ccx(0,1,2) if inp=='1': qc.x(2) qc.barrier() qc.measure(2, 0) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('aer_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc,shots=1,memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = NAND(inp1, inp2) print('NAND with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') def OR(inp1,inp2): """An OR gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output XOR circuit. str: Output value measured from qubit 2. """ qc = QuantumCircuit(3, 1) qc.reset(range(3)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() # this is where your program for quantum OR gate goes qc.cx(0, 2) qc.cx(1, 2) qc.barrier() qc.measure(2, 0) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('aer_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc,shots=1,memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = OR(inp1, inp2) print('OR with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') from qiskit import IBMQ #IBMQ.save_account("a68a35747d4eccd1d58f275e637909987c789ce5c0edd8a4f43014672bf0301b54b28b1b5f44ba8ff87500777429e1e4ceb79621a6ba248d6cca6bca0e233d23", overwrite=True) IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider('ibm-q') provider.backends() import qiskit.tools.jupyter # run this cell backend = provider.get_backend('ibmq_quito') qc_and = QuantumCircuit(3) qc_and.ccx(0,1,2) print('AND gate') display(qc_and.draw()) print('\n\nTranspiled AND gate with all the required connectivity') qc_and.decompose().draw() from qiskit.tools.monitor import job_monitor # run the cell to define AND gate for real quantum system def AND(inp1, inp2, backend, layout): qc = QuantumCircuit(3, 1) qc.reset(range(3)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() qc.ccx(0, 1, 2) qc.barrier() qc.measure(2, 0) qc_trans = transpile(qc, backend, initial_layout=layout, optimization_level=3) job = backend.run(qc_trans, shots=8192) print(job.job_id()) job_monitor(job) output = job.result().get_counts() return qc_trans, output backend layout = [0, 1, 2] output_all = [] qc_trans_all = [] prob_all = [] worst = 1 best = 0 for input1 in ['0','1']: for input2 in ['0','1']: qc_trans, output = AND(input1, input2, backend, layout) output_all.append(output) qc_trans_all.append(qc_trans) prob = output[str(int( input1=='1' and input2=='1' ))]/8192 prob_all.append(prob) print('\nProbability of correct answer for inputs',input1,input2) print('{:.2f}'.format(prob) ) print('---------------------------------') worst = min(worst,prob) best = max(best, prob) print('') print('\nThe highest of these probabilities was {:.2f}'.format(best)) print('The lowest of these probabilities was {:.2f}'.format(worst)) print('Transpiled AND gate circuit for ibmq_vigo with input 0 0') print('\nThe circuit depth : {}'.format (qc_trans_all[0].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[0].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[0]) ) qc_trans_all[0].draw() print('Transpiled AND gate circuit for ibmq_vigo with input 0 1') print('\nThe circuit depth : {}'.format (qc_trans_all[1].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[1].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[1]) ) qc_trans_all[1].draw() print('Transpiled AND gate circuit for ibmq_vigo with input 1 0') print('\nThe circuit depth : {}'.format (qc_trans_all[2].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[2].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[2]) ) qc_trans_all[2].draw() print('Transpiled AND gate circuit for ibmq_vigo with input 1 1') print('\nThe circuit depth : {}'.format (qc_trans_all[3].depth())) print('# of nonlocal gates : {}'.format (qc_trans_all[3].num_nonlocal_gates())) print('Probability of correct answer : {:.2f}'.format(prob_all[3]) ) qc_trans_all[3].draw()
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, execute from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.providers.aer import QasmSimulator backend = Aer.get_backend('statevector_simulator') qc1 = QuantumCircuit(4) # perform gate operations on individual qubits qc1.x(0) qc1.y(1) qc1.z(2) qc1.s(3) # Draw circuit qc1.draw() # Plot blochshere out1 = execute(qc1,backend).result().get_statevector() plot_bloch_multivector(out1) qc2 = QuantumCircuit(4) # initialize qubits qc2.x(range(4)) # perform gate operations on individual qubits qc2.x(0) qc2.y(1) qc2.z(2) qc2.s(3) # Draw circuit qc2.draw() # Plot blochshere out2 = execute(qc2,backend).result().get_statevector() plot_bloch_multivector(out2) qc3 = QuantumCircuit(4) # initialize qubits qc3.h(range(4)) # perform gate operations on individual qubits qc3.x(0) qc3.y(1) qc3.z(2) qc3.s(3) # Draw circuit qc3.draw() # Plot blochshere out3 = execute(qc3,backend).result().get_statevector() plot_bloch_multivector(out3) qc4 = QuantumCircuit(4) # initialize qubits qc4.x(range(4)) qc4.h(range(4)) # perform gate operations on individual qubits qc4.x(0) qc4.y(1) qc4.z(2) qc4.s(3) # Draw circuit qc4.draw() # Plot blochshere out4 = execute(qc4,backend).result().get_statevector() plot_bloch_multivector(out4) qc5 = QuantumCircuit(4) # initialize qubits qc5.h(range(4)) qc5.s(range(4)) # perform gate operations on individual qubits qc5.x(0) qc5.y(1) qc5.z(2) qc5.s(3) # Draw circuit qc5.draw() # Plot blochshere out5 = execute(qc5,backend).result().get_statevector() plot_bloch_multivector(out5) qc6 = QuantumCircuit(4) # initialize qubits qc6.x(range(4)) qc6.h(range(4)) qc6.s(range(4)) # perform gate operations on individual qubits qc6.x(0) qc6.y(1) qc6.z(2) qc6.s(3) # Draw circuit qc6.draw() # Plot blochshere out6 = execute(qc6,backend).result().get_statevector() plot_bloch_multivector(out6) import qiskit qiskit.__qiskit_version__
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit import * import numpy as np from numpy import linalg as la from qiskit.tools.monitor import job_monitor import qiskit.tools.jupyter qc = QuantumCircuit(1) #### your code goes here # z measurement of qubit 0 measure_z = QuantumCircuit(1,1) measure_z.measure(0,0) # x measurement of qubit 0 measure_x = QuantumCircuit(1,1) # your code goes here # y measurement of qubit 0 measure_y = QuantumCircuit(1,1) # your code goes here shots = 2**14 # number of samples used for statistics sim = Aer.get_backend('qasm_simulator') bloch_vector_measure = [] for measure_circuit in [measure_x, measure_y, measure_z]: # run the circuit with a the selected measurement and get the number of samples that output each bit value counts = execute(qc+measure_circuit, sim, shots=shots).result().get_counts() # calculate the probabilities for each bit value probs = {} for output in ['0','1']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 bloch_vector_measure.append( probs['0'] - probs['1'] ) # normalizing the bloch sphere vector bloch_vector = bloch_vector_measure/la.norm(bloch_vector_measure) print('The bloch sphere coordinates are [{0:4.3f}, {1:4.3f}, {2:4.3f}]' .format(*bloch_vector)) from kaleidoscope.interactive import bloch_sphere bloch_sphere(bloch_vector, vectors_annotation=True) from qiskit.visualization import plot_bloch_vector plot_bloch_vector( bloch_vector ) # circuit for the state Tri1 Tri1 = QuantumCircuit(2) # your code goes here # circuit for the state Tri2 Tri2 = QuantumCircuit(2) # your code goes here # circuit for the state Tri3 Tri3 = QuantumCircuit(2) # your code goes here # circuit for the state Sing Sing = QuantumCircuit(2) # your code goes here # <ZZ> measure_ZZ = QuantumCircuit(2) measure_ZZ.measure_all() # <XX> measure_XX = QuantumCircuit(2) # your code goes here # <YY> measure_YY = QuantumCircuit(2) # your code goes here shots = 2**14 # number of samples used for statistics A = 1.47e-6 #unit of A is eV E_sim = [] for state_init in [Tri1,Tri2,Tri3,Sing]: Energy_meas = [] for measure_circuit in [measure_XX, measure_YY, measure_ZZ]: # run the circuit with a the selected measurement and get the number of samples that output each bit value qc = state_init+measure_circuit counts = execute(qc, sim, shots=shots).result().get_counts() # calculate the probabilities for each computational basis probs = {} for output in ['00','01', '10', '11']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] ) E_sim.append(A * np.sum(np.array(Energy_meas))) # Run this cell to print out your results print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_sim[0])) print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_sim[1])) print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_sim[2])) print('Energy expection value of the state Sing : {:.3e} eV'.format(E_sim[3])) # reduced plank constant in (eV) and the speed of light(cgs units) hbar, c = 4.1357e-15, 3e10 # energy difference between the triplets and singlet E_del = abs(E_sim[0] - E_sim[3]) # frequency associated with the energy difference f = E_del/hbar # convert frequency to wavelength in (cm) wavelength = c/f print('The wavelength of the radiation from the transition\ in the hyperfine structure is : {:.1f} cm'.format(wavelength)) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_athens') # run this cell to get the backend information through the widget backend # assign your choice for the initial layout to the list variable `initial_layout`. initial_layout = qc_all = [state_init+measure_circuit for state_init in [Tri1,Tri2,Tri3,Sing] for measure_circuit in [measure_XX, measure_YY, measure_ZZ] ] shots = 8192 job = execute(qc_all, backend, initial_layout=initial_layout, optimization_level=3, shots=shots) print(job.job_id()) job_monitor(job) # getting the results of your job results = job.result() ## To access the results of the completed job #results = backend.retrieve_job('job_id').result() def Energy(results, shots): """Compute the energy levels of the hydrogen ground state. Parameters: results (obj): results, results from executing the circuits for measuring a hamiltonian. shots (int): shots, number of shots used for the circuit execution. Returns: Energy (list): energy values of the four different hydrogen ground states """ E = [] A = 1.47e-6 for ind_state in range(4): Energy_meas = [] for ind_comp in range(3): counts = results.get_counts(ind_state*3+ind_comp) # calculate the probabilities for each computational basis probs = {} for output in ['00','01', '10', '11']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] ) E.append(A * np.sum(np.array(Energy_meas))) return E E = Energy(results, shots) print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E[0])) print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E[1])) print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E[2])) print('Energy expection value of the state Sing : {:.3e} eV'.format(E[3])) from qiskit.ignis.mitigation.measurement import * # your code to create the circuits, meas_calibs, goes here meas_calibs, state_labels = # execute meas_calibs on your choice of the backend job = execute(meas_calibs, backend, shots = shots) print(job.job_id()) job_monitor(job) cal_results = job.result() ## To access the results of the completed job #cal_results = backend.retrieve_job('job_id').result() # your code to obtain the measurement filter object, 'meas_filter', goes here results_new = meas_filter.apply(results) E_new = Energy(results_new, shots) print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_new[0])) print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_new[1])) print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_new[2])) print('Energy expection value of the state Sing : {:.3e} eV'.format(E_new[3])) # results for the energy estimation from the simulation, # execution on a quantum system without error mitigation and # with error mitigation in numpy array format Energy_exact, Energy_exp_orig, Energy_exp_new = np.array(E_sim), np.array(E), np.array(E_new) # Calculate the relative errors of the energy values without error mitigation # and assign to the numpy array variable `Err_rel_orig` of size 4 Err_rel_orig = # Calculate the relative errors of the energy values with error mitigation # and assign to the numpy array variable `Err_rel_new` of size 4 Err_rel_new = np.set_printoptions(precision=3) print('The relative errors of the energy values for four bell basis\ without measurement error mitigation : {}'.format(Err_rel_orig)) np.set_printoptions(precision=3) print('The relative errors of the energy values for four bell basis\ with measurement error mitigation : {}'.format(Err_rel_new))
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# Importing standard Qiskit libraries and configuring account from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute from qiskit.visualization import plot_bloch_multivector # If you run this code outside IBM Quantum Experience, # run the following commands to store your API token locally. # Please refer https://qiskit.org/documentation/install.html#access-ibm-quantum-systems # IBMQ.save_account('MY_API_TOKEN') # Loading your IBM Q account(s) IBMQ.load_account() # Let's do an X-gate on a |0> qubit q = QuantumRegister(1) qc = QuantumCircuit(q) qc.x(q[0]) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result().get_statevector(qc, decimals=3) plot_bloch_multivector(result) # Let's do an H-gate on a |0> qubit q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q[0]) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result().get_statevector(qc, decimals=3) plot_bloch_multivector(result) # Let's do an Z-gate on |+> q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q[0]) qc.z(q[0]) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result().get_statevector(qc, decimals=3) print(result) plot_bloch_multivector(result) # Let's do an CX-gate on |00> q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result().get_statevector(qc, decimals=3) print(result) plot_bloch_multivector(result) # Let's do an CZ-gate on |00> q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw(output='mpl') # Let's make CZ-gate with CX-gate and H-gate q = QuantumRegister(2) qc = QuantumCircuit(q) qc.h(q[1]) qc.cx(q[0],q[1]) qc.h(q[1]) qc.draw(output='mpl') # Let's do an CCX-gate on |00> q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q[0],q[1],q[2]) qc.draw(output='mpl') # Create a Quantum Circuit with 1 quantum register and 1 classical register q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.x(q[0]) qc.measure(q[0], c[0]) # Map the quantum measurement to the classical bits qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.ccx(q[0], q[1], q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.ccx(q[0], q[1], q[2]) qc.x(q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.cx(q[1], q[2]) qc.cx(q[0], q[2]) qc.ccx(q[0], q[1], q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.cx(q[1], q[2]) qc.cx(q[0], q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.cx(q[1], q[2]) qc.cx(q[0], q[2]) qc.ccx(q[0], q[1], q[2]) qc.x(q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') #Define registers and a quantum circuit q = QuantumRegister(4) c = ClassicalRegister(2) qc = QuantumCircuit(q,c) #XOR qc.cx(q[1], q[2]) qc.cx(q[0], q[2]) qc.barrier() #AND qc.ccx(q[0], q[1], q[3]) qc.barrier() #Sum qc.measure(q[2], c[0]) #Carry out qc.measure(q[3], c[1]) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer, execute from qiskit.quantum_info import Pauli, state_fidelity, process_fidelity q = QuantumRegister(4, 'q0') c = ClassicalRegister(1, 'c0') qc = QuantumCircuit(q, c) qc.ccx(q[0], q[1], q[2]) qc.cx(q[3], q[1]) qc.h(q[3]) qc.ccx(q[3], q[2], q[1]) qc.measure(q[3],c[0]) qc.draw(output='mpl') qc.count_ops() from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) new_circuit.draw(output='mpl') new_circuit.count_ops() q = QuantumRegister(3, 'q0') c = ClassicalRegister(1, 'c0') qc = QuantumCircuit(q, c) qc.ccx(q[0], q[1], q[2]) qc.draw(output='mpl') pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) new_circuit.draw(output='mpl') new_circuit.count_ops() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute ##### build your quantum circuit here q = QuantumRegister(8, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q,c) qc.x(q[0]) #input 1 #qc.x(q[1]) #input 1 qc.x(q[2]) #input 1 qc.cx(q[2],q[3]) qc.cx(q[1], q[3]) # B XOR X qc.cx(q[3], q[4]) qc.cx(q[0], q[4]) #4 will be my sum - B XOR X XOR A qc.ccx(q[0], q[3], q[5]) # A AND (B XOR X) qc.ccx(q[1], q[2], q[6]) # BX qc.cx(q[6], q[7]) qc.cx(q[5], q[7]) qc.ccx(q[5], q[6], q[7]) # BX AND A(B XOR X) qc.measure(q[4],c[0]) # SUM - B XOR X XOR A qc.measure(q[7],c[1]) # Carry Out - BX OR A(B XOR X) # execute the circuit by qasm_simulator backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute ##### build your quantum circuit here q = QuantumRegister(6, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q,c) qc.x(q[0]) #input 1 #qc.x(q[1]) #input 1 qc.x(q[2]) #input 1 qc.ccx(q[1], q[2],q[3]) # BX qc.cx(q[1], q[2]) # B XOR X qc.ccx(q[0], q[2], q[4]) # A(B XOR X) qc.cx(q[0], q[2]) #2 will be my sum - B XOR X XOR A qc.cx(q[4], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[3], q[4], q[5]) # BX OR A(B XOR X) qc.measure(q[2],c[0]) # SUM - B XOR X XOR A qc.measure(q[5],c[1]) # Carry Out - BX OR A(B XOR X) # execute the circuit by qasm_simulator backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute ##### build your quantum circuit here q = QuantumRegister(6, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q,c) qc.x(q[0]) #input 1 #qc.x(q[1]) #input 1 qc.x(q[2]) #input 1 qc.ccx(q[1], q[2],q[3]) # BX qc.cx(q[1], q[2]) # B XOR X qc.ccx(q[0], q[2], q[4]) # A(B XOR X) qc.cx(q[0], q[2]) #2 will be my sum - B XOR X XOR A qc.measure(q[2],c[0]) # SUM - B XOR X XOR A qc.x(q[3]) qc.x(q[4]) qc.ccx(q[3], q[4], q[5]) qc.x(q[5])# BX OR A(B XOR X) qc.measure(q[5],c[1]) # Carry Out - BX OR A(B XOR X) # execute the circuit by qasm_simulator backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute ##### build your quantum circuit here q = QuantumRegister(4, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q,c) qc.x(q[0]) #input 1 #qc.x(q[1]) #input 1 qc.x(q[2]) #input 1 qc.ccx(q[1], q[2],q[3]) # BX qc.cx(q[1], q[2]) # B XOR X qc.ccx(q[0], q[2], q[3]) # A(B XOR X) qc.cx(q[0], q[2]) #2 will be my sum - A XOR B XOR X qc.measure(q[2],c[0]) # SUM - B XOR X XOR A qc.measure(q[3],c[1]) # Carry Out - BX OR A(B XOR X) # execute the circuit by qasm_simulator backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) #new_circuit.draw(output='mpl') new_circuit.count_ops() # Check your answer using following code from qc_grader import grade_ex1a grade_ex1a(qc) # Submit your answer. You can re-submit at any time. from qc_grader import submit_ex1a submit_ex1a(qc)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# Number of iteration import math import numpy as np def num_iter(n): res = ((np.pi/4) * (math.sqrt(n))) - (1/2) iter_list = ['N:'+str(n), 'Number of iteration:'+ str(res)] return iter_list for i in range(16): n = 2**i print(num_iter(n)) # importing Qiskit from qiskit import Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.aer import QasmSimulator backend = Aer.get_backend('qasm_simulator') prob_of_ans = [] for x in range(15): database = QuantumRegister(7) oracle = QuantumRegister(1) ancilla = QuantumRegister(5) cr = ClassicalRegister(7) qc = QuantumCircuit(database, oracle, ancilla, cr) qc.h(database[:]) qc.x(oracle[0]) qc.h(oracle[0]) for j in range(x): # oracle_7q # search 47: 0101111 qc.x(database[0]) qc.x(database[2]) qc.mct(database[:], oracle[0], ancilla[:], mode='basic') qc.x(database[0]) qc.x(database[2]) # diffusion_7q qc.h(database[:]) qc.x(database[:]) qc.h(database[6]) qc.mct(database[0:6], database[6], ancilla[:], mode='basic') qc.h(database[6]) qc.x(database[:]) qc.h(database[:]) qc.h(oracle[0]) qc.x(oracle[0]) qc.measure(database,cr) # Change the endian qc = qc.reverse_bits() job = execute(qc, backend=backend, shots=1000, backend_options={"fusion_enable":True}) result = job.result() count = result.get_counts() answer = count['0101111'] prob_of_ans.append(answer) import matplotlib.pyplot as plt iteration = [i for i in range(15)] plt.bar(iteration, prob_of_ans) plt.xlabel('# of iteration') plt.ylabel('# of times the solution was obtained')
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from IPython.display import Image, display Image('lights_out_prob.png') Image('lights_out_circuit.jpg') from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister tile = QuantumRegister(9) flip = QuantumRegister(9) oracle = QuantumRegister(1) auxiliary = QuantumRegister(7) result = ClassicalRegister(9) #26 qubit qc = QuantumCircuit(tile, flip, oracle, auxiliary, result) lights = [0, 1, 1, 1, 0, 0, 1, 1, 1] def map_board(lights, qc, qr): j = 0 for i in lights: if i==1: qc.x(qr[j]) j+=1 else: j+=1 def initialize(): map_board(lights, qc, tile) qc.h(flip[0:10]) qc.x(oracle[0]) qc.h(oracle[0]) # Subroutine for oracle # Calculate what the light state will be after pressing each solution candidate. def flip_tile(qc,flip,tile): qc.cx(flip[0], tile[0]) qc.cx(flip[0], tile[1]) qc.cx(flip[0], tile[3]) qc.cx(flip[1], tile[0]) qc.cx(flip[1], tile[1]) qc.cx(flip[1], tile[2]) qc.cx(flip[1], tile[4]) qc.cx(flip[2], tile[1]) qc.cx(flip[2], tile[2]) qc.cx(flip[2], tile[5]) qc.cx(flip[3], tile[0]) qc.cx(flip[3], tile[3]) qc.cx(flip[3], tile[4]) qc.cx(flip[3], tile[6]) qc.cx(flip[4], tile[1]) qc.cx(flip[4], tile[3]) qc.cx(flip[4], tile[4]) qc.cx(flip[4], tile[5]) qc.cx(flip[4], tile[7]) qc.cx(flip[5], tile[2]) qc.cx(flip[5], tile[4]) qc.cx(flip[5], tile[5]) qc.cx(flip[5], tile[8]) qc.cx(flip[6], tile[3]) qc.cx(flip[6], tile[6]) qc.cx(flip[6], tile[7]) qc.cx(flip[7], tile[4]) qc.cx(flip[7], tile[6]) qc.cx(flip[7], tile[7]) qc.cx(flip[7], tile[8]) qc.cx(flip[8], tile[5]) qc.cx(flip[8], tile[7]) qc.cx(flip[8], tile[8]) initialize() for i in range(17): # oracle flip_tile(qc,flip,tile) qc.x(tile[0:9]) qc.mct(tile[0:9], oracle[0], auxiliary[0:7], mode='basic') qc.x(tile[0:9]) flip_tile(qc,flip,tile) # diffusion qc.h(flip) qc.x(flip) qc.h(flip[8]) qc.mct(flip[0:8], flip[8], auxiliary[0:7], mode='basic') qc.h(flip[8]) qc.x(flip) qc.h(flip) # Uncompute qc.h(oracle[0]) qc.x(oracle[0]) # Measuremnt qc.measure(flip,result) # Make the Out put order the same as the input. qc = qc.reverse_bits() from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller # Unroll the circuit pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) # obtain gates gates=new_circuit.count_ops() print(gates) %%time from qiskit import IBMQ, execute provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True}) result = job.result() count = result.get_counts() score_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True) final_score = score_sorted[0:40] final_score Image('lights_out_optimal.png') Image('lights_out_optimal_circuit.jpg') tile = QuantumRegister(9) flip = QuantumRegister(9) oracle = QuantumRegister(1) auxiliary = QuantumRegister(1) result = ClassicalRegister(9) # 20 qubit qc = QuantumCircuit(tile, flip, oracle, auxiliary, result) # Initialize def initialize_smart(l,qc,tile): map_board(l, qc, tile) qc.h(flip[:3]) qc.x(oracle[0]) qc.h(oracle[0]) def flip_1(qc,flip,tile): # push 0 qc.cx(flip[0], tile[0]) qc.cx(flip[0], tile[1]) qc.cx(flip[0], tile[3]) # push 1 qc.cx(flip[1], tile[0]) qc.cx(flip[1], tile[1]) qc.cx(flip[1], tile[2]) qc.cx(flip[1], tile[4]) # push 2 qc.cx(flip[2], tile[1]) qc.cx(flip[2], tile[2]) qc.cx(flip[2], tile[5]) def inv_1(qc,flip,tile): # copy 0,1,2 qc.cx(tile[0], flip[3]) qc.cx(tile[1], flip[4]) qc.cx(tile[2], flip[5]) def flip_2(qc,flip,tile): # apply flip[3,4,5] qc.cx(flip[3], tile[0]) qc.cx(flip[3], tile[3]) qc.cx(flip[3], tile[4]) qc.cx(flip[3], tile[6]) qc.cx(flip[4], tile[1]) qc.cx(flip[4], tile[3]) qc.cx(flip[4], tile[4]) qc.cx(flip[4], tile[5]) qc.cx(flip[4], tile[7]) qc.cx(flip[5], tile[2]) qc.cx(flip[5], tile[4]) qc.cx(flip[5], tile[5]) qc.cx(flip[5], tile[8]) def inv_2(qc,flip,tile1): # copy 3,4,5 qc.cx(tile[3], flip[6]) qc.cx(tile[4], flip[7]) qc.cx(tile[5], flip[8]) def flip_3(qc,flip,tile): qc.cx(flip[6], tile[3]) qc.cx(flip[6], tile[6]) qc.cx(flip[6], tile[7]) qc.cx(flip[7], tile[4]) qc.cx(flip[7], tile[6]) qc.cx(flip[7], tile[7]) qc.cx(flip[7], tile[8]) qc.cx(flip[8], tile[5]) qc.cx(flip[8], tile[7]) qc.cx(flip[8], tile[8]) def lights_out_oracle(qc,tile,oracle,auxiliary): qc.x(tile[6:9]) qc.mct(tile[6:9], oracle[0], auxiliary, mode='basic') qc.x(tile[6:9]) def diffusion(qc,flip): qc.h(flip[:3]) qc.x(flip[:3]) qc.h(flip[2]) qc.ccx(flip[0],flip[1],flip[2]) qc.h(flip[2]) qc.x(flip[:3]) qc.h(flip[:3]) initialize_smart(lights,qc,tile) for i in range(2): flip_1(qc,flip,tile) inv_1(qc,flip,tile) flip_2(qc,flip,tile) inv_2(qc,flip,tile) flip_3(qc,flip,tile) lights_out_oracle(qc,tile,oracle,auxiliary) flip_3(qc,flip,tile) inv_2(qc,flip,tile) flip_2(qc,flip,tile) inv_1(qc,flip,tile) flip_1(qc,flip,tile) diffusion(qc,flip) # Uncompute qc.h(oracle[0]) qc.x(oracle[0]) # get the whole solution from the top row of the solution # If you get a solution, you don't need to erase the board, so you don't need the flip_3 function. flip_1(qc,flip,tile) inv_1(qc,flip,tile) flip_2(qc,flip,tile) inv_2(qc,flip,tile) # Measuremnt qc.measure(flip,result) # Make the Out put order the same as the input. qc = qc.reverse_bits() # Unroll the circuit pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) # obtain gates gates=new_circuit.count_ops() print(gates) %%time backend = provider.get_backend('ibmq_qasm_simulator') job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True}) result = job.result() count = result.get_counts() score_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True) final_score = score_sorted[0:40] final_score
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from IPython.display import Image, display Image("ryoko.png", width="70") from IPython.display import Image, display Image('4lightsout_ex.png') from qiskit import * from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute provider = IBMQ.load_account() address = QuantumRegister(2) data = QuantumRegister(3) c = ClassicalRegister(5) qc = QuantumCircuit(address,data,c) # address preparation qc.h([address[0],address[1]]) qc.barrier() # address 0 -> data = 1 qc.x([address[0],address[1]]) qc.ccx(address[0],address[1],data[2]) qc.x([address[0],address[1]]) qc.barrier() # address 1 -> data = 2 qc.x(address[0]) qc.ccx(address[0],address[1],data[1]) qc.x(address[0]) qc.barrier() # address 2 -> data = 5 qc.x(address[1]) qc.ccx(address[0],address[1],data[2]) qc.ccx(address[0],address[1],data[0]) qc.x(address[1]) qc.barrier() # address 3 -> data = 7 qc.ccx(address[0],address[1],data[2]) qc.ccx(address[0],address[1],data[1]) qc.ccx(address[0],address[1],data[0]) qc.barrier() #Check the qRAM status qc.measure(address[0:2], c[0:2]) qc.measure(data[0:3], c[2:5]) # Reverse the output string. qc = qc.reverse_bits() #backend = provider.get_backend('ibmq_qasm_simulator') backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True}) #job = execute(qc, backend=backend, shots=8192) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') Image('circuit_ex.png') Image('gatesynthesis_ex.png') Image('4lightsout_pr.png') lightsout4=[[1, 1, 1, 0, 0, 0, 1, 0, 0],[1, 0, 1, 0, 0, 0, 1, 1, 0],[1, 0, 1, 1, 1, 1, 0, 0, 1],[1, 0, 0, 0, 0, 0, 1, 0, 0]] import numpy as np # import qiskit libraries from qiskit import IBMQ, Aer,QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.tools.jupyter import * provider = IBMQ.load_account() #import functions to plot from qiskit.visualization import plot_histogram def week2b_ans_func(lightout4): ##### Build your cirucuit here def qRAM(qc, add, board, lightout4): # Board 1 qc.x(add[0]) qc.x(add[1]) for i, curr_light in enumerate(lightout4[0]): if curr_light == 1: qc.ccx(add[0], add[1], board[i]) #qc.ch(q[0], q[3]) #qc.cz(q[2], q[3]) #qc.ch(q[0], q[3]) qc.x(add[0]) qc.x(add[1]) qc.barrier() # Board 2 qc.x(add[0]) for i, curr_light in enumerate(lightout4[1]): if curr_light == 1: qc.ccx(add[0], add[1], board[i]) qc.x(add[0]) qc.barrier() # Board 3 qc.x(add[1]) for i, curr_light in enumerate(lightout4[2]): if curr_light == 1: qc.ccx(add[0], add[1], board[i]) qc.x(add[1]) qc.barrier() # Board 4 for i, curr_light in enumerate(lightout4[3]): if curr_light == 1: qc.ccx(add[0], add[1], board[i]) qc.barrier() def diffuser(nqubits): qc_diff = QuantumCircuit(nqubits) for qubit in range(nqubits): qc_diff.h(qubit) for qubit in range(nqubits): qc_diff.x(qubit) qc_diff.h(nqubits-1) qc_diff.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc_diff.h(nqubits-1) for qubit in range(nqubits): qc_diff.x(qubit) for qubit in range(nqubits): qc_diff.h(qubit) U_f0 = qc_diff.to_gate() U_f0.name = "V" return U_f0 def lights_oracle(sol, board, anc, orc_out_2a): #board_oracle = QuantumRegister(n, 'board') #sol = QuantumRegister(n, 'solution') #orc_out_2a = QuantumRegister(1, 'oracle_out_2a') #this has to be phase flipped qc_1 = QuantumCircuit(sol, board, anc, orc_out_2a) flip_matrix = [[1,1,0,1,0,0,0,0,0], [1,1,1,0,1,0,0,0,0], [0,1,1,0,0,1,0,0,0], [1,0,0,1,1,0,1,0,0], [0,1,0,1,1,1,0,1,0], [0,0,1,0,1,1,0,0,1], [0,0,0,1,0,0,1,1,0], [0,0,0,0,1,0,1,1,1], [0,0,0,0,0,1,0,1,1]] qc_1.barrier() for sol_bit in range(len(flip_matrix)): for board_bit in range(len(flip_matrix[sol_bit])): if flip_matrix[sol_bit][board_bit] == 1: qc_1.cx(sol[sol_bit], board[board_bit]) qc_1.barrier() for i in range(len(flip_matrix)): qc_1.x(board[i]) qc_1.barrier() qc_1.ccx(board[0], board[1], anc[0]) qc_1.ccx(board[2], board[3], anc[1]) qc_1.ccx(anc[0], anc[1], anc[2]) qc_1.ccx(board[4], board[5], anc[3]) qc_1.ccx(board[6], board[7], anc[4]) qc_1.ccx(anc[3], anc[4], anc[5]) qc_1.mct([board[8], anc[2], anc[5]], orc_out_2a, mode = 'noancilla') qc_1.ccx(anc[3], anc[4], anc[5]) qc_1.ccx(board[6], board[7], anc[4]) qc_1.ccx(board[4], board[5], anc[3]) qc_1.ccx(anc[0], anc[1], anc[2]) qc_1.ccx(board[2], board[3], anc[1]) qc_1.ccx(board[0], board[1], anc[0]) #qc_1.mct([board[0], board[1],board[2],board[3],board[4],board[5],board[6],board[7],board[8]], # orc_out_2a, #[anc[0], anc[1],anc[2],anc[3],anc[4],anc[5],anc[6]], # mode='noancilla') qc_1.barrier() for i in range(len(flip_matrix)): qc_1.x(board[i]) qc_1.barrier() for sol_bit in range(len(flip_matrix)): for board_bit in range(len(flip_matrix[sol_bit])): if flip_matrix[sol_bit][board_bit] == 1: qc_1.cx(sol[sol_bit], board[board_bit]) return qc_1 def new_u2a(qc, sol, board, anc, orc_out_2a): r_2a = 1 flip_matrix = [[1,1,0,1,0,0,0,0,0], [1,1,1,0,1,0,0,0,0], [0,1,1,0,0,1,0,0,0], [1,0,0,1,1,0,1,0,0], [0,1,0,1,1,1,0,1,0], [0,0,1,0,1,1,0,0,1], [0,0,0,1,0,0,1,1,0], [0,0,0,0,1,0,1,1,1], [0,0,0,0,0,1,0,1,1]] n =len(flip_matrix) for i_2a in range(r_2a): qc.extend(lights_oracle(sol, board, anc, orc_out_2a)) qc.barrier() qc.append(diffuser(n), sol) qc.barrier() def new_u2a_dagger(qc, sol, board, anc, orc_out_2a): r_2a = 1 flip_matrix = [[1,1,0,1,0,0,0,0,0], [1,1,1,0,1,0,0,0,0], [0,1,1,0,0,1,0,0,0], [1,0,0,1,1,0,1,0,0], [0,1,0,1,1,1,0,1,0], [0,0,1,0,1,1,0,0,1], [0,0,0,1,0,0,1,1,0], [0,0,0,0,1,0,1,1,1], [0,0,0,0,0,1,0,1,1]] n =len(flip_matrix) for i_2a in range(r_2a): qc.barrier() qc.append(diffuser(n), sol) qc.barrier() orc_org = lights_oracle(sol, board, anc, orc_out_2a) qc.extend(orc_org.inverse()) def bitcounter(qc, sol, anc): for i in range(len(sol)): qc.mct([sol[i], anc[0], anc[1], anc[2]], anc[3], mode = 'noancilla') qc.mct([sol[i], anc[0], anc[1]], anc[2], mode = 'noancilla') qc.ccx(sol[i], anc[0], anc[1]) qc.cx(sol[i], anc[0]) def bitcounter_uncompute(qc, sol, anc): for i in range(len(sol)): qc.cx(sol[i], anc[0]) qc.ccx(sol[i], anc[0], anc[1]) qc.mct([sol[i], anc[0], anc[1]], anc[2], mode = 'noancilla') qc.mct([sol[i], anc[0], anc[1], anc[2]], anc[3], mode = 'noancilla') def oracle_2b(qc, add, board, sol, anc, orc_out_2a, orc_out_2b, lightout4): #apply QRAM qRAM(qc, add, board, lightout4) #apply U_2A new_u2a(qc, sol, board, anc, orc_out_2a) #counter #qc.append(WeightedAdder(9), sol+anc) bitcounter(qc, sol, anc) #verifying that the count is less than 3 qc.x(anc[2]) qc.x(anc[3]) qc.ccx(anc[2], anc[3], orc_out_2b) qc.x(anc[2]) qc.x(anc[3]) bitcounter_uncompute(qc, sol, anc) #apply U_2a_dagger new_u2a_dagger(qc, sol, board, anc, orc_out_2a) #apply qRAM dagger - same as qRAM qRAM(qc, add, board, lightout4) # start building the circuit n = len(lightout4[0]) add = QuantumRegister(2, 'address') board = QuantumRegister(n, 'board') sol = QuantumRegister(n, 'solution') anc = QuantumRegister(6, 'anc') orc_out_2a = QuantumRegister(1, 'oracle_out_2a') orc_out_2b = QuantumRegister(1, 'oracle_out_2b') c_out = ClassicalRegister(2, 'classical_bits') qc = QuantumCircuit(add, board, sol, orc_out_2a, anc, orc_out_2b, c_out) qc.h(add) qc.h(sol) qc.x(orc_out_2a) qc.h(orc_out_2a) qc.x(orc_out_2b) qc.h(orc_out_2b) qc.barrier() r_2b = 2 for i_2b in range(r_2b): oracle_2b(qc, add, board, sol, anc, orc_out_2a, orc_out_2b, lightout4) qc.barrier() qc.append(diffuser(2), add) qc.barrier() qc.measure(add, c_out) qc = qc.reverse_bits() #### In addition, please make sure your function can solve the problem with different inputs (lightout4). We will cross validate with different inputs. return qc # Submission code from qc_grader import prepare_ex2b, grade_ex2b, submit_ex2b # Execute your circuit with following prepare_ex2b() function. # The prepare_ex2b() function works like the execute() function with only QuantumCircuit as an argument. job = prepare_ex2b(week2b_ans_func) result = job.result() count = result.get_counts() original_problem_set_counts = count[0] original_problem_set_counts # The bit string with the highest number of observations is treated as the solution. # Check your answer by executing following code. # The quantum cost of the QuantumCircuit is obtained as the score. The quantum cost is related to rank only in the third week. grade_ex2b(job) # Submit your results by executing following code. You can submit as many times as you like during the period. submit_ex2b(job)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from IPython.display import Image, display Image("ryoko.png", width="70") Image('asteroids_example.png') Image('asteroids_beam_example.png') Image('false_asteroids_example.png') Image('asteroids_example.png') problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] import numpy as np # import qiskit libraries from qiskit import IBMQ, Aer,QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.tools.jupyter import * from qiskit.circuit.library import OR as or_gate provider = IBMQ.load_account() #import functions to plot from qiskit.visualization import plot_histogram def week3_ans_func(problem_set): ##### build your quantum circuit here ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. def qRAM(qc,add,data, auxiliary, problem_set): problem_set_mapping_dict = {'0' : {'0': 0, '1': 1, '2': 2, '3':3}, '1' : {'0': 4, '1': 5, '2': 6, '3':7}, '2' : {'0': 8, '1': 9, '2': 10, '3':11}, '3' : {'0': 12, '1': 13, '2': 14, '3':15}} for ind in range(len(data)): binary = f'{ind:04b}' if(binary[0] == '0'): qc.x(add[0]) if(binary[1] == '0'): qc.x(add[1]) if(binary[2] == '0'): qc.x(add[2]) if(binary[3] == '0'): qc.x(add[3]) for i, edg in enumerate(problem_set[ind]): qc.ch(add[0],auxiliary[0]) qc.cz(add[1],auxiliary[0]) qc.ch(add[0], auxiliary[0]) #qc.ccx(add[0], add[1], auxiliary[0]) qc.ch(add[2],auxiliary[1]) qc.cz(add[3],auxiliary[1]) qc.ch(add[2], auxiliary[1]) #qc.ccx(add[2], add[3], auxiliary[1]) qc.ch(auxiliary[0],auxiliary[2]) qc.cz(auxiliary[1],auxiliary[2]) qc.ch(auxiliary[0],auxiliary[2]) #qc.ccx(auxiliary[0], auxiliary[1], auxiliary[2]) qc.cx(auxiliary[2], data[problem_set_mapping_dict[edg[0]][edg[1]]]) qc.ch(auxiliary[0],auxiliary[2]) qc.cz(auxiliary[1],auxiliary[2]) qc.ch(auxiliary[0],auxiliary[2]) qc.ch(add[2],auxiliary[1]) qc.cz(add[3],auxiliary[1]) qc.ch(add[2], auxiliary[1]) qc.ch(add[0],auxiliary[0]) qc.cz(add[1],auxiliary[0]) qc.ch(add[0], auxiliary[0]) if(binary[0] == '0'): qc.x(add[0]) if(binary[1] == '0'): qc.x(add[1]) if(binary[2] == '0'): qc.x(add[2]) if(binary[3] == '0'): qc.x(add[3]) qc.barrier() def diffuser(nqubits): qc_diff = QuantumCircuit(nqubits) for qubit in range(nqubits): qc_diff.h(qubit) for qubit in range(nqubits): qc_diff.x(qubit) qc_diff.h(nqubits-1) qc_diff.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc_diff.h(nqubits-1) for qubit in range(nqubits): qc_diff.x(qubit) for qubit in range(nqubits): qc_diff.h(qubit) U_f0 = qc_diff.to_gate() U_f0.name = "V" return U_f0 def add_row_counters(qc, data, auxiliary): row_mat = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]] for i, curr_row in enumerate(row_mat): flag_list = [0] * len(data) for curr_flag_index in range(len(data)): if curr_flag_index in curr_row: flag_list[curr_flag_index] = 1 qc.append(or_gate(len(data), flag_list, mcx_mode='noancilla'), [*data, auxiliary[i]]) def add_column_counters(qc, data, auxiliary): col_mat = [[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]] for i, curr_col in enumerate(col_mat): flag_list = [0] * len(data) for curr_flag_index in range(len(data)): if curr_flag_index in curr_col: flag_list[curr_flag_index] = 1 qc.append(or_gate(len(data), flag_list, mcx_mode='noancilla'), [*data, auxiliary[i]]) def add_lone_counters(qc, data, auxiliary, count_out): lone_mat = [[0, 1, 2, 3, 4, 8, 12], [1, 0, 2, 3, 5, 9, 13], [2, 0, 1, 3, 6, 10, 14], [3, 0, 1, 2, 7, 11, 15], [4, 5, 6, 7, 0, 8, 12], [5, 4, 6, 7, 1, 9, 13], [6, 4, 5, 7, 2, 10, 14], [7, 4, 5, 6, 3, 11, 15], [8, 9, 10, 11, 0, 4, 12], [9, 8, 10, 11, 1, 5, 13], [10, 8, 9, 11, 2, 6, 14], [11, 8, 9, 10, 3, 7, 15], [12, 13, 14, 15, 0, 4, 8], [13, 12, 14, 15, 1, 5, 9], [14, 12, 13, 15, 2, 6, 10], [15, 12, 13, 14, 3, 7, 11]] qc.barrier() #curr_lone_row = [0, 1, 2, 3, 4, 8, 12] for curr_lone_row in lone_mat: n = len(curr_lone_row) for j in range(1,n): qc.x(data[curr_lone_row[j]]) qc.ch(data[curr_lone_row[0]], auxiliary[0]) qc.cz(data[curr_lone_row[1]], auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) #qc.ccx(data[curr_lone_row[0]], data[curr_lone_row[1]], auxiliary[0]) qc.ch(data[curr_lone_row[2]],auxiliary[1]) qc.cz(data[curr_lone_row[3]],auxiliary[1]) qc.ch(data[curr_lone_row[2]],auxiliary[1]) #qc.ccx(data[curr_lone_row[2]], data[curr_lone_row[3]], auxiliary[1]) qc.ch(auxiliary[0],auxiliary[2]) qc.cz(auxiliary[1],auxiliary[2]) qc.ch(auxiliary[0],auxiliary[2]) #qc.ccx(auxiliary[0], auxiliary[1], auxiliary[2]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) qc.cz(data[curr_lone_row[1]],auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) #qc.ccx(data[curr_lone_row[0]], data[curr_lone_row[1]], auxiliary[0]) qc.ch(data[curr_lone_row[4]],auxiliary[0]) qc.cz(data[curr_lone_row[5]],auxiliary[0]) qc.ch(data[curr_lone_row[4]],auxiliary[0]) #qc.ccx(data[curr_lone_row[4]], data[curr_lone_row[5]], auxiliary[0]) qc.ch(auxiliary[0],auxiliary[3]) qc.cz(auxiliary[2],auxiliary[3]) qc.ch(auxiliary[0],auxiliary[3]) #qc.ccx(auxiliary[0], auxiliary[2], auxiliary[3]) #------------------------------------------------------------------------------------------------------------------------ #qc.ch(data[curr_lone_row[6]], count_out[2]) #qc.cz(auxiliary[3],count_out[2]) #qc.ch(data[curr_lone_row[2]],count_out[2]) qc.ccx(data[curr_lone_row[6]], auxiliary[3], count_out[2]) #this CCX is important to avoid #unnecessary addition of relative phase #------------------------------------------------------------------------------------------------------------------------ qc.ch(auxiliary[0],auxiliary[3]) qc.cz(auxiliary[2],auxiliary[3]) qc.ch(auxiliary[0],auxiliary[3]) qc.ch(data[curr_lone_row[4]],auxiliary[0]) qc.cz(data[curr_lone_row[5]],auxiliary[0]) qc.ch(data[curr_lone_row[4]],auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) qc.cz(data[curr_lone_row[1]],auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) qc.ch(auxiliary[0],auxiliary[2]) qc.cz(auxiliary[1],auxiliary[2]) qc.ch(auxiliary[0],auxiliary[2]) qc.ch(data[curr_lone_row[2]],auxiliary[1]) qc.cz(data[curr_lone_row[3]],auxiliary[1]) qc.ch(data[curr_lone_row[2]],auxiliary[1]) qc.ch(data[curr_lone_row[0]], auxiliary[0]) qc.cz(data[curr_lone_row[1]], auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) for j in range(1,n): qc.x(data[curr_lone_row[j]]) qc.barrier def u3a(data, auxiliary,oracle, count_out): qc_1 = QuantumCircuit(data, auxiliary,oracle, count_out) #Oracle ----------------------------------------------- #Adding Row counters to check if each row has at least 1 asteroid and then flipping a count_out bit if all rows has at least one asteroid add_row_counters(qc_1, data, auxiliary) #compute qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[0], mode = 'noancilla') add_row_counters(qc_1, data, auxiliary) #uncompute #Adding column counters to check if each column has at least 1 asteroid and then flipping a count_out bit if all columns has at least one asteroid add_column_counters(qc_1, data, auxiliary) #compute qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[1], mode = 'noancilla') add_column_counters(qc_1, data, auxiliary) #uncompute #qc_1.barrier() #lone asteroid counter circuit to add add_lone_counters(qc_1, data, auxiliary, count_out) return qc_1 def u3a_dagger(data, auxiliary, oracle, count_out): qc_1 = QuantumCircuit(data, auxiliary,oracle, count_out) #Oracle ----------------------------------------------- #Adding Row counters to check if each row has at least 1 asteroid and then flipping a count_out bit if all rows has at least one asteroid add_row_counters(qc_1, data, auxiliary) #compute qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[0], mode = 'noancilla') add_row_counters(qc_1, data, auxiliary) #uncompute #Adding column counters to check if each column has at least 1 asteroid and then flipping a count_out bit if all columns has at least one asteroid add_column_counters(qc_1, data, auxiliary) #compute qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[1], mode = 'noancilla') add_column_counters(qc_1, data, auxiliary) #uncompute #qc_1.barrier() #lone asteroid counter circuit to add add_lone_counters(qc_1, data, auxiliary, count_out) qc_2 = qc_1.inverse() return qc_2 add = QuantumRegister(4, name = 'address') data = QuantumRegister(16, name = 'data') auxiliary = QuantumRegister(4, name = 'auxiliary') count_out = QuantumRegister(3, name = 'counter_outputs') oracle = QuantumRegister(1, name = 'oracle') cbits = ClassicalRegister(4, name = 'solution') qc = QuantumCircuit(add, data, auxiliary,oracle, count_out, cbits) qc.x(oracle) qc.h(oracle) qc.h(add) qc.barrier() #Add qRAM qRAM(qc,add,data, auxiliary, problem_set) #compute qc.barrier() # counters qc.extend(u3a(data, auxiliary,oracle, count_out)) qc.barrier() # Phase flipping oracle #qc.cx(auxiliary[6], oracle) qc.mct([count_out[0], count_out[1], count_out[2]], oracle, mode = 'noancilla') # ------------------------------------------------------- # counters - dagger qc.extend(u3a_dagger(data, auxiliary,oracle, count_out)) qc.barrier() #qRAM qc.barrier() qRAM(qc,add,data, auxiliary, problem_set) #uncompute qc.barrier() #diffuser qc.append(diffuser(4), add) qc.barrier() #measure qc.measure(add[0], cbits[0]) qc.measure(add[1], cbits[1]) qc.measure(add[2], cbits[2]) qc.measure(add[3], cbits[3]) return qc # Submission code from qc_grader import grade_ex3, prepare_ex3, submit_ex3 # Execute your circuit with following prepare_ex3() function. # The prepare_ex3() function works like the execute() function with only QuantumCircuit as an argument. job = prepare_ex3(week3_ans_func) result = job.result() counts = result.get_counts() original_problem_set_counts = counts[0] original_problem_set_counts # The bit string with the highest number of observations is treated as the solution. # Check your answer by executing following code. # The quantum cost of the QuantumCircuit is obtained as the score. The lower the cost, the better. grade_ex3(job) # Submit your results by executing following code. You can submit as many times as you like during the period. submit_ex3(job)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
#Let us begin by importing necessary libraries. from qiskit import Aer from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import * from qiskit.circuit.library import TwoLocal from qiskit.utils import QuantumInstance from qiskit.utils import algorithm_globals from qiskit_finance import QiskitFinanceError from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import * from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_optimization.applications import OptimizationApplication from qiskit_optimization.converters import QuadraticProgramToQubo import numpy as np import matplotlib.pyplot as plt %matplotlib inline import datetime import warnings from sympy.utilities.exceptions import SymPyDeprecationWarning warnings.simplefilter("ignore", SymPyDeprecationWarning) # Set parameters for assets and risk factor num_assets = 4 # set number of assets to 4 q = 0.5 # set risk factor to 0.5 budget = 2 # set budget as defined in the problem seed = 132 # set random seed # Generate time series data stocks = [("STOCK%s" % i) for i in range(num_assets)] data = RandomDataProvider(tickers=stocks, start=datetime.datetime(1955,11,5), end=datetime.datetime(1985,10,26), seed=seed) data.run() # Let's plot our finanical data for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.xlabel('days') plt.ylabel('stock value') plt.show() #Let's calculate the expected return for our problem data mu = data.get_period_return_mean_vector() # Returns a vector containing the mean value of each asset's expected return. print(mu) # Let's plot our covariance matrix Σ(sigma) sigma = data.get_period_return_covariance_matrix() #Returns the covariance matrix of the four assets print(sigma) fig, ax = plt.subplots(1,1) im = plt.imshow(sigma, extent=[-1,1,-1,1]) x_label_list = ['stock3', 'stock2', 'stock1', 'stock0'] y_label_list = ['stock3', 'stock2', 'stock1', 'stock0'] ax.set_xticks([-0.75,-0.25,0.25,0.75]) ax.set_yticks([0.75,0.25,-0.25,-0.75]) ax.set_xticklabels(x_label_list) ax.set_yticklabels(y_label_list) plt.colorbar() plt.clim(-0.000002, 0.00001) plt.show() ############################## # Provide your code here portfolio = qp = ############################## print(qp) # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex1a grade_ex1a(qp) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print(result) optimizer = SLSQP(maxiter=1000) algorithm_globals.random_seed = 1234 backend = Aer.get_backend('statevector_simulator') ############################## # Provide your code here vqe = ############################## vqe_meo = MinimumEigenOptimizer(vqe) #please do not change this code result = vqe_meo.solve(qp) #please do not change this code print(result) #please do not change this code # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex1b grade_ex1b(vqe, qp) #Step 1: Let us begin by importing necessary libraries import qiskit from qiskit import Aer from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import * from qiskit.circuit.library import TwoLocal from qiskit.utils import QuantumInstance from qiskit.utils import algorithm_globals from qiskit_finance import QiskitFinanceError from qiskit_finance.applications.optimization import * from qiskit_finance.data_providers import * from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_optimization.applications import OptimizationApplication from qiskit_optimization.converters import QuadraticProgramToQubo import numpy as np import matplotlib.pyplot as plt %matplotlib inline import datetime import warnings from sympy.utilities.exceptions import SymPyDeprecationWarning warnings.simplefilter("ignore",SymPyDeprecationWarning) # Step 2. Generate time series data for four assets. # Do not change start/end dates specified to generate problem data. seed = 132 num_assets = 4 stocks = [("STOCK%s" % i) for i in range(num_assets)] data = RandomDataProvider(tickers=stocks, start=datetime.datetime(1955,11,5), end=datetime.datetime(1985,10,26), seed=seed) data.run() # Let's plot our finanical data (We are generating the same time series data as in the previous example.) for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.xlabel('days') plt.ylabel('stock value') plt.show() # Step 3. Calculate mu and sigma for this problem mu2 = data.get_period_return_mean_vector() #Returns a vector containing the mean value of each asset. sigma2 = data.get_period_return_covariance_matrix() #Returns the covariance matrix associated with the assets. print(mu2, sigma2) # Step 4. Set parameters and constraints based on this challenge 1c ############################## # Provide your code here q2 = #Set risk factor to 0.5 budget2 = #Set budget to 3 ############################## # Step 5. Complete code to generate the portfolio instance ############################## # Provide your code here portfolio2 = qp2 = ############################## # Step 6. Now let's use QAOA to solve this problem. optimizer = SLSQP(maxiter=1000) algorithm_globals.random_seed = 1234 backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed) ############################## # Provide your code here qaoa = ############################## qaoa_meo = MinimumEigenOptimizer(qaoa) #please do not change this code result2 = qaoa_meo.solve(qp2) #please do not change this code print(result2) #please do not change this code # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex1c grade_ex1c(qaoa, qp2)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver # PSPCz molecule geometry = [['C', [ -0.2316640, 1.1348450, 0.6956120]], ['C', [ -0.8886300, 0.3253780, -0.2344140]], ['C', [ -0.1842470, -0.1935670, -1.3239330]], ['C', [ 1.1662930, 0.0801450, -1.4737160]], ['C', [ 1.8089230, 0.8832220, -0.5383540]], ['C', [ 1.1155860, 1.4218050, 0.5392780]], ['S', [ 3.5450920, 1.2449890, -0.7349240]], ['O', [ 3.8606900, 1.0881590, -2.1541690]], ['C', [ 4.3889120, -0.0620730, 0.1436780]], ['O', [ 3.8088290, 2.4916780, -0.0174650]], ['C', [ 4.6830900, 0.1064460, 1.4918230]], ['C', [ 5.3364470, -0.9144080, 2.1705280]], ['C', [ 5.6895490, -2.0818670, 1.5007820]], ['C', [ 5.4000540, -2.2323130, 0.1481350]], ['C', [ 4.7467230, -1.2180160, -0.5404770]], ['N', [ -2.2589180, 0.0399120, -0.0793330]], ['C', [ -2.8394600, -1.2343990, -0.1494160]], ['C', [ -4.2635450, -1.0769890, 0.0660760]], ['C', [ -4.5212550, 0.2638010, 0.2662190]], ['C', [ -3.2669630, 0.9823890, 0.1722720]], ['C', [ -2.2678900, -2.4598950, -0.3287380]], ['C', [ -3.1299420, -3.6058560, -0.3236210]], ['C', [ -4.5179520, -3.4797390, -0.1395160]], ['C', [ -5.1056310, -2.2512990, 0.0536940]], ['C', [ -5.7352450, 1.0074800, 0.5140960]], ['C', [ -5.6563790, 2.3761270, 0.6274610]], ['C', [ -4.4287740, 3.0501460, 0.5083650]], ['C', [ -3.2040560, 2.3409470, 0.2746950]], ['H', [ -0.7813570, 1.5286610, 1.5426490]], ['H', [ -0.7079140, -0.7911480, -2.0611600]], ['H', [ 1.7161320, -0.2933710, -2.3302930]], ['H', [ 1.6308220, 2.0660550, 1.2427990]], ['H', [ 4.4214900, 1.0345500, 1.9875450]], ['H', [ 5.5773000, -0.7951290, 3.2218590]], ['H', [ 6.2017810, -2.8762260, 2.0345740]], ['H', [ 5.6906680, -3.1381740, -0.3739110]], ['H', [ 4.5337010, -1.3031330, -1.6001680]], ['H', [ -1.1998460, -2.5827750, -0.4596910]], ['H', [ -2.6937370, -4.5881470, -0.4657540]], ['H', [ -5.1332290, -4.3740010, -0.1501080]], ['H', [ -6.1752900, -2.1516170, 0.1987120]], ['H', [ -6.6812260, 0.4853900, 0.6017680]], ['H', [ -6.5574610, 2.9529350, 0.8109620]], ['H', [ -4.3980410, 4.1305040, 0.5929440]], ['H', [ -2.2726630, 2.8838620, 0.1712760]]] molecule = Molecule(geometry=geometry, charge=0, multiplicity=1) driver = ElectronicStructureMoleculeDriver(molecule=molecule, basis='631g*', driver_type=ElectronicStructureDriverType.PYSCF) num_ao = { 'C': 14, 'H': 2, 'N': 14, 'O': 14, 'S': 18, } ############################## # Provide your code here num_C_atom = num_H_atom = num_N_atom = num_O_atom = num_S_atom = num_atoms_total = num_AO_total = num_MO_total = ############################## answer_ex2a ={ 'C': num_C_atom, 'H': num_H_atom, 'N': num_N_atom, 'O': num_O_atom, 'S': num_S_atom, 'atoms': num_atoms_total, 'AOs': num_AO_total, 'MOs': num_MO_total } print(answer_ex2a) # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex2a grade_ex2a(answer_ex2a) from qiskit_nature.drivers.second_quantization import HDF5Driver driver_reduced = HDF5Driver("resources/PSPCz_reduced.hdf5") properties = driver_reduced.run() from qiskit_nature.properties.second_quantization.electronic import ElectronicEnergy electronic_energy = properties.get_property(ElectronicEnergy) print(electronic_energy) from qiskit_nature.properties.second_quantization.electronic import ParticleNumber ############################## # Provide your code here particle_number = num_electron = num_MO = num_SO = num_qubits = ############################## answer_ex2b = { 'electrons': num_electron, 'MOs': num_MO, 'SOs': num_SO, 'qubits': num_qubits } print(answer_ex2b) # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex2b grade_ex2b(answer_ex2b) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem ############################## # Provide your code here es_problem = ############################## second_q_op = es_problem.second_q_ops() print(second_q_op[0]) from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper, ParityMapper, BravyiKitaevMapper ############################## # Provide your code here qubit_converter = ############################## qubit_op = qubit_converter.convert(second_q_op[0]) print(qubit_op) from qiskit_nature.circuit.library import HartreeFock ############################## # Provide your code here init_state = ############################## init_state.draw() from qiskit.circuit.library import EfficientSU2, TwoLocal, NLocal, PauliTwoDesign from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD ############################## # Provide your code here ansatz = ############################## ansatz.decompose().draw() from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_nature.algorithms import GroundStateEigensolver ############################## # Provide your code here numpy_solver = numpy_ground_state_solver = numpy_results = ############################## exact_energy = numpy_results.computed_energies[0] print(f"Exact electronic energy: {exact_energy:.6f} Hartree\n") print(numpy_results) # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex2c grade_ex2c(numpy_results) from qiskit.providers.aer import StatevectorSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP ############################## # Provide your code here backend = optimizer = ############################## from qiskit.algorithms import VQE from qiskit_nature.algorithms import VQEUCCFactory, GroundStateEigensolver from jupyterplot import ProgressPlot import numpy as np error_threshold = 10 # mHartree np.random.seed(5) # fix seed for reproducibility initial_point = np.random.random(ansatz.num_parameters) # for live plotting pp = ProgressPlot(plot_names=['Energy'], line_names=['Runtime VQE', f'Target + {error_threshold}mH', 'Target']) intermediate_info = { 'nfev': [], 'parameters': [], 'energy': [], 'stddev': [] } def callback(nfev, parameters, energy, stddev): intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['energy'].append(energy) intermediate_info['stddev'].append(stddev) pp.update([[energy, exact_energy+error_threshold/1000, exact_energy]]) ############################## # Provide your code here vqe = vqe_ground_state_solver = vqe_results = ############################## print(vqe_results) error = (vqe_results.computed_energies[0] - exact_energy) * 1000 # mHartree print(f'Error is: {error:.3f} mHartree') # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex2d grade_ex2d(vqe_results) from qiskit_nature.algorithms import QEOM ############################## # Provide your code here qeom_excited_state_solver = qeom_results = ############################## print(qeom_results) # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex2e grade_ex2e(qeom_results) bandgap = qeom_results.computed_energies[1] - qeom_results.computed_energies[0] bandgap # in Hartree from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-education', group='ibm-4', project='qiskit-hackathon') backend = provider.get_backend('ibmq_qasm_simulator') backend from qiskit_nature.runtime import VQEProgram error_threshold = 10 # mHartree # for live plotting pp = ProgressPlot(plot_names=['Energy'], line_names=['Runtime VQE', f'Target + {error_threshold}mH', 'Target']) intermediate_info = { 'nfev': [], 'parameters': [], 'energy': [], 'stddev': [] } def callback(nfev, parameters, energy, stddev): intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['energy'].append(energy) intermediate_info['stddev'].append(stddev) pp.update([[energy,exact_energy+error_threshold/1000, exact_energy]]) ############################## # Provide your code here optimizer = { 'name': 'QN-SPSA', # leverage the Quantum Natural SPSA # 'name': 'SPSA', # set to ordinary SPSA 'maxiter': 100, } runtime_vqe = ############################## # Submit a runtime job using the following code from qc_grader.challenges.unimelb_2022 import prepare_ex2f runtime_job = prepare_ex2f(runtime_vqe, qubit_converter, es_problem) # Check your answer and submit using the following code from qc_grader.challenges.unimelb_2022 import grade_ex2f grade_ex2f(runtime_job) print(runtime_job.result().get("eigenvalue")) # Please change backend before running the following code runtime_job_real_device = prepare_ex2f(runtime_vqe, qubit_converter, es_problem, real_device=True) print(runtime_job_real_device.result().get("eigenvalue"))
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# General imports import os import gzip import numpy as np import matplotlib.pyplot as plt from pylab import cm import warnings warnings.filterwarnings("ignore") # scikit-learn imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.svm import SVC from sklearn.metrics import accuracy_score # Qiskit imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load MNIST dataset DATA_PATH = './resources/ch3_part1.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Visualize samples fig = plt.figure() LABELS = [4, 9] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(1, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # Standardize ss = StandardScaler() sample_train = ss.fit_transform(sample_train) sample_val = ss.transform(sample_val) sample_test = ss.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) sample_val = pca.transform(sample_val) sample_test = pca.transform(sample_test) # Normalize mms = MinMaxScaler((-1, 1)) sample_train = mms.fit_transform(sample_train) sample_val = mms.transform(sample_val) sample_test = mms.transform(sample_test) # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.decompose().draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.decompose().draw('mpl') # 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.decompose().draw('mpl') # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.decompose().draw('mpl') twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.decompose().draw('mpl') twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.decompose().draw('mpl') print(f'First training data: {sample_train[0]}') encode_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.decompose().draw(output='mpl') ############################## # Provide your code here ex3a_fmap = ZZFeatureMap(feature_dimension=5, reps=3, entanglement='circular') ############################## # Check your answer and submit using the following code from qc_grader import grade_ex3a grade_ex3a(ex3a_fmap) pauli_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) pauli_kernel = QuantumKernel(feature_map=pauli_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(f'First training data : {sample_train[0]}') print(f'Second training data: {sample_train[1]}') pauli_circuit = pauli_kernel.construct_circuit(sample_train[0], sample_train[1]) pauli_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(pauli_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(pauli_circuit) print(f"Transition amplitude: {counts['0'*N_DIM]/sum(counts.values())}") matrix_train = pauli_kernel.evaluate(x_vec=sample_train) matrix_val = pauli_kernel.evaluate(x_vec=sample_val, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_val), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("validation kernel matrix") plt.show() x = [-0.5, -0.4, 0.3, 0, -0.9] y = [0, -0.7, -0.3, 0, -0.4] ############################## # Provide your code here zz = ZZFeatureMap(feature_dimension=N_DIM, reps=3, entanglement='circular') zz_kernel = QuantumKernel(feature_map=zz, quantum_instance=Aer.get_backend('statevector_simulator')) zz_circuit = zz_kernel.construct_circuit(x, y) backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) ex3b_amp = counts['0'*N_DIM]/sum(counts.values()) ############################## # Check your answer and submit using the following code from qc_grader import grade_ex3b grade_ex3b(ex3b_amp) pauli_svc = SVC(kernel='precomputed') pauli_svc.fit(matrix_train, labels_train) pauli_score = pauli_svc.score(matrix_val, labels_val) print(f'Precomputed kernel classification test score: {pauli_score*100}%') # Load MNIST dataset DATA_PATH = './resources/ch3_part2.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Visualize samples fig = plt.figure() LABELS = [0, 2, 3] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(1, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # Standardize standard_scaler = StandardScaler() sample_train = standard_scaler.fit_transform(sample_train) sample_val = standard_scaler.transform(sample_val) sample_test = standard_scaler.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) sample_val = pca.transform(sample_val) sample_test = pca.transform(sample_test) # Normalize min_max_scaler = MinMaxScaler((-1, 1)) sample_train = min_max_scaler.fit_transform(sample_train) sample_val = min_max_scaler.transform(sample_val) sample_test = min_max_scaler.transform(sample_test) labels_train_0 = np.where(labels_train==0, 1, 0) labels_val_0 = np.where(labels_val==0, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 0 vs Rest: {labels_val_0}') labels_train_2 = np.where(labels_train==2, 1, 0) labels_val_2 = np.where(labels_val==2, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 2 vs Rest: {labels_val_2}') labels_train_3 = np.where(labels_train==3, 1, 0) labels_val_3 = np.where(labels_val==3, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 2 vs Rest: {labels_val_3}') pauli_map_0 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement = 'linear') pauli_kernel_0 = QuantumKernel(feature_map=pauli_map_0, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_0 = SVC(kernel='precomputed', probability=True) matrix_train_0 = pauli_kernel_0.evaluate(x_vec=sample_train) pauli_svc_0.fit(matrix_train_0, labels_train_0) matrix_val_0 = pauli_kernel_0.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_0 = pauli_svc_0.score(matrix_val_0, labels_val_0) print(f'Accuracy of discriminating between label 0 and others: {pauli_score_0*100}%') pauli_map_2 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement='linear') pauli_kernel_2 = QuantumKernel(feature_map=pauli_map_2, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_2 = SVC(kernel='precomputed', probability=True) matrix_train_2 = pauli_kernel_2.evaluate(x_vec=sample_train) pauli_svc_2.fit(matrix_train_2, labels_train_2) matrix_val_2 = pauli_kernel_2.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_2 = pauli_svc_2.score(matrix_val_2, labels_val_2) print(f'Accuracy of discriminating between label 2 and others: {pauli_score_2*100}%') pauli_map_3 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement = 'linear') pauli_kernel_3 = QuantumKernel(feature_map=pauli_map_3, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_3 = SVC(kernel='precomputed', probability=True) matrix_train_3 = pauli_kernel_3.evaluate(x_vec=sample_train) pauli_svc_3.fit(matrix_train_3, labels_train_3) matrix_val_3 = pauli_kernel_3.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_3 = pauli_svc_3.score(matrix_val_3, labels_val_3) print(f'Accuracy of discriminating between label 3 and others: {pauli_score_3*100}%') matrix_test_0 = pauli_kernel_0.evaluate(x_vec=sample_test, y_vec=sample_train) pred_0 = pauli_svc_0.predict_proba(matrix_test_0)[:, 1] print(f'Probability of label 0: {np.round(pred_0, 2)}') matrix_test_2 = pauli_kernel_2.evaluate(x_vec=sample_test, y_vec=sample_train) pred_2 = pauli_svc_2.predict_proba(matrix_test_2)[:, 1] print(f'Probability of label 2: {np.round(pred_2, 2)}') matrix_test_3 = pauli_kernel_3.evaluate(x_vec=sample_test, y_vec=sample_train) pred_3 = pauli_svc_3.predict_proba(matrix_test_3)[:, 1] print(f'Probability of label 3: {np.round(pred_3, 2)}') ############################## # Provide your code here pred_2 = pauli_svc_2.predict_proba(matrix_test_2)[:, 1] ############################## ############################## # Provide your code here pred_3 = pauli_svc_3.predict_proba(matrix_test_3)[:, 1] ############################## sample_pred = np.load('./resources/ch3_part2_sub.npy') print(f'Sample prediction: {sample_pred}') pred_2_ex = np.array([0.7]) pred_3_ex = np.array([0.2]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}') pred_2_ex = np.array([0.7, 0.1]) pred_3_ex = np.array([0.2, 0.6]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}') ############################## # Provide your code here prob_0 = np.array(np.round(pred_0,2)) prob_2 = np.array(np.round(pred_2,2)) prob_3 = np.array(np.round(pred_3,2)) def pred(pred_0, pred_2, pred_3): prediction=[] for i in range(len(pred_0)): if pred_0[i]>pred_2[i] and pred_0[i]>pred_3[i]: prediction.append(0) elif pred_2[i]>pred_0[i] and pred_2[i]>pred_3[i]: prediction.append(2) else: prediction.append(3) return np.array(prediction) test = pred(prob_0, prob_2, prob_3) pred_test = np.array(test) print(pred_test) ############################## print(f'Sample prediction: {sample_pred}') # Check your answer and submit using the following code from qc_grader import grade_ex3c grade_ex3c(pred_test, sample_train, standard_scaler, pca, min_max_scaler, pauli_kernel_0, pauli_kernel_2, pauli_kernel_3, pauli_svc_0, pauli_svc_2, pauli_svc_3)